blob: fff714cb6aa96d3254a01dff2bf1b3d3c96be6e5 [file] [log] [blame]
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001//===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
Chris Lattnerddc135e2006-11-10 06:34:16 +00002//
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"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000016#include "clang/AST/APValue.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/ASTMutationListener.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000018#include "clang/AST/ASTTypeTraits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Attr.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000020#include "clang/AST/AttrIterator.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000021#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000022#include "clang/AST/Comment.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000023#include "clang/AST/Decl.h"
24#include "clang/AST/DeclBase.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000025#include "clang/AST/DeclCXX.h"
Chandler Carruthaa36b892015-12-30 03:40:23 +000026#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000027#include "clang/AST/DeclObjC.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000028#include "clang/AST/DeclOpenMP.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000029#include "clang/AST/DeclTemplate.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000030#include "clang/AST/DeclarationName.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000031#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000032#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000033#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000034#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000035#include "clang/AST/MangleNumberingContext.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000036#include "clang/AST/NestedNameSpecifier.h"
37#include "clang/AST/RawCommentList.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000038#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000039#include "clang/AST/RecursiveASTVisitor.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000040#include "clang/AST/Stmt.h"
41#include "clang/AST/TemplateBase.h"
42#include "clang/AST/TemplateName.h"
43#include "clang/AST/Type.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000044#include "clang/AST/TypeLoc.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000045#include "clang/AST/UnresolvedSet.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000046#include "clang/AST/VTableBuilder.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000047#include "clang/Basic/AddressSpaces.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000048#include "clang/Basic/Builtins.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000049#include "clang/Basic/CommentOptions.h"
50#include "clang/Basic/IdentifierTable.h"
51#include "clang/Basic/LLVM.h"
52#include "clang/Basic/LangOptions.h"
53#include "clang/Basic/Linkage.h"
54#include "clang/Basic/ObjCRuntime.h"
55#include "clang/Basic/SanitizerBlacklist.h"
56#include "clang/Basic/SourceLocation.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000057#include "clang/Basic/SourceManager.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000058#include "clang/Basic/Specifiers.h"
59#include "clang/Basic/TargetCXXABI.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000060#include "clang/Basic/TargetInfo.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000061#include "clang/Basic/XRayLists.h"
62#include "llvm/ADT/APInt.h"
63#include "llvm/ADT/APSInt.h"
64#include "llvm/ADT/ArrayRef.h"
65#include "llvm/ADT/DenseMap.h"
66#include "llvm/ADT/DenseSet.h"
67#include "llvm/ADT/FoldingSet.h"
68#include "llvm/ADT/None.h"
69#include "llvm/ADT/Optional.h"
70#include "llvm/ADT/PointerUnion.h"
71#include "llvm/ADT/STLExtras.h"
72#include "llvm/ADT/SmallPtrSet.h"
73#include "llvm/ADT/SmallVector.h"
Anders Carlssond8499822007-10-29 05:01:08 +000074#include "llvm/ADT/StringExtras.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000075#include "llvm/ADT/StringRef.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000076#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000077#include "llvm/Support/Capacity.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000078#include "llvm/Support/Casting.h"
79#include "llvm/Support/Compiler.h"
80#include "llvm/Support/ErrorHandling.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000081#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000082#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000083#include <algorithm>
84#include <cassert>
85#include <cstddef>
86#include <cstdint>
87#include <cstdlib>
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000088#include <map>
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000089#include <memory>
90#include <string>
91#include <tuple>
92#include <utility>
Anders Carlssona4267a62009-07-18 21:19:52 +000093
Chris Lattnerddc135e2006-11-10 06:34:16 +000094using namespace clang;
95
Douglas Gregor9672f922010-07-03 00:47:00 +000096unsigned ASTContext::NumImplicitDefaultConstructors;
97unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000098unsigned ASTContext::NumImplicitCopyConstructors;
99unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +0000100unsigned ASTContext::NumImplicitMoveConstructors;
101unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000102unsigned ASTContext::NumImplicitCopyAssignmentOperators;
103unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +0000104unsigned ASTContext::NumImplicitMoveAssignmentOperators;
105unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +0000106unsigned ASTContext::NumImplicitDestructors;
107unsigned ASTContext::NumImplicitDestructorsDeclared;
108
Steve Naroff0af91202007-04-27 21:51:21 +0000109enum FloatingRank {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +0000110 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +0000111};
112
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000113RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000114 if (!CommentsLoaded && ExternalSource) {
115 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +0000116
117#ifndef NDEBUG
118 ArrayRef<RawComment *> RawComments = Comments.getComments();
119 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
120 BeforeThanCompare<RawComment>(SourceMgr)));
121#endif
122
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000123 CommentsLoaded = true;
124 }
125
126 assert(D);
127
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000128 // User can not attach documentation to implicit declarations.
129 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +0000130 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000131
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000132 // User can not attach documentation to implicit instantiations.
133 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
134 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000135 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000136 }
137
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000138 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
139 if (VD->isStaticDataMember() &&
140 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000141 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000142 }
143
144 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
145 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000146 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000147 }
148
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000149 if (const ClassTemplateSpecializationDecl *CTSD =
150 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
151 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
152 if (TSK == TSK_ImplicitInstantiation ||
153 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000154 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000155 }
156
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000157 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
158 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000159 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000160 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000161 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
162 // When tag declaration (but not definition!) is part of the
163 // decl-specifier-seq of some other declaration, it doesn't get comment
164 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000165 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000166 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 // TODO: handle comments for function parameters properly.
168 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000169 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000170
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000171 // TODO: we could look up template parameter documentation in the template
172 // documentation.
173 if (isa<TemplateTypeParmDecl>(D) ||
174 isa<NonTypeTemplateParmDecl>(D) ||
175 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000176 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000177
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000178 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000179
180 // If there are no comments anywhere, we won't find anything.
181 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000182 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000183
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000184 // Find declaration location.
185 // For Objective-C declarations we generally don't expect to have multiple
186 // declarators, thus use declaration starting location as the "declaration
187 // location".
188 // For all other declarations multiple declarators are used quite frequently,
189 // so we use the location of the identifier as the "declaration location".
190 SourceLocation DeclLoc;
191 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000192 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000193 isa<RedeclarableTemplateDecl>(D) ||
194 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000195 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000196 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000197 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000198 if (DeclLoc.isMacroID()) {
199 if (isa<TypedefDecl>(D)) {
200 // If location of the typedef name is in a macro, it is because being
201 // declared via a macro. Try using declaration's starting location as
202 // the "declaration location".
203 DeclLoc = D->getLocStart();
204 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
205 // If location of the tag decl is inside a macro, but the spelling of
206 // the tag name comes from a macro argument, it looks like a special
207 // macro like NS_ENUM is being used to define the tag decl. In that
208 // case, adjust the source location to the expansion loc so that we can
209 // attach the comment to the tag decl.
210 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
211 TD->isCompleteDefinition())
212 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
213 }
214 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000215 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000216
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000217 // If the declaration doesn't map directly to a location in a file, we
218 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000219 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000220 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000221
222 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000223 ArrayRef<RawComment *>::iterator Comment;
224 {
225 // When searching for comments during parsing, the comment we are looking
226 // for is usually among the last two comments we parsed -- check them
227 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000228 RawComment CommentAtDeclLoc(
229 SourceMgr, SourceRange(DeclLoc), false,
230 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000231 BeforeThanCompare<RawComment> Compare(SourceMgr);
232 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
233 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
234 if (!Found && RawComments.size() >= 2) {
235 MaybeBeforeDecl--;
236 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
237 }
238
239 if (Found) {
240 Comment = MaybeBeforeDecl + 1;
241 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
242 &CommentAtDeclLoc, Compare));
243 } else {
244 // Slow path.
245 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
246 &CommentAtDeclLoc, Compare);
247 }
248 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000249
250 // Decompose the location for the declaration and find the beginning of the
251 // file buffer.
252 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
253
254 // First check whether we have a trailing comment.
255 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000256 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000257 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000258 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000259 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000260 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000261 // Check that Doxygen trailing comment comes after the declaration, starts
262 // on the same line and in the same file as the declaration.
263 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
264 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
265 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
266 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000267 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000268 }
269 }
270
271 // The comment just after the declaration was not a trailing comment.
272 // Let's look at the previous comment.
273 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000274 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000275 --Comment;
276
277 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000278 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000279 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000280
281 // Decompose the end of the comment.
282 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000283 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000284
285 // If the comment and the declaration aren't in the same file, then they
286 // aren't related.
287 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000288 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000289
290 // Get the corresponding buffer.
291 bool Invalid = false;
292 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
293 &Invalid).data();
294 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000295 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000296
297 // Extract text between the comment and declaration.
298 StringRef Text(Buffer + CommentEndDecomp.second,
299 DeclLocDecomp.second - CommentEndDecomp.second);
300
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000301 // There should be no other declarations or preprocessor directives between
302 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000303 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000304 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000305
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000306 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000307}
308
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000309/// If we have a 'templated' declaration for a template, adjust 'D' to
310/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000311/// If we have an implicit instantiation, adjust 'D' to refer to template.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000312static const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000313 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000314 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000315 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000316 return FTD;
317
318 // Nothing to do if function is not an implicit instantiation.
319 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
320 return D;
321
322 // Function is an implicit instantiation of a function template?
323 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
324 return FTD;
325
326 // Function is instantiated from a member definition of a class template?
327 if (const FunctionDecl *MemberDecl =
328 FD->getInstantiatedFromMemberFunction())
329 return MemberDecl;
330
331 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000332 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000333 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
334 // Static data member is instantiated from a member definition of a class
335 // template?
336 if (VD->isStaticDataMember())
337 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
338 return MemberDecl;
339
340 return D;
341 }
342 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
343 // Is this class declaration part of a class template?
344 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
345 return CTD;
346
347 // Class is an implicit instantiation of a class template or partial
348 // specialization?
349 if (const ClassTemplateSpecializationDecl *CTSD =
350 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
351 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
352 return D;
353 llvm::PointerUnion<ClassTemplateDecl *,
354 ClassTemplatePartialSpecializationDecl *>
355 PU = CTSD->getSpecializedTemplateOrPartial();
356 return PU.is<ClassTemplateDecl*>() ?
357 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
358 static_cast<const Decl*>(
359 PU.get<ClassTemplatePartialSpecializationDecl *>());
360 }
361
362 // Class is instantiated from a member definition of a class template?
363 if (const MemberSpecializationInfo *Info =
364 CRD->getMemberSpecializationInfo())
365 return Info->getInstantiatedFrom();
366
367 return D;
368 }
369 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
370 // Enum is instantiated from a member definition of a class template?
371 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
372 return MemberDecl;
373
374 return D;
375 }
376 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000377 return D;
378}
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000379
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000380const RawComment *ASTContext::getRawCommentForAnyRedecl(
381 const Decl *D,
382 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000383 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000384
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000385 // Check whether we have cached a comment for this declaration already.
386 {
387 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
388 RedeclComments.find(D);
389 if (Pos != RedeclComments.end()) {
390 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000391 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
392 if (OriginalDecl)
393 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000394 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000395 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000396 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000397 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000398
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000399 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000400 const RawComment *RC = nullptr;
401 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000402 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000403 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000404 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000405 if (Pos != RedeclComments.end()) {
406 const RawCommentAndCacheFlags &Raw = Pos->second;
407 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
408 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000409 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000410 break;
411 }
412 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000413 RC = getRawCommentForDeclNoCache(I);
414 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000415 RawCommentAndCacheFlags Raw;
416 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000417 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
418 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000419 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000420 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000421 } else
422 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000423 Raw.setOriginalDecl(I);
424 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000425 if (RC)
426 break;
427 }
428 }
429
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000430 // If we found a comment, it should be a documentation comment.
431 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000432
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000433 if (OriginalDecl)
434 *OriginalDecl = OriginalDeclForRC;
435
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000436 // Update cache for every declaration in the redeclaration chain.
437 RawCommentAndCacheFlags Raw;
438 Raw.setRaw(RC);
439 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000440 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000441
Aaron Ballman86c93902014-03-06 23:45:36 +0000442 for (auto I : D->redecls()) {
443 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000444 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
445 R = Raw;
446 }
447
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000448 return RC;
449}
450
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000451static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
452 SmallVectorImpl<const NamedDecl *> &Redeclared) {
453 const DeclContext *DC = ObjCMethod->getDeclContext();
454 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
455 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
456 if (!ID)
457 return;
458 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000459 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000460 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000461 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000462 ObjCMethod->isInstanceMethod()))
463 Redeclared.push_back(RedeclaredMethod);
464 }
465 }
466}
467
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000468comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
469 const Decl *D) const {
470 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
471 ThisDeclInfo->CommentDecl = D;
472 ThisDeclInfo->IsFilled = false;
473 ThisDeclInfo->fill();
474 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000475 if (!ThisDeclInfo->TemplateParameters)
476 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000477 comments::FullComment *CFC =
478 new (*this) comments::FullComment(FC->getBlocks(),
479 ThisDeclInfo);
480 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000481}
482
Richard Smithb39b9d52013-05-21 05:24:00 +0000483comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
484 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000485 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000486}
487
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000488comments::FullComment *ASTContext::getCommentForDecl(
489 const Decl *D,
490 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000491 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000492 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000493 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000494
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000495 const Decl *Canonical = D->getCanonicalDecl();
496 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
497 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000498
499 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000500 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000501 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000502 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000503 return CFC;
504 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000505 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000506 }
507
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000508 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000509
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000510 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000511 if (!RC) {
512 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000513 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000514 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000515 if (OMD && OMD->isPropertyAccessor())
516 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
517 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
518 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000519 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000520 addRedeclaredMethods(OMD, Overridden);
521 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000522 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
523 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
524 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000525 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000526 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000527 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000528 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000529 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000530 if (const TagType *TT = QT->getAs<TagType>())
531 if (const Decl *TD = TT->getDecl())
532 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000533 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000534 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000535 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
536 while (IC->getSuperClass()) {
537 IC = IC->getSuperClass();
538 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
539 return cloneFullComment(FC, D);
540 }
541 }
542 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
543 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
544 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
545 return cloneFullComment(FC, D);
546 }
547 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
548 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000549 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000550 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000551 for (const auto &I : RD->bases()) {
552 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000553 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000554 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000555 if (Ty.isNull())
556 continue;
557 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
558 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
559 continue;
560
561 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
562 return cloneFullComment(FC, D);
563 }
564 }
565 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000566 for (const auto &I : RD->vbases()) {
567 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000568 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000569 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000570 if (Ty.isNull())
571 continue;
572 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
573 if (!(VirtualBase= VirtualBase->getDefinition()))
574 continue;
575 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
576 return cloneFullComment(FC, D);
577 }
578 }
579 }
Craig Topper36250ad2014-05-12 05:36:57 +0000580 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000581 }
582
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000583 // If the RawComment was attached to other redeclaration of this Decl, we
584 // should parse the comment in context of that other Decl. This is important
585 // because comments can contain references to parameter names which can be
586 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000587 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000588 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000589
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000590 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000591 ParsedComments[Canonical] = FC;
592 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000593}
594
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000595void
596ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
597 TemplateTemplateParmDecl *Parm) {
598 ID.AddInteger(Parm->getDepth());
599 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000600 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000601
602 TemplateParameterList *Params = Parm->getTemplateParameters();
603 ID.AddInteger(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 ID.AddInteger(0);
609 ID.AddBoolean(TTP->isParameterPack());
610 continue;
611 }
612
613 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
614 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000615 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000616 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000617 if (NTTP->isExpandedParameterPack()) {
618 ID.AddBoolean(true);
619 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000620 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
621 QualType T = NTTP->getExpansionType(I);
622 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
623 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000624 } else
625 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000626 continue;
627 }
628
629 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
630 ID.AddInteger(2);
631 Profile(ID, TTP);
632 }
633}
634
635TemplateTemplateParmDecl *
636ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000637 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000638 // Check if we already have a canonical template template parameter.
639 llvm::FoldingSetNodeID ID;
640 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000641 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000642 CanonicalTemplateTemplateParm *Canonical
643 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
644 if (Canonical)
645 return Canonical->getParam();
646
647 // Build a canonical template parameter list.
648 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000649 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000650 CanonParams.reserve(Params->size());
651 for (TemplateParameterList::const_iterator P = Params->begin(),
652 PEnd = Params->end();
653 P != PEnd; ++P) {
654 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
655 CanonParams.push_back(
656 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000657 SourceLocation(),
658 SourceLocation(),
659 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000660 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000661 TTP->isParameterPack()));
662 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000663 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
664 QualType T = getCanonicalType(NTTP->getType());
665 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
666 NonTypeTemplateParmDecl *Param;
667 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000668 SmallVector<QualType, 2> ExpandedTypes;
669 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000670 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
671 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
672 ExpandedTInfos.push_back(
673 getTrivialTypeSourceInfo(ExpandedTypes.back()));
674 }
675
676 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000677 SourceLocation(),
678 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000679 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000680 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000681 T,
682 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000683 ExpandedTypes,
684 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000685 } else {
686 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000687 SourceLocation(),
688 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000689 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000690 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000691 T,
692 NTTP->isParameterPack(),
693 TInfo);
694 }
695 CanonParams.push_back(Param);
696
697 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000698 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
699 cast<TemplateTemplateParmDecl>(*P)));
700 }
701
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000702 assert(!TTP->getRequiresClause() &&
703 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000704 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000705
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000706 TemplateTemplateParmDecl *CanonTTP
707 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
708 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000709 TTP->getPosition(),
710 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000711 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000712 TemplateParameterList::Create(*this, SourceLocation(),
713 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000714 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000715 SourceLocation(),
716 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000717
718 // Get the new insert position for the node we care about.
719 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000720 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000721 (void)Canonical;
722
723 // Create the canonical template template parameter entry.
724 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
725 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
726 return CanonTTP;
727}
728
Charles Davis53c59df2010-08-16 03:33:14 +0000729CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000730 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000731
John McCall359b8852013-01-25 22:30:49 +0000732 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000733 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000734 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000735 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000736 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000737 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000738 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000739 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000740 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000741 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000742 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000743 return CreateMicrosoftCXXABI(*this);
744 }
David Blaikie8a40f702012-01-17 06:56:22 +0000745 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000746}
747
Alexander Richardson6d989432017-10-15 18:48:14 +0000748static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
749 const LangOptions &LOpts) {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000750 if (LOpts.FakeAddressSpaceMap) {
751 // The fake address space map must have a distinct entry for each
752 // language-specific address space.
753 static const unsigned FakeAddrSpaceMap[] = {
Yaxun Liub34ec822017-04-11 17:24:23 +0000754 0, // Default
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000755 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000756 3, // opencl_local
757 2, // opencl_constant
Yaxun Liub7318e02017-10-13 03:37:48 +0000758 0, // opencl_private
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000759 4, // opencl_generic
760 5, // cuda_device
761 6, // cuda_constant
762 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000763 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000764 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000765 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000766 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000767 }
768}
769
David Tweed31d09b02013-09-13 12:04:22 +0000770static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
771 const LangOptions &LangOpts) {
772 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000773 case LangOptions::ASMM_Target:
774 return TI.useAddressSpaceMapMangling();
775 case LangOptions::ASMM_On:
776 return true;
777 case LangOptions::ASMM_Off:
778 return false;
779 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000780 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000781}
782
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000783ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000784 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000785 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000786 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
787 DependentTemplateSpecializationTypes(this_()),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000788 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000789 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000790 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
791 LangOpts.XRayNeverInstrumentFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000792 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000793 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000794 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000795 TUDecl = TranslationUnitDecl::Create(*this);
796}
797
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000798ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000799 ReleaseParentMapEntries();
800
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000801 // Release the DenseMaps associated with DeclContext objects.
802 // FIXME: Is this the ideal solution?
803 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000804
Manuel Klimeka7328992013-06-03 13:51:33 +0000805 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000806 for (auto &Pair : Deallocations)
807 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000808
Ted Kremenek076baeb2010-06-08 23:00:58 +0000809 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000810 // because they can contain DenseMaps.
811 for (llvm::DenseMap<const ObjCContainerDecl*,
812 const ASTRecordLayout*>::iterator
813 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
814 // Increment in loop to prevent using deallocated memory.
815 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
816 R->Destroy(*this);
817
Ted Kremenek076baeb2010-06-08 23:00:58 +0000818 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
819 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
820 // Increment in loop to prevent using deallocated memory.
821 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
822 R->Destroy(*this);
823 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000824
825 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
826 AEnd = DeclAttrs.end();
827 A != AEnd; ++A)
828 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000829
David Majnemere694f3e2015-08-14 14:43:50 +0000830 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
831 MaterializedTemporaryValues)
832 MTVPair.second->~APValue();
833
Richard Smith423f46f2016-07-20 21:38:26 +0000834 for (const auto &Value : ModuleInitializers)
835 Value.second->~PerModuleInitializers();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000836}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000837
Manuel Klimek95403e62014-05-21 13:28:59 +0000838void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000839 if (!PointerParents) return;
840 for (const auto &Entry : *PointerParents) {
841 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
842 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
843 } else if (Entry.second.is<ParentVector *>()) {
844 delete Entry.second.get<ParentVector *>();
845 }
846 }
847 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000848 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
849 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000850 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000851 delete Entry.second.get<ParentVector *>();
852 }
853 }
854}
855
Douglas Gregor1a809332010-05-23 18:26:36 +0000856void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000857 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000858}
859
Mike Stump11289f42009-09-09 15:08:12 +0000860void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000861ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000862 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000863}
864
Chris Lattner4eb445d2007-01-26 01:27:23 +0000865void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000866 llvm::errs() << "\n*** AST Context Stats:\n";
867 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000868
Douglas Gregora30d0462009-05-26 14:40:08 +0000869 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000870#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000871#define ABSTRACT_TYPE(Name, Parent)
872#include "clang/AST/TypeNodes.def"
873 0 // Extra
874 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000875
Chris Lattner4eb445d2007-01-26 01:27:23 +0000876 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
877 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000878 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000879 }
880
Douglas Gregora30d0462009-05-26 14:40:08 +0000881 unsigned Idx = 0;
882 unsigned TotalBytes = 0;
883#define TYPE(Name, Parent) \
884 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000885 llvm::errs() << " " << counts[Idx] << " " << #Name \
886 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000887 TotalBytes += counts[Idx] * sizeof(Name##Type); \
888 ++Idx;
889#define ABSTRACT_TYPE(Name, Parent)
890#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000891
Chandler Carruth3c147a72011-07-04 05:32:14 +0000892 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
893
Douglas Gregor7454c562010-07-02 20:37:36 +0000894 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000895 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
896 << NumImplicitDefaultConstructors
897 << " implicit default constructors created\n";
898 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
899 << NumImplicitCopyConstructors
900 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000901 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000902 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
903 << NumImplicitMoveConstructors
904 << " implicit move constructors created\n";
905 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
906 << NumImplicitCopyAssignmentOperators
907 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000908 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000909 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
910 << NumImplicitMoveAssignmentOperators
911 << " implicit move assignment operators created\n";
912 llvm::errs() << NumImplicitDestructorsDeclared << "/"
913 << NumImplicitDestructors
914 << " implicit destructors created\n";
915
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000916 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000917 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000918 ExternalSource->PrintStats();
919 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000920
Douglas Gregor5b11d492010-07-25 17:53:33 +0000921 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000922}
923
Richard Smith42413142015-05-15 20:05:43 +0000924void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
925 bool NotifyListeners) {
926 if (NotifyListeners)
927 if (auto *Listener = getASTMutationListener())
928 Listener->RedefinedHiddenDefinition(ND, M);
929
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000930 if (getLangOpts().ModulesLocalVisibility)
931 MergedDefModules[ND].push_back(M);
932 else
Richard Smith90dc5252017-06-23 01:04:34 +0000933 ND->setVisibleDespiteOwningModule();
Richard Smith42413142015-05-15 20:05:43 +0000934}
935
936void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
937 auto It = MergedDefModules.find(ND);
938 if (It == MergedDefModules.end())
939 return;
940
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000941 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000942 llvm::DenseSet<Module*> Found;
943 for (Module *&M : Merged)
944 if (!Found.insert(M).second)
945 M = nullptr;
946 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
947}
948
Richard Smithdc1f0422016-07-20 19:10:16 +0000949void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
950 if (LazyInitializers.empty())
951 return;
952
953 auto *Source = Ctx.getExternalSource();
954 assert(Source && "lazy initializers but no external source");
955
956 auto LazyInits = std::move(LazyInitializers);
957 LazyInitializers.clear();
958
959 for (auto ID : LazyInits)
960 Initializers.push_back(Source->GetExternalDecl(ID));
961
962 assert(LazyInitializers.empty() &&
963 "GetExternalDecl for lazy module initializer added more inits");
964}
965
966void ASTContext::addModuleInitializer(Module *M, Decl *D) {
967 // One special case: if we add a module initializer that imports another
968 // module, and that module's only initializer is an ImportDecl, simplify.
969 if (auto *ID = dyn_cast<ImportDecl>(D)) {
970 auto It = ModuleInitializers.find(ID->getImportedModule());
971
972 // Maybe the ImportDecl does nothing at all. (Common case.)
973 if (It == ModuleInitializers.end())
974 return;
975
976 // Maybe the ImportDecl only imports another ImportDecl.
977 auto &Imported = *It->second;
978 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
979 Imported.resolve(*this);
980 auto *OnlyDecl = Imported.Initializers.front();
981 if (isa<ImportDecl>(OnlyDecl))
982 D = OnlyDecl;
983 }
984 }
985
986 auto *&Inits = ModuleInitializers[M];
987 if (!Inits)
988 Inits = new (*this) PerModuleInitializers;
989 Inits->Initializers.push_back(D);
990}
991
992void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
993 auto *&Inits = ModuleInitializers[M];
994 if (!Inits)
995 Inits = new (*this) PerModuleInitializers;
996 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
997 IDs.begin(), IDs.end());
998}
999
1000ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) {
1001 auto It = ModuleInitializers.find(M);
1002 if (It == ModuleInitializers.end())
1003 return None;
1004
1005 auto *Inits = It->second;
1006 Inits->resolve(*this);
1007 return Inits->Initializers;
1008}
1009
Richard Smithf19e1272015-03-07 00:04:49 +00001010ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1011 if (!ExternCContext)
1012 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1013
1014 return ExternCContext;
1015}
1016
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001017BuiltinTemplateDecl *
1018ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1019 const IdentifierInfo *II) const {
1020 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1021 BuiltinTemplate->setImplicit();
1022 TUDecl->addDecl(BuiltinTemplate);
1023
1024 return BuiltinTemplate;
1025}
1026
1027BuiltinTemplateDecl *
1028ASTContext::getMakeIntegerSeqDecl() const {
1029 if (!MakeIntegerSeqDecl)
1030 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1031 getMakeIntegerSeqName());
1032 return MakeIntegerSeqDecl;
1033}
1034
Eric Fiselier6ad68552016-07-01 01:24:09 +00001035BuiltinTemplateDecl *
1036ASTContext::getTypePackElementDecl() const {
1037 if (!TypePackElementDecl)
1038 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1039 getTypePackElementName());
1040 return TypePackElementDecl;
1041}
1042
Alp Toker2dea15b2013-12-17 01:22:38 +00001043RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1044 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001045 SourceLocation Loc;
1046 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001047 if (getLangOpts().CPlusPlus)
1048 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1049 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001050 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001051 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1052 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001053 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001054 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1055 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001056 return NewDecl;
1057}
1058
1059TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1060 StringRef Name) const {
1061 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1062 TypedefDecl *NewDecl = TypedefDecl::Create(
1063 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1064 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1065 NewDecl->setImplicit();
1066 return NewDecl;
1067}
1068
Douglas Gregor801c99d2011-08-12 06:49:56 +00001069TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001070 if (!Int128Decl)
1071 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001072 return Int128Decl;
1073}
1074
1075TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001076 if (!UInt128Decl)
1077 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001078 return UInt128Decl;
1079}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001080
John McCall48f2d582009-10-23 23:03:21 +00001081void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +00001082 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001083 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001084 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001085}
1086
Artem Belevichb5bc9232015-09-22 17:23:22 +00001087void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1088 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001089 assert((!this->Target || this->Target == &Target) &&
1090 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001091 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001092
Douglas Gregore8bbc122011-09-02 00:18:52 +00001093 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001094 this->AuxTarget = AuxTarget;
1095
Douglas Gregore8bbc122011-09-02 00:18:52 +00001096 ABI.reset(createCXXABI(Target));
1097 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001098 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001099
Chris Lattner970e54e2006-11-12 00:37:36 +00001100 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001101 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001102
Chris Lattner970e54e2006-11-12 00:37:36 +00001103 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001104 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001105 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001106 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001107 InitBuiltinType(CharTy, BuiltinType::Char_S);
1108 else
1109 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001110 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001111 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1112 InitBuiltinType(ShortTy, BuiltinType::Short);
1113 InitBuiltinType(IntTy, BuiltinType::Int);
1114 InitBuiltinType(LongTy, BuiltinType::Long);
1115 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001116
Chris Lattner970e54e2006-11-12 00:37:36 +00001117 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001118 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1119 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1120 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1121 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1122 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001123
Chris Lattner970e54e2006-11-12 00:37:36 +00001124 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001125 InitBuiltinType(FloatTy, BuiltinType::Float);
1126 InitBuiltinType(DoubleTy, BuiltinType::Double);
1127 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001128
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001129 // GNU extension, __float128 for IEEE quadruple precision
1130 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1131
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001132 // C11 extension ISO/IEC TS 18661-3
1133 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1134
Chris Lattnerf122cef2009-04-30 02:43:43 +00001135 // GNU extension, 128-bit integers.
1136 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1137 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1138
Hans Wennborg0d81e012013-05-10 10:08:40 +00001139 // C++ 3.9.1p5
1140 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1141 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1142 else // -fshort-wchar makes wchar_t be unsigned.
1143 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1144 if (LangOpts.CPlusPlus && LangOpts.WChar)
1145 WideCharTy = WCharTy;
1146 else {
1147 // C99 (or C++ using -fno-wchar).
1148 WideCharTy = getFromTargetType(Target.getWCharType());
1149 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001150
James Molloy36365542012-05-04 10:55:22 +00001151 WIntTy = getFromTargetType(Target.getWIntType());
1152
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001153 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1154 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1155 else // C99
1156 Char16Ty = getFromTargetType(Target.getChar16Type());
1157
1158 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1159 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1160 else // C99
1161 Char32Ty = getFromTargetType(Target.getChar32Type());
1162
Douglas Gregor4619e432008-12-05 23:32:09 +00001163 // Placeholder type for type-dependent expressions whose type is
1164 // completely unknown. No code should ever check a type against
1165 // DependentTy and users should never see it; however, it is here to
1166 // help diagnose failures to properly check for type-dependent
1167 // expressions.
1168 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001169
John McCall36e7fe32010-10-12 00:20:44 +00001170 // Placeholder type for functions.
1171 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1172
John McCall0009fcc2011-04-26 20:42:42 +00001173 // Placeholder type for bound members.
1174 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1175
John McCall526ab472011-10-25 17:37:35 +00001176 // Placeholder type for pseudo-objects.
1177 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1178
John McCall31996342011-04-07 08:22:57 +00001179 // "any" type; useful for debugger-like clients.
1180 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1181
John McCall8a6b59a2011-10-17 18:09:15 +00001182 // Placeholder type for unbridged ARC casts.
1183 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1184
Eli Friedman34866c72012-08-31 00:14:07 +00001185 // Placeholder type for builtin functions.
1186 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1187
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001188 // Placeholder type for OMP array sections.
1189 if (LangOpts.OpenMP)
1190 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1191
Chris Lattner970e54e2006-11-12 00:37:36 +00001192 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001193 FloatComplexTy = getComplexType(FloatTy);
1194 DoubleComplexTy = getComplexType(DoubleTy);
1195 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001196 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001197
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001198 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001199 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1200 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001201 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001202
Alexey Bader954ba212016-04-08 13:40:33 +00001203 if (LangOpts.OpenCL) {
1204#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1205 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001206#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001207
Guy Benyei61054192013-02-07 10:55:47 +00001208 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001209 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001210 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1211 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001212 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001213 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001214
1215 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001216 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1217 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001218
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001219 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001220
1221 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001222
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001223 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001224 if (LangOpts.OpenCLVersion >= 200) {
1225 auto Q = VoidTy.getQualifiers();
1226 Q.setAddressSpace(LangAS::opencl_generic);
1227 VoidPtrTy = getPointerType(getCanonicalType(
1228 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1229 } else {
1230 VoidPtrTy = getPointerType(VoidTy);
1231 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001232
1233 // nullptr type (C++0x 2.14.7)
1234 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001235
1236 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1237 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001238
1239 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001240 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001241}
1242
David Blaikie9c902b52011-09-25 23:23:43 +00001243DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001244 return SourceMgr.getDiagnostics();
1245}
1246
Douglas Gregor561eceb2010-08-30 16:49:28 +00001247AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1248 AttrVec *&Result = DeclAttrs[D];
1249 if (!Result) {
1250 void *Mem = Allocate(sizeof(AttrVec));
1251 Result = new (Mem) AttrVec;
1252 }
1253
1254 return *Result;
1255}
1256
1257/// \brief Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001258void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001259 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1260 if (Pos != DeclAttrs.end()) {
1261 Pos->second->~AttrVec();
1262 DeclAttrs.erase(Pos);
1263 }
1264}
1265
Larisse Voufo39a1e502013-08-06 01:03:05 +00001266// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001267MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001268ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001269 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001270 return getTemplateOrSpecializationInfo(Var)
1271 .dyn_cast<MemberSpecializationInfo *>();
1272}
1273
1274ASTContext::TemplateOrSpecializationInfo
1275ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1276 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1277 TemplateOrInstantiation.find(Var);
1278 if (Pos == TemplateOrInstantiation.end())
1279 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001280
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001281 return Pos->second;
1282}
1283
Mike Stump11289f42009-09-09 15:08:12 +00001284void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001285ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001286 TemplateSpecializationKind TSK,
1287 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001288 assert(Inst->isStaticDataMember() && "Not a static data member");
1289 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001290 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1291 Tmpl, TSK, PointOfInstantiation));
1292}
1293
1294void
1295ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1296 TemplateOrSpecializationInfo TSI) {
1297 assert(!TemplateOrInstantiation[Inst] &&
1298 "Already noted what the variable was instantiated from");
1299 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001300}
1301
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001302FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1303 const FunctionDecl *FD){
1304 assert(FD && "Specialization is 0");
1305 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001306 = ClassScopeSpecializationPattern.find(FD);
1307 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001308 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001309
1310 return Pos->second;
1311}
1312
1313void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1314 FunctionDecl *Pattern) {
1315 assert(FD && "Specialization is 0");
1316 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001317 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001318}
1319
John McCalle61f2ba2009-11-18 02:36:19 +00001320NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001321ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1322 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001323 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001324 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001325
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001326 return Pos->second;
1327}
1328
1329void
Richard Smithd8a9e372016-12-18 21:39:37 +00001330ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001331 assert((isa<UsingDecl>(Pattern) ||
1332 isa<UnresolvedUsingValueDecl>(Pattern) ||
1333 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1334 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001335 assert((isa<UsingDecl>(Inst) ||
1336 isa<UnresolvedUsingValueDecl>(Inst) ||
1337 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1338 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001339 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1340 InstantiatedFromUsingDecl[Inst] = Pattern;
1341}
1342
1343UsingShadowDecl *
1344ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1345 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1346 = InstantiatedFromUsingShadowDecl.find(Inst);
1347 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001348 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001349
1350 return Pos->second;
1351}
1352
1353void
1354ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1355 UsingShadowDecl *Pattern) {
1356 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1357 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001358}
1359
Anders Carlsson5da84842009-09-01 04:26:58 +00001360FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1361 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1362 = InstantiatedFromUnnamedFieldDecl.find(Field);
1363 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001364 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001365
Anders Carlsson5da84842009-09-01 04:26:58 +00001366 return Pos->second;
1367}
1368
1369void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1370 FieldDecl *Tmpl) {
1371 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1372 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1373 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1374 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001375
Anders Carlsson5da84842009-09-01 04:26:58 +00001376 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1377}
1378
Douglas Gregor832940b2010-03-02 23:58:15 +00001379ASTContext::overridden_cxx_method_iterator
1380ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001381 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001382}
1383
1384ASTContext::overridden_cxx_method_iterator
1385ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001386 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001387}
1388
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001389unsigned
1390ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001391 auto Range = overridden_methods(Method);
1392 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001393}
1394
Clement Courbet6ecaec82016-07-05 07:49:31 +00001395ASTContext::overridden_method_range
1396ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001397 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1398 OverriddenMethods.find(Method->getCanonicalDecl());
1399 if (Pos == OverriddenMethods.end())
1400 return overridden_method_range(nullptr, nullptr);
1401 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001402}
1403
Douglas Gregor832940b2010-03-02 23:58:15 +00001404void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1405 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001406 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001407 OverriddenMethods[Method].push_back(Overridden);
1408}
1409
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001410void ASTContext::getOverriddenMethods(
1411 const NamedDecl *D,
1412 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001413 assert(D);
1414
1415 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001416 Overridden.append(overridden_methods_begin(CXXMethod),
1417 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001418 return;
1419 }
1420
1421 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1422 if (!Method)
1423 return;
1424
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001425 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1426 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001427 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001428}
1429
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001430void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1431 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1432 assert(!Import->isFromASTFile() && "Non-local import declaration");
1433 if (!FirstLocalImport) {
1434 FirstLocalImport = Import;
1435 LastLocalImport = Import;
1436 return;
1437 }
1438
1439 LastLocalImport->NextLocalImport = Import;
1440 LastLocalImport = Import;
1441}
1442
Chris Lattner53cfe802007-07-18 17:52:12 +00001443//===----------------------------------------------------------------------===//
1444// Type Sizing and Analysis
1445//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001446
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001447/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1448/// scalar floating point type.
1449const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001450 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001451 assert(BT && "Not a floating point type!");
1452 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001453 default: llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001454 case BuiltinType::Float16:
1455 case BuiltinType::Half:
1456 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001457 case BuiltinType::Float: return Target->getFloatFormat();
1458 case BuiltinType::Double: return Target->getDoubleFormat();
1459 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001460 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001461 }
1462}
1463
Rafael Espindola71eccb32013-08-08 19:53:46 +00001464CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001465 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001466
John McCall94268702010-10-08 18:24:19 +00001467 bool UseAlignAttrOnly = false;
1468 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1469 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001470
John McCall94268702010-10-08 18:24:19 +00001471 // __attribute__((aligned)) can increase or decrease alignment
1472 // *except* on a struct or struct member, where it only increases
1473 // alignment unless 'packed' is also specified.
1474 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001475 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001476 // ignore that possibility; Sema should diagnose it.
1477 if (isa<FieldDecl>(D)) {
1478 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1479 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1480 } else {
1481 UseAlignAttrOnly = true;
1482 }
1483 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001484 else if (isa<FieldDecl>(D))
1485 UseAlignAttrOnly =
1486 D->hasAttr<PackedAttr>() ||
1487 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001488
John McCall4e819612011-01-20 07:57:12 +00001489 // If we're using the align attribute only, just ignore everything
1490 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001491 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001492 // do nothing
John McCall94268702010-10-08 18:24:19 +00001493 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001494 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001495 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001496 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001497 T = RT->getPointeeType();
1498 else
1499 T = getPointerType(RT->getPointeeType());
1500 }
Richard Smithf6d70302014-06-10 23:34:28 +00001501 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001502 if (T->isFunctionType())
1503 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1504 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001505 // Adjust alignments of declarations with array type by the
1506 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001507 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001508 unsigned MinWidth = Target->getLargeArrayMinWidth();
1509 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001510 if (isa<VariableArrayType>(arrayType))
1511 Align = std::max(Align, Target->getLargeArrayAlign());
1512 else if (isa<ConstantArrayType>(arrayType) &&
1513 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1514 Align = std::max(Align, Target->getLargeArrayAlign());
1515 }
John McCall33ddac02011-01-19 10:06:00 +00001516 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001517 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001518 if (BaseT.getQualifiers().hasUnaligned())
1519 Align = Target->getCharWidth();
Ulrich Weigandfa806422013-05-06 16:23:57 +00001520 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001521 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001522 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1523 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001524 }
John McCall4e819612011-01-20 07:57:12 +00001525
1526 // Fields can be subject to extra alignment constraints, like if
1527 // the field is packed, the struct is packed, or the struct has a
1528 // a max-field-alignment constraint (#pragma pack). So calculate
1529 // the actual alignment of the field within the struct, and then
1530 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001531 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1532 const RecordDecl *Parent = Field->getParent();
1533 // We can only produce a sensible answer if the record is valid.
1534 if (!Parent->isInvalidDecl()) {
1535 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001536
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001537 // Start with the record's overall alignment.
1538 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001539
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001540 // Use the GCD of that and the offset within the record.
1541 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1542 if (Offset > 0) {
1543 // Alignment is always a power of 2, so the GCD will be a power of 2,
1544 // which means we get to do this crazy thing instead of Euclid's.
1545 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1546 if (LowBitOfOffset < FieldAlign)
1547 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1548 }
1549
1550 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001551 }
Charles Davis3fc51072010-02-23 04:52:00 +00001552 }
Chris Lattner68061312009-01-24 21:53:27 +00001553 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001554
Ken Dyckcc56c542011-01-15 18:38:59 +00001555 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001556}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001557
John McCallf1249922012-08-21 04:10:00 +00001558// getTypeInfoDataSizeInChars - Return the size of a type, in
1559// chars. If the type is a record, its data size is returned. This is
1560// the size of the memcpy that's performed when assigning this type
1561// using a trivial copy/move assignment operator.
1562std::pair<CharUnits, CharUnits>
1563ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1564 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1565
1566 // In C++, objects can sometimes be allocated into the tail padding
1567 // of a base-class subobject. We decide whether that's possible
1568 // during class layout, so here we can just trust the layout results.
1569 if (getLangOpts().CPlusPlus) {
1570 if (const RecordType *RT = T->getAs<RecordType>()) {
1571 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1572 sizeAndAlign.first = layout.getDataSize();
1573 }
1574 }
1575
1576 return sizeAndAlign;
1577}
1578
Richard Trieu04d2d942013-05-14 21:59:17 +00001579/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1580/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1581std::pair<CharUnits, CharUnits>
1582static getConstantArrayInfoInChars(const ASTContext &Context,
1583 const ConstantArrayType *CAT) {
1584 std::pair<CharUnits, CharUnits> EltInfo =
1585 Context.getTypeInfoInChars(CAT->getElementType());
1586 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001587 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1588 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001589 "Overflow in array type char size evaluation");
1590 uint64_t Width = EltInfo.first.getQuantity() * Size;
1591 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001592 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1593 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001594 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001595 return std::make_pair(CharUnits::fromQuantity(Width),
1596 CharUnits::fromQuantity(Align));
1597}
1598
John McCall87fe5d52010-05-20 01:18:31 +00001599std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001600ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001601 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1602 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001603 TypeInfo Info = getTypeInfo(T);
1604 return std::make_pair(toCharUnitsFromBits(Info.Width),
1605 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001606}
1607
1608std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001609ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001610 return getTypeInfoInChars(T.getTypePtr());
1611}
1612
David Majnemer34b57492014-07-30 01:30:47 +00001613bool ASTContext::isAlignmentRequired(const Type *T) const {
1614 return getTypeInfo(T).AlignIsRequired;
1615}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001616
David Majnemer34b57492014-07-30 01:30:47 +00001617bool ASTContext::isAlignmentRequired(QualType T) const {
1618 return isAlignmentRequired(T.getTypePtr());
1619}
1620
Richard Smithb2f0f052016-10-10 18:54:32 +00001621unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1622 // An alignment on a typedef overrides anything else.
1623 if (auto *TT = T->getAs<TypedefType>())
1624 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1625 return Align;
1626
1627 // If we have an (array of) complete type, we're done.
1628 T = getBaseElementType(T);
1629 if (!T->isIncompleteType())
1630 return getTypeAlign(T);
1631
1632 // If we had an array type, its element type might be a typedef
1633 // type with an alignment attribute.
1634 if (auto *TT = T->getAs<TypedefType>())
1635 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1636 return Align;
1637
1638 // Otherwise, see if the declaration of the type had an attribute.
1639 if (auto *TT = T->getAs<TagType>())
1640 return TT->getDecl()->getMaxAlignment();
1641
1642 return 0;
1643}
1644
David Majnemer34b57492014-07-30 01:30:47 +00001645TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001646 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1647 if (I != MemoizedTypeInfo.end())
1648 return I->second;
1649
1650 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1651 TypeInfo TI = getTypeInfoImpl(T);
1652 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001653 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001654}
1655
1656/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1657/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001658///
1659/// FIXME: Pointers into different addr spaces could have different sizes and
1660/// alignment requirements: getPointerInfo should take an AddrSpace, this
1661/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001662TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1663 uint64_t Width = 0;
1664 unsigned Align = 8;
1665 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001666 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001667 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001668#define TYPE(Class, Base)
1669#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001670#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001671#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001672#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1673 case Type::Class: \
1674 assert(!T->isDependentType() && "should not see dependent types here"); \
1675 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001676#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001677 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001678
Chris Lattner355332d2007-07-13 22:27:08 +00001679 case Type::FunctionNoProto:
1680 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001681 // GCC extension: alignof(function) = 32 bits
1682 Width = 0;
1683 Align = 32;
1684 break;
1685
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001686 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001687 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001688 Width = 0;
1689 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1690 break;
1691
Steve Naroff5c131802007-08-30 01:06:46 +00001692 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001693 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001694
David Majnemer34b57492014-07-30 01:30:47 +00001695 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001696 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001697 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001698 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001699 Width = EltInfo.Width * Size;
1700 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001701 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1702 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001703 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001704 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001705 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001706 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001707 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001708 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001709 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1710 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001711 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001712 // If the alignment is not a power of 2, round up to the next power of 2.
1713 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001714 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001715 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001716 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001717 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001718 // Adjust the alignment based on the target max.
1719 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1720 if (TargetVectorAlign && TargetVectorAlign < Align)
1721 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001722 break;
1723 }
Chris Lattner647fb222007-07-18 18:26:58 +00001724
Chris Lattner7570e9c2008-03-08 08:52:55 +00001725 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001726 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001727 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001728 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001729 // GCC extension: alignof(void) = 8 bits.
1730 Width = 0;
1731 Align = 8;
1732 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001733 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001734 Width = Target->getBoolWidth();
1735 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001736 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001737 case BuiltinType::Char_S:
1738 case BuiltinType::Char_U:
1739 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001740 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001741 Width = Target->getCharWidth();
1742 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001743 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001744 case BuiltinType::WChar_S:
1745 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001746 Width = Target->getWCharWidth();
1747 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001748 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001749 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001750 Width = Target->getChar16Width();
1751 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001752 break;
1753 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001754 Width = Target->getChar32Width();
1755 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001756 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001757 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001758 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001759 Width = Target->getShortWidth();
1760 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001761 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001762 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001763 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001764 Width = Target->getIntWidth();
1765 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001766 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001767 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001768 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001769 Width = Target->getLongWidth();
1770 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001771 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001772 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001773 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001774 Width = Target->getLongLongWidth();
1775 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001776 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001777 case BuiltinType::Int128:
1778 case BuiltinType::UInt128:
1779 Width = 128;
1780 Align = 128; // int128_t is 128-bit aligned on all targets.
1781 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001782 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001783 case BuiltinType::Half:
1784 Width = Target->getHalfWidth();
1785 Align = Target->getHalfAlign();
1786 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001787 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001788 Width = Target->getFloatWidth();
1789 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001790 break;
1791 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001792 Width = Target->getDoubleWidth();
1793 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001794 break;
1795 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001796 Width = Target->getLongDoubleWidth();
1797 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001798 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001799 case BuiltinType::Float128:
1800 Width = Target->getFloat128Width();
1801 Align = Target->getFloat128Align();
1802 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001803 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001804 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1805 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001806 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001807 case BuiltinType::ObjCId:
1808 case BuiltinType::ObjCClass:
1809 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001810 Width = Target->getPointerWidth(0);
1811 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001812 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001813 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001814 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001815 case BuiltinType::OCLClkEvent:
1816 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001817 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00001818#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1819 case BuiltinType::Id:
1820#include "clang/Basic/OpenCLImageTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00001821 AS = getTargetAddressSpace(
1822 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001823 Width = Target->getPointerWidth(AS);
1824 Align = Target->getPointerAlign(AS);
1825 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001826 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001827 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001828 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001829 Width = Target->getPointerWidth(0);
1830 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001831 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001832 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001833 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001834 Width = Target->getPointerWidth(AS);
1835 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001836 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001837 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001838 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001839 // alignof and sizeof should never enter this code path here, so we go
1840 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001841 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001842 Width = Target->getPointerWidth(AS);
1843 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001844 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001845 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001846 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001847 Width = Target->getPointerWidth(AS);
1848 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001849 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001850 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001851 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00001852 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
1853 Width = MPI.Width;
1854 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00001855 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001856 }
Chris Lattner647fb222007-07-18 18:26:58 +00001857 case Type::Complex: {
1858 // Complex types have the same alignment as their elements, but twice the
1859 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001860 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1861 Width = EltInfo.Width * 2;
1862 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001863 break;
1864 }
John McCall8b07ec22010-05-15 11:32:37 +00001865 case Type::ObjCObject:
1866 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001867 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001868 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001869 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001870 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001871 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001872 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001873 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001874 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001875 break;
1876 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001877 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001878 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001879 const TagType *TT = cast<TagType>(T);
1880
1881 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001882 Width = 8;
1883 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001884 break;
1885 }
Mike Stump11289f42009-09-09 15:08:12 +00001886
David Majnemer475b25e2015-01-21 10:54:38 +00001887 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1888 const EnumDecl *ED = ET->getDecl();
1889 TypeInfo Info =
1890 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1891 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1892 Info.Align = AttrAlign;
1893 Info.AlignIsRequired = true;
1894 }
1895 return Info;
1896 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001897
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001898 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001899 const RecordDecl *RD = RT->getDecl();
1900 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001901 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001902 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001903 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001904 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001905 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001906
Chris Lattner63d2b362009-10-22 05:17:15 +00001907 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001908 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1909 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001910
Richard Smith600b5262017-01-26 20:40:47 +00001911 case Type::Auto:
1912 case Type::DeducedTemplateSpecialization: {
1913 const DeducedType *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001914 assert(!A->getDeducedType().isNull() &&
1915 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001916 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001917 }
1918
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001919 case Type::Paren:
1920 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1921
Manman Rene6be26c2016-09-13 17:25:08 +00001922 case Type::ObjCTypeParam:
1923 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1924
Douglas Gregoref462e62009-04-30 17:32:17 +00001925 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001926 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001927 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001928 // If the typedef has an aligned attribute on it, it overrides any computed
1929 // alignment we have. This violates the GCC documentation (which says that
1930 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001931 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001932 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001933 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001934 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001935 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001936 AlignIsRequired = Info.AlignIsRequired;
1937 }
David Majnemer34b57492014-07-30 01:30:47 +00001938 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001939 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001940 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001941
Abramo Bagnara6150c882010-05-11 21:36:43 +00001942 case Type::Elaborated:
1943 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001944
John McCall81904512011-01-06 01:58:22 +00001945 case Type::Attributed:
1946 return getTypeInfo(
1947 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1948
Eli Friedman0dfb8892011-10-06 23:00:33 +00001949 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001950 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001951 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1952 Width = Info.Width;
1953 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001954
1955 // If the size of the type doesn't exceed the platform's max
1956 // atomic promotion width, make the size and alignment more
1957 // favorable to atomic operations:
1958 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1959 // Round the size up to a power of 2.
1960 if (!llvm::isPowerOf2_64(Width))
1961 Width = llvm::NextPowerOf2(Width);
1962
1963 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001964 Align = static_cast<unsigned>(Width);
1965 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001966 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001967 break;
1968
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001969 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00001970 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
1971 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001972 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00001973 }
Mike Stump11289f42009-09-09 15:08:12 +00001974
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001975 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001976 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001977}
1978
Alexey Bataev00396512015-07-02 03:40:19 +00001979unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1980 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1981 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1982 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1983 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1984 getTargetInfo().getABI() == "elfv1-qpx" &&
1985 T->isSpecificBuiltinType(BuiltinType::Double))
1986 SimdAlign = 256;
1987 return SimdAlign;
1988}
1989
Ken Dyckcc56c542011-01-15 18:38:59 +00001990/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1991CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1992 return CharUnits::fromQuantity(BitSize / getCharWidth());
1993}
1994
Ken Dyckb0fcc592011-02-11 01:54:29 +00001995/// toBits - Convert a size in characters to a size in characters.
1996int64_t ASTContext::toBits(CharUnits CharSize) const {
1997 return CharSize.getQuantity() * getCharWidth();
1998}
1999
Ken Dyck8c89d592009-12-22 14:23:30 +00002000/// getTypeSizeInChars - Return the size of the specified type, in characters.
2001/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002002CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002003 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002004}
Jay Foad39c79802011-01-12 09:06:06 +00002005CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002006 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002007}
2008
Ken Dycka6046ab2010-01-26 17:25:18 +00002009/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002010/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002011CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002012 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002013}
Jay Foad39c79802011-01-12 09:06:06 +00002014CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002015 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002016}
2017
Chris Lattnera3402cd2009-01-27 18:08:34 +00002018/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2019/// type for the current target in bits. This can be different than the ABI
2020/// alignment in cases where it is beneficial for performance to overalign
2021/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002022unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002023 TypeInfo TI = getTypeInfo(T);
2024 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002025
David Majnemere1544562015-04-24 01:25:05 +00002026 T = T->getBaseElementTypeUnsafe();
2027
2028 // The preferred alignment of member pointers is that of a pointer.
2029 if (T->isMemberPointerType())
2030 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2031
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002032 if (!Target->allowsLargerPreferedTypeAlignment())
2033 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002034
Eli Friedman7ab09572009-05-25 21:27:19 +00002035 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00002036 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002037 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00002038 if (const EnumType *ET = T->getAs<EnumType>())
2039 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002040 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002041 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2042 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002043 // Don't increase the alignment if an alignment attribute was specified on a
2044 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002045 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002046 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002047
Chris Lattnera3402cd2009-01-27 18:08:34 +00002048 return ABIAlign;
2049}
2050
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002051/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2052/// for __attribute__((aligned)) on this target, to be used if no alignment
2053/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002054unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002055 return getTargetInfo().getDefaultAlignForAttributeAligned();
2056}
2057
Ulrich Weigandfa806422013-05-06 16:23:57 +00002058/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2059/// to a global variable of the specified type.
2060unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2061 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2062}
2063
2064/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2065/// should be given to a global variable of the specified type.
2066CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2067 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2068}
2069
David Majnemer08ef2ba2015-06-23 20:34:18 +00002070CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2071 CharUnits Offset = CharUnits::Zero();
2072 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2073 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2074 Offset += Layout->getBaseClassOffset(Base);
2075 Layout = &getASTRecordLayout(Base);
2076 }
2077 return Offset;
2078}
2079
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002080/// DeepCollectObjCIvars -
2081/// This routine first collects all declared, but not synthesized, ivars in
2082/// super class and then collects all ivars, including those synthesized for
2083/// current class. This routine is used for implementation of current class
2084/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002085void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2086 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002087 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002088 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2089 DeepCollectObjCIvars(SuperClass, false, Ivars);
2090 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002091 for (const auto *I : OI->ivars())
2092 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002093 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002094 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00002095 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002096 Iv= Iv->getNextIvar())
2097 Ivars.push_back(Iv);
2098 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002099}
2100
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002101/// CollectInheritedProtocols - Collect all protocols in current class and
2102/// those inherited by it.
2103void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002104 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002105 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002106 // We can use protocol_iterator here instead of
2107 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002108 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002109 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002110 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002111
2112 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002113 for (const auto *Cat : OI->visible_categories())
2114 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002115
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002116 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2117 while (SD) {
2118 CollectInheritedProtocols(SD, Protocols);
2119 SD = SD->getSuperClass();
2120 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002121 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002122 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002123 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002124 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002125 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002126 // Insert the protocol.
2127 if (!Protocols.insert(
2128 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2129 return;
2130
2131 for (auto *Proto : OP->protocols())
2132 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002133 }
2134}
2135
Erich Keane8a6b7402017-11-30 16:37:02 +00002136static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2137 const RecordDecl *RD) {
2138 assert(RD->isUnion() && "Must be union type");
2139 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2140
2141 for (const auto *Field : RD->fields()) {
2142 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2143 return false;
2144 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2145 if (FieldSize != UnionSize)
2146 return false;
2147 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002148 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002149}
2150
Benjamin Kramer802e6252017-12-24 12:46:22 +00002151static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002152 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2153
2154 if (!RD->field_empty())
2155 return false;
2156
2157 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2158 return ClassDecl->isEmpty();
2159
2160 return true;
2161}
2162
2163static llvm::Optional<int64_t>
2164structHasUniqueObjectRepresentations(const ASTContext &Context,
2165 const RecordDecl *RD) {
2166 assert(!RD->isUnion() && "Must be struct/class type");
2167 const auto &Layout = Context.getASTRecordLayout(RD);
2168
2169 int64_t CurOffsetInBits = 0;
2170 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2171 if (ClassDecl->isDynamicClass())
2172 return llvm::None;
2173
2174 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2175 for (const auto Base : ClassDecl->bases()) {
2176 // Empty types can be inherited from, and non-empty types can potentially
2177 // have tail padding, so just make sure there isn't an error.
2178 if (!isStructEmpty(Base.getType())) {
2179 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2180 Context, Base.getType()->getAs<RecordType>()->getDecl());
2181 if (!Size)
2182 return llvm::None;
2183 Bases.emplace_back(Base.getType(), Size.getValue());
2184 }
2185 }
2186
2187 std::sort(
2188 Bases.begin(), Bases.end(), [&](const std::pair<QualType, int64_t> &L,
2189 const std::pair<QualType, int64_t> &R) {
2190 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2191 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2192 });
2193
2194 for (const auto Base : Bases) {
2195 int64_t BaseOffset = Context.toBits(
2196 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2197 int64_t BaseSize = Base.second;
2198 if (BaseOffset != CurOffsetInBits)
2199 return llvm::None;
2200 CurOffsetInBits = BaseOffset + BaseSize;
2201 }
2202 }
2203
2204 for (const auto *Field : RD->fields()) {
2205 if (!Field->getType()->isReferenceType() &&
2206 !Context.hasUniqueObjectRepresentations(Field->getType()))
2207 return llvm::None;
2208
2209 int64_t FieldSizeInBits =
2210 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2211 if (Field->isBitField()) {
2212 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2213
2214 if (BitfieldSize > FieldSizeInBits)
2215 return llvm::None;
2216 FieldSizeInBits = BitfieldSize;
2217 }
2218
2219 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2220
2221 if (FieldOffsetInBits != CurOffsetInBits)
2222 return llvm::None;
2223
2224 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2225 }
2226
2227 return CurOffsetInBits;
2228}
2229
2230bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2231 // C++17 [meta.unary.prop]:
2232 // The predicate condition for a template specialization
2233 // has_unique_object_representations<T> shall be
2234 // satisfied if and only if:
2235 // (9.1) - T is trivially copyable, and
2236 // (9.2) - any two objects of type T with the same value have the same
2237 // object representation, where two objects
2238 // of array or non-union class type are considered to have the same value
2239 // if their respective sequences of
2240 // direct subobjects have the same values, and two objects of union type
2241 // are considered to have the same
2242 // value if they have the same active member and the corresponding members
2243 // have the same value.
2244 // The set of scalar types for which this condition holds is
2245 // implementation-defined. [ Note: If a type has padding
2246 // bits, the condition does not hold; otherwise, the condition holds true
2247 // for unsigned integral types. -- end note ]
2248 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2249
2250 // Arrays are unique only if their element type is unique.
2251 if (Ty->isArrayType())
2252 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2253
2254 // (9.1) - T is trivially copyable...
2255 if (!Ty.isTriviallyCopyableType(*this))
2256 return false;
2257
2258 // All integrals and enums are unique.
2259 if (Ty->isIntegralOrEnumerationType())
2260 return true;
2261
2262 // All other pointers are unique.
2263 if (Ty->isPointerType())
2264 return true;
2265
2266 if (Ty->isMemberPointerType()) {
2267 const MemberPointerType *MPT = Ty->getAs<MemberPointerType>();
2268 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2269 }
2270
2271 if (Ty->isRecordType()) {
2272 const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
2273
Erich Keanebd2197c2017-12-12 16:02:06 +00002274 if (Record->isInvalidDecl())
2275 return false;
2276
Erich Keane8a6b7402017-11-30 16:37:02 +00002277 if (Record->isUnion())
2278 return unionHasUniqueObjectRepresentations(*this, Record);
2279
2280 Optional<int64_t> StructSize =
2281 structHasUniqueObjectRepresentations(*this, Record);
2282
2283 return StructSize &&
2284 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2285 }
2286
2287 // FIXME: More cases to handle here (list by rsmith):
2288 // vectors (careful about, eg, vector of 3 foo)
2289 // _Complex int and friends
2290 // _Atomic T
2291 // Obj-C block pointers
2292 // Obj-C object pointers
2293 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2294 // clk_event_t, queue_t, reserve_id_t)
2295 // There're also Obj-C class types and the Obj-C selector type, but I think it
2296 // makes sense for those to return false here.
2297
2298 return false;
2299}
2300
Jay Foad39c79802011-01-12 09:06:06 +00002301unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002302 unsigned count = 0;
2303 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002304 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002305 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002306
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002307 // Count ivar defined in this class's implementation. This
2308 // includes synthesized ivars.
2309 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002310 count += ImplDecl->ivar_size();
2311
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002312 return count;
2313}
2314
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002315bool ASTContext::isSentinelNullExpr(const Expr *E) {
2316 if (!E)
2317 return false;
2318
2319 // nullptr_t is always treated as null.
2320 if (E->getType()->isNullPtrType()) return true;
2321
2322 if (E->getType()->isAnyPointerType() &&
2323 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2324 Expr::NPC_ValueDependentIsNull))
2325 return true;
2326
2327 // Unfortunately, __null has type 'int'.
2328 if (isa<GNUNullExpr>(E)) return true;
2329
2330 return false;
2331}
2332
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002333/// \brief Get the implementation of ObjCInterfaceDecl, or nullptr if none
2334/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002335ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2336 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2337 I = ObjCImpls.find(D);
2338 if (I != ObjCImpls.end())
2339 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002340 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002341}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002342
2343/// \brief Get the implementation of ObjCCategoryDecl, or nullptr if none
2344/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002345ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2346 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2347 I = ObjCImpls.find(D);
2348 if (I != ObjCImpls.end())
2349 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002350 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002351}
2352
2353/// \brief Set the implementation of ObjCInterfaceDecl.
2354void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2355 ObjCImplementationDecl *ImplD) {
2356 assert(IFaceD && ImplD && "Passed null params");
2357 ObjCImpls[IFaceD] = ImplD;
2358}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002359
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002360/// \brief Set the implementation of ObjCCategoryDecl.
2361void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2362 ObjCCategoryImplDecl *ImplD) {
2363 assert(CatD && ImplD && "Passed null params");
2364 ObjCImpls[CatD] = ImplD;
2365}
2366
Chandler Carruth21c90602015-12-30 03:24:14 +00002367const ObjCMethodDecl *
2368ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2369 return ObjCMethodRedecls.lookup(MD);
2370}
2371
2372void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2373 const ObjCMethodDecl *Redecl) {
2374 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2375 ObjCMethodRedecls[MD] = Redecl;
2376}
2377
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002378const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2379 const NamedDecl *ND) const {
2380 if (const ObjCInterfaceDecl *ID =
2381 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002382 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002383 if (const ObjCCategoryDecl *CD =
2384 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002385 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002386 if (const ObjCImplDecl *IMD =
2387 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002388 return IMD->getClassInterface();
2389
Craig Topper36250ad2014-05-12 05:36:57 +00002390 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002391}
2392
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002393/// \brief Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002394/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002395Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002396 assert(VD && "Passed null params");
2397 assert(VD->hasAttr<BlocksAttr>() &&
2398 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002399 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002400 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002401 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002402}
2403
2404/// \brief Set the copy inialization expression of a block var decl.
2405void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2406 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002407 assert(VD->hasAttr<BlocksAttr>() &&
2408 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002409 BlockVarCopyInits[VD] = Init;
2410}
2411
John McCallbcd03502009-12-07 02:54:59 +00002412TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002413 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002414 if (!DataSize)
2415 DataSize = TypeLoc::getFullDataSizeForType(T);
2416 else
2417 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002418 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002419
John McCallbcd03502009-12-07 02:54:59 +00002420 TypeSourceInfo *TInfo =
2421 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2422 new (TInfo) TypeSourceInfo(T);
2423 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002424}
2425
John McCallbcd03502009-12-07 02:54:59 +00002426TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002427 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002428 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002429 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002430 return DI;
2431}
2432
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002433const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002434ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002435 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002436}
2437
2438const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002439ASTContext::getASTObjCImplementationLayout(
2440 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002441 return getObjCLayout(D->getClassInterface(), D);
2442}
2443
Chris Lattner983a8bb2007-07-13 22:13:22 +00002444//===----------------------------------------------------------------------===//
2445// Type creation/memoization methods
2446//===----------------------------------------------------------------------===//
2447
Jay Foad39c79802011-01-12 09:06:06 +00002448QualType
John McCall33ddac02011-01-19 10:06:00 +00002449ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2450 unsigned fastQuals = quals.getFastQualifiers();
2451 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002452
2453 // Check if we've already instantiated this type.
2454 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002455 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002456 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002457 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2458 assert(eq->getQualifiers() == quals);
2459 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002460 }
2461
John McCall33ddac02011-01-19 10:06:00 +00002462 // If the base type is not canonical, make the appropriate canonical type.
2463 QualType canon;
2464 if (!baseType->isCanonicalUnqualified()) {
2465 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002466 canonSplit.Quals.addConsistentQualifiers(quals);
2467 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002468
2469 // Re-find the insert position.
2470 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2471 }
2472
2473 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2474 ExtQualNodes.InsertNode(eq, insertPos);
2475 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002476}
2477
Alexander Richardson6d989432017-10-15 18:48:14 +00002478QualType ASTContext::getAddrSpaceQualType(QualType T,
2479 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002480 QualType CanT = getCanonicalType(T);
2481 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002482 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002483
John McCall8ccfcb52009-09-24 19:53:00 +00002484 // If we are composing extended qualifiers together, merge together
2485 // into one ExtQuals node.
2486 QualifierCollector Quals;
2487 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002488
John McCall8ccfcb52009-09-24 19:53:00 +00002489 // If this type already has an address space specified, it cannot get
2490 // another one.
2491 assert(!Quals.hasAddressSpace() &&
2492 "Type cannot be in multiple addr spaces!");
2493 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002494
John McCall8ccfcb52009-09-24 19:53:00 +00002495 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002496}
2497
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002498QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2499 // If we are composing extended qualifiers together, merge together
2500 // into one ExtQuals node.
2501 QualifierCollector Quals;
2502 const Type *TypeNode = Quals.strip(T);
2503
2504 // If the qualifier doesn't have an address space just return it.
2505 if (!Quals.hasAddressSpace())
2506 return T;
2507
2508 Quals.removeAddressSpace();
2509
2510 // Removal of the address space can mean there are no longer any
2511 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2512 // or required.
2513 if (Quals.hasNonFastQualifiers())
2514 return getExtQualType(TypeNode, Quals);
2515 else
2516 return QualType(TypeNode, Quals.getFastQualifiers());
2517}
2518
Chris Lattnerd60183d2009-02-18 22:53:11 +00002519QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002520 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002521 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002522 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002523 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002524
John McCall53fa7142010-12-24 02:08:15 +00002525 if (const PointerType *ptr = T->getAs<PointerType>()) {
2526 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002527 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002528 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2529 return getPointerType(ResultType);
2530 }
2531 }
Mike Stump11289f42009-09-09 15:08:12 +00002532
John McCall8ccfcb52009-09-24 19:53:00 +00002533 // If we are composing extended qualifiers together, merge together
2534 // into one ExtQuals node.
2535 QualifierCollector Quals;
2536 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002537
John McCall8ccfcb52009-09-24 19:53:00 +00002538 // If this type already has an ObjCGC specified, it cannot get
2539 // another one.
2540 assert(!Quals.hasObjCGCAttr() &&
2541 "Type cannot have multiple ObjCGCs!");
2542 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002543
John McCall8ccfcb52009-09-24 19:53:00 +00002544 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002545}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002546
John McCall4f5019e2010-12-19 02:44:49 +00002547const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2548 FunctionType::ExtInfo Info) {
2549 if (T->getExtInfo() == Info)
2550 return T;
2551
2552 QualType Result;
2553 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002554 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002555 } else {
2556 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2557 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2558 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002559 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002560 }
2561
2562 return cast<FunctionType>(Result.getTypePtr());
2563}
2564
Richard Smith2a7d4812013-05-04 07:00:32 +00002565void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2566 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002567 FD = FD->getMostRecentDecl();
2568 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002569 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2570 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002571 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002572 if (FunctionDecl *Next = FD->getPreviousDecl())
2573 FD = Next;
2574 else
2575 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002576 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002577 if (ASTMutationListener *L = getASTMutationListener())
2578 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002579}
2580
Richard Smith0b3a4622014-11-13 20:01:57 +00002581/// Get a function type and produce the equivalent function type with the
2582/// specified exception specification. Type sugar that can be present on a
2583/// declaration of a function with an exception specification is permitted
2584/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002585QualType ASTContext::getFunctionTypeWithExceptionSpec(
2586 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002587 // Might have some parens.
2588 if (auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002589 return getParenType(
2590 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002591
2592 // Might have a calling-convention attribute.
2593 if (auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002594 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002595 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002596 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2597 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002598
2599 // Anything else must be a function type. Rebuild it with the new exception
2600 // specification.
2601 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002602 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002603 Proto->getReturnType(), Proto->getParamTypes(),
2604 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2605}
2606
Richard Smithdfe85e22016-12-15 02:35:39 +00002607bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2608 QualType U) {
2609 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002610 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002611 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2612 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002613}
2614
Richard Smith0b3a4622014-11-13 20:01:57 +00002615void ASTContext::adjustExceptionSpec(
2616 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2617 bool AsWritten) {
2618 // Update the type.
2619 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002620 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002621 FD->setType(Updated);
2622
2623 if (!AsWritten)
2624 return;
2625
2626 // Update the type in the type source information too.
2627 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2628 // If the type and the type-as-written differ, we may need to update
2629 // the type-as-written too.
2630 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002631 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002632
2633 // FIXME: When we get proper type location information for exceptions,
2634 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2635 // up the TypeSourceInfo;
2636 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2637 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2638 "TypeLoc size mismatch from updating exception specification");
2639 TSInfo->overrideType(Updated);
2640 }
2641}
2642
Akira Hatanaka02914dc2018-02-05 20:23:22 +00002643bool ASTContext::isParamDestroyedInCallee(QualType T) const {
2644 return getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee() ||
2645 T.hasTrivialABIOverride();
2646}
2647
Chris Lattnerc6395932007-06-22 20:56:16 +00002648/// getComplexType - Return the uniqued reference to the type for a complex
2649/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002650QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002651 // Unique pointers, to guarantee there is only one pointer of a particular
2652 // structure.
2653 llvm::FoldingSetNodeID ID;
2654 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002655
Craig Topper36250ad2014-05-12 05:36:57 +00002656 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002657 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2658 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002659
Chris Lattnerc6395932007-06-22 20:56:16 +00002660 // If the pointee type isn't canonical, this won't be a canonical type either,
2661 // so fill in the canonical type field.
2662 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002663 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002664 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002665
Chris Lattnerc6395932007-06-22 20:56:16 +00002666 // Get the new insert position for the node we care about.
2667 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002668 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002669 }
John McCall90d1c2d2009-09-24 23:30:46 +00002670 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002671 Types.push_back(New);
2672 ComplexTypes.InsertNode(New, InsertPos);
2673 return QualType(New, 0);
2674}
2675
Chris Lattner970e54e2006-11-12 00:37:36 +00002676/// getPointerType - Return the uniqued reference to the type for a pointer to
2677/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002678QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002679 // Unique pointers, to guarantee there is only one pointer of a particular
2680 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002681 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002682 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002683
Craig Topper36250ad2014-05-12 05:36:57 +00002684 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002685 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002686 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002687
Chris Lattner7ccecb92006-11-12 08:50:50 +00002688 // If the pointee type isn't canonical, this won't be a canonical type either,
2689 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002690 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002691 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002692 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002693
Bob Wilsonc8541f22013-03-15 17:12:43 +00002694 // Get the new insert position for the node we care about.
2695 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002696 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002697 }
John McCall90d1c2d2009-09-24 23:30:46 +00002698 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002699 Types.push_back(New);
2700 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002701 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002702}
2703
Reid Kleckner0503a872013-12-05 01:23:43 +00002704QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2705 llvm::FoldingSetNodeID ID;
2706 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002707 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002708 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2709 if (AT)
2710 return QualType(AT, 0);
2711
2712 QualType Canonical = getCanonicalType(New);
2713
2714 // Get the new insert position for the node we care about.
2715 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002716 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002717
2718 AT = new (*this, TypeAlignment)
2719 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2720 Types.push_back(AT);
2721 AdjustedTypes.InsertNode(AT, InsertPos);
2722 return QualType(AT, 0);
2723}
2724
Reid Kleckner8a365022013-06-24 17:51:48 +00002725QualType ASTContext::getDecayedType(QualType T) const {
2726 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2727
Reid Kleckner8a365022013-06-24 17:51:48 +00002728 QualType Decayed;
2729
2730 // C99 6.7.5.3p7:
2731 // A declaration of a parameter as "array of type" shall be
2732 // adjusted to "qualified pointer to type", where the type
2733 // qualifiers (if any) are those specified within the [ and ] of
2734 // the array type derivation.
2735 if (T->isArrayType())
2736 Decayed = getArrayDecayedType(T);
2737
2738 // C99 6.7.5.3p8:
2739 // A declaration of a parameter as "function returning type"
2740 // shall be adjusted to "pointer to function returning type", as
2741 // in 6.3.2.1.
2742 if (T->isFunctionType())
2743 Decayed = getPointerType(T);
2744
Reid Kleckner0503a872013-12-05 01:23:43 +00002745 llvm::FoldingSetNodeID ID;
2746 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002747 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002748 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2749 if (AT)
2750 return QualType(AT, 0);
2751
Reid Kleckner8a365022013-06-24 17:51:48 +00002752 QualType Canonical = getCanonicalType(Decayed);
2753
2754 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002755 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002756 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002757
Reid Kleckner0503a872013-12-05 01:23:43 +00002758 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2759 Types.push_back(AT);
2760 AdjustedTypes.InsertNode(AT, InsertPos);
2761 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002762}
2763
Mike Stump11289f42009-09-09 15:08:12 +00002764/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002765/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002766QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002767 assert(T->isFunctionType() && "block of function types only");
2768 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002769 // structure.
2770 llvm::FoldingSetNodeID ID;
2771 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002772
Craig Topper36250ad2014-05-12 05:36:57 +00002773 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002774 if (BlockPointerType *PT =
2775 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2776 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002777
2778 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002779 // type either so fill in the canonical type field.
2780 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002781 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002782 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002783
Steve Naroffec33ed92008-08-27 16:04:49 +00002784 // Get the new insert position for the node we care about.
2785 BlockPointerType *NewIP =
2786 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002787 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002788 }
John McCall90d1c2d2009-09-24 23:30:46 +00002789 BlockPointerType *New
2790 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002791 Types.push_back(New);
2792 BlockPointerTypes.InsertNode(New, InsertPos);
2793 return QualType(New, 0);
2794}
2795
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002796/// getLValueReferenceType - Return the uniqued reference to the type for an
2797/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002798QualType
2799ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002800 assert(getCanonicalType(T) != OverloadTy &&
2801 "Unresolved overloaded function type");
2802
Bill Wendling3708c182007-05-27 10:15:43 +00002803 // Unique pointers, to guarantee there is only one pointer of a particular
2804 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002805 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002806 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002807
Craig Topper36250ad2014-05-12 05:36:57 +00002808 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002809 if (LValueReferenceType *RT =
2810 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002811 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002812
John McCallfc93cf92009-10-22 22:37:11 +00002813 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2814
Bill Wendling3708c182007-05-27 10:15:43 +00002815 // If the referencee type isn't canonical, this won't be a canonical type
2816 // either, so fill in the canonical type field.
2817 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002818 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2819 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2820 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002821
Bill Wendling3708c182007-05-27 10:15:43 +00002822 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002823 LValueReferenceType *NewIP =
2824 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002825 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002826 }
2827
John McCall90d1c2d2009-09-24 23:30:46 +00002828 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002829 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2830 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002831 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002832 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002833
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002834 return QualType(New, 0);
2835}
2836
2837/// getRValueReferenceType - Return the uniqued reference to the type for an
2838/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002839QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002840 // Unique pointers, to guarantee there is only one pointer of a particular
2841 // structure.
2842 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002843 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002844
Craig Topper36250ad2014-05-12 05:36:57 +00002845 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002846 if (RValueReferenceType *RT =
2847 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2848 return QualType(RT, 0);
2849
John McCallfc93cf92009-10-22 22:37:11 +00002850 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2851
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002852 // If the referencee type isn't canonical, this won't be a canonical type
2853 // either, so fill in the canonical type field.
2854 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002855 if (InnerRef || !T.isCanonical()) {
2856 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2857 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002858
2859 // Get the new insert position for the node we care about.
2860 RValueReferenceType *NewIP =
2861 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002862 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002863 }
2864
John McCall90d1c2d2009-09-24 23:30:46 +00002865 RValueReferenceType *New
2866 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002867 Types.push_back(New);
2868 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002869 return QualType(New, 0);
2870}
2871
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002872/// getMemberPointerType - Return the uniqued reference to the type for a
2873/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002874QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002875 // Unique pointers, to guarantee there is only one pointer of a particular
2876 // structure.
2877 llvm::FoldingSetNodeID ID;
2878 MemberPointerType::Profile(ID, T, Cls);
2879
Craig Topper36250ad2014-05-12 05:36:57 +00002880 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002881 if (MemberPointerType *PT =
2882 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2883 return QualType(PT, 0);
2884
2885 // If the pointee or class type isn't canonical, this won't be a canonical
2886 // type either, so fill in the canonical type field.
2887 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002888 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002889 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2890
2891 // Get the new insert position for the node we care about.
2892 MemberPointerType *NewIP =
2893 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002894 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002895 }
John McCall90d1c2d2009-09-24 23:30:46 +00002896 MemberPointerType *New
2897 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002898 Types.push_back(New);
2899 MemberPointerTypes.InsertNode(New, InsertPos);
2900 return QualType(New, 0);
2901}
2902
Mike Stump11289f42009-09-09 15:08:12 +00002903/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002904/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002905QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002906 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002907 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002908 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002909 assert((EltTy->isDependentType() ||
2910 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002911 "Constant array of VLAs is illegal!");
2912
Chris Lattnere2df3f92009-05-13 04:12:56 +00002913 // Convert the array size into a canonical width matching the pointer size for
2914 // the target.
2915 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00002916 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00002917
Chris Lattner23b7eb62007-06-15 23:05:46 +00002918 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002919 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002920
Craig Topper36250ad2014-05-12 05:36:57 +00002921 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002922 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002923 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002924 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002925
John McCall33ddac02011-01-19 10:06:00 +00002926 // If the element type isn't canonical or has qualifiers, this won't
2927 // be a canonical type either, so fill in the canonical type field.
2928 QualType Canon;
2929 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2930 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002931 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002932 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002933 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002934
Chris Lattner36f8e652007-01-27 08:31:04 +00002935 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002936 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002937 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002938 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002939 }
Mike Stump11289f42009-09-09 15:08:12 +00002940
John McCall90d1c2d2009-09-24 23:30:46 +00002941 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002942 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002943 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002944 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002945 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002946}
2947
John McCall06549462011-01-18 08:40:38 +00002948/// getVariableArrayDecayedType - Turns the given type, which may be
2949/// variably-modified, into the corresponding type with all the known
2950/// sizes replaced with [*].
2951QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2952 // Vastly most common case.
2953 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002954
John McCall06549462011-01-18 08:40:38 +00002955 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002956
John McCall06549462011-01-18 08:40:38 +00002957 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002958 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002959 switch (ty->getTypeClass()) {
2960#define TYPE(Class, Base)
2961#define ABSTRACT_TYPE(Class, Base)
2962#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2963#include "clang/AST/TypeNodes.def"
2964 llvm_unreachable("didn't desugar past all non-canonical types?");
2965
2966 // These types should never be variably-modified.
2967 case Type::Builtin:
2968 case Type::Complex:
2969 case Type::Vector:
2970 case Type::ExtVector:
2971 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002972 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00002973 case Type::ObjCObject:
2974 case Type::ObjCInterface:
2975 case Type::ObjCObjectPointer:
2976 case Type::Record:
2977 case Type::Enum:
2978 case Type::UnresolvedUsing:
2979 case Type::TypeOfExpr:
2980 case Type::TypeOf:
2981 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002982 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002983 case Type::DependentName:
2984 case Type::InjectedClassName:
2985 case Type::TemplateSpecialization:
2986 case Type::DependentTemplateSpecialization:
2987 case Type::TemplateTypeParm:
2988 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002989 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002990 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00002991 case Type::PackExpansion:
2992 llvm_unreachable("type should never be variably-modified");
2993
2994 // These types can be variably-modified but should never need to
2995 // further decay.
2996 case Type::FunctionNoProto:
2997 case Type::FunctionProto:
2998 case Type::BlockPointer:
2999 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00003000 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00003001 return type;
3002
3003 // These types can be variably-modified. All these modifications
3004 // preserve structure except as noted by comments.
3005 // TODO: if we ever care about optimizing VLAs, there are no-op
3006 // optimizations available here.
3007 case Type::Pointer:
3008 result = getPointerType(getVariableArrayDecayedType(
3009 cast<PointerType>(ty)->getPointeeType()));
3010 break;
3011
3012 case Type::LValueReference: {
3013 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
3014 result = getLValueReferenceType(
3015 getVariableArrayDecayedType(lv->getPointeeType()),
3016 lv->isSpelledAsLValue());
3017 break;
3018 }
3019
3020 case Type::RValueReference: {
3021 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
3022 result = getRValueReferenceType(
3023 getVariableArrayDecayedType(lv->getPointeeType()));
3024 break;
3025 }
3026
Eli Friedman0dfb8892011-10-06 23:00:33 +00003027 case Type::Atomic: {
3028 const AtomicType *at = cast<AtomicType>(ty);
3029 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3030 break;
3031 }
3032
John McCall06549462011-01-18 08:40:38 +00003033 case Type::ConstantArray: {
3034 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
3035 result = getConstantArrayType(
3036 getVariableArrayDecayedType(cat->getElementType()),
3037 cat->getSize(),
3038 cat->getSizeModifier(),
3039 cat->getIndexTypeCVRQualifiers());
3040 break;
3041 }
3042
3043 case Type::DependentSizedArray: {
3044 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
3045 result = getDependentSizedArrayType(
3046 getVariableArrayDecayedType(dat->getElementType()),
3047 dat->getSizeExpr(),
3048 dat->getSizeModifier(),
3049 dat->getIndexTypeCVRQualifiers(),
3050 dat->getBracketsRange());
3051 break;
3052 }
3053
3054 // Turn incomplete types into [*] types.
3055 case Type::IncompleteArray: {
3056 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
3057 result = getVariableArrayType(
3058 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003059 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003060 ArrayType::Normal,
3061 iat->getIndexTypeCVRQualifiers(),
3062 SourceRange());
3063 break;
3064 }
3065
3066 // Turn VLA types into [*] types.
3067 case Type::VariableArray: {
3068 const VariableArrayType *vat = cast<VariableArrayType>(ty);
3069 result = getVariableArrayType(
3070 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003071 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003072 ArrayType::Star,
3073 vat->getIndexTypeCVRQualifiers(),
3074 vat->getBracketsRange());
3075 break;
3076 }
3077 }
3078
3079 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003080 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003081}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003082
Steve Naroffcadebd02007-08-30 18:14:25 +00003083/// getVariableArrayType - Returns a non-unique reference to the type for a
3084/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003085QualType ASTContext::getVariableArrayType(QualType EltTy,
3086 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003087 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003088 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003089 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003090 // Since we don't unique expressions, it isn't possible to unique VLA's
3091 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003092 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003093
John McCall33ddac02011-01-19 10:06:00 +00003094 // Be sure to pull qualifiers off the element type.
3095 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3096 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003097 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003098 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003099 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003100 }
3101
John McCall90d1c2d2009-09-24 23:30:46 +00003102 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003103 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003104
3105 VariableArrayTypes.push_back(New);
3106 Types.push_back(New);
3107 return QualType(New, 0);
3108}
3109
Douglas Gregor4619e432008-12-05 23:32:09 +00003110/// getDependentSizedArrayType - Returns a non-unique reference to
3111/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003112/// type.
John McCall33ddac02011-01-19 10:06:00 +00003113QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3114 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003115 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003116 unsigned elementTypeQuals,
3117 SourceRange brackets) const {
3118 assert((!numElements || numElements->isTypeDependent() ||
3119 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003120 "Size must be type- or value-dependent!");
3121
John McCall33ddac02011-01-19 10:06:00 +00003122 // Dependently-sized array types that do not have a specified number
3123 // of elements will have their sizes deduced from a dependent
3124 // initializer. We do no canonicalization here at all, which is okay
3125 // because they can't be used in most locations.
3126 if (!numElements) {
3127 DependentSizedArrayType *newType
3128 = new (*this, TypeAlignment)
3129 DependentSizedArrayType(*this, elementType, QualType(),
3130 numElements, ASM, elementTypeQuals,
3131 brackets);
3132 Types.push_back(newType);
3133 return QualType(newType, 0);
3134 }
3135
3136 // Otherwise, we actually build a new type every time, but we
3137 // also build a canonical type.
3138
3139 SplitQualType canonElementType = getCanonicalType(elementType).split();
3140
Craig Topper36250ad2014-05-12 05:36:57 +00003141 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003142 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003143 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003144 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003145 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003146
John McCall33ddac02011-01-19 10:06:00 +00003147 // Look for an existing type with these properties.
3148 DependentSizedArrayType *canonTy =
3149 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003150
John McCall33ddac02011-01-19 10:06:00 +00003151 // If we don't have one, build one.
3152 if (!canonTy) {
3153 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003154 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003155 QualType(), numElements, ASM, elementTypeQuals,
3156 brackets);
3157 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3158 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003159 }
3160
John McCall33ddac02011-01-19 10:06:00 +00003161 // Apply qualifiers from the element type to the array.
3162 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003163 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003164
David Majnemer16a74702015-07-24 05:54:19 +00003165 // If we didn't need extra canonicalization for the element type or the size
3166 // expression, then just use that as our result.
3167 if (QualType(canonElementType.Ty, 0) == elementType &&
3168 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003169 return canon;
3170
3171 // Otherwise, we need to build a type which follows the spelling
3172 // of the element type.
3173 DependentSizedArrayType *sugaredType
3174 = new (*this, TypeAlignment)
3175 DependentSizedArrayType(*this, elementType, canon, numElements,
3176 ASM, elementTypeQuals, brackets);
3177 Types.push_back(sugaredType);
3178 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003179}
3180
John McCall33ddac02011-01-19 10:06:00 +00003181QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003182 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003183 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003184 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003185 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003186
Craig Topper36250ad2014-05-12 05:36:57 +00003187 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003188 if (IncompleteArrayType *iat =
3189 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3190 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003191
3192 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003193 // either, so fill in the canonical type field. We also have to pull
3194 // qualifiers off the element type.
3195 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003196
John McCall33ddac02011-01-19 10:06:00 +00003197 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3198 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003199 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003200 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003201 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003202
3203 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003204 IncompleteArrayType *existing =
3205 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3206 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003207 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003208
John McCall33ddac02011-01-19 10:06:00 +00003209 IncompleteArrayType *newType = new (*this, TypeAlignment)
3210 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003211
John McCall33ddac02011-01-19 10:06:00 +00003212 IncompleteArrayTypes.InsertNode(newType, insertPos);
3213 Types.push_back(newType);
3214 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003215}
3216
Steve Naroff91fcddb2007-07-18 18:00:27 +00003217/// getVectorType - Return the unique reference to a vector type of
3218/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003219QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003220 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003221 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003222
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003223 // Check if we've already instantiated a vector of this type.
3224 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003225 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003226
Craig Topper36250ad2014-05-12 05:36:57 +00003227 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003228 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3229 return QualType(VTP, 0);
3230
3231 // If the element type isn't canonical, this won't be a canonical type either,
3232 // so fill in the canonical type field.
3233 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003234 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003235 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003236
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003237 // Get the new insert position for the node we care about.
3238 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003239 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003240 }
John McCall90d1c2d2009-09-24 23:30:46 +00003241 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003242 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003243 VectorTypes.InsertNode(New, InsertPos);
3244 Types.push_back(New);
3245 return QualType(New, 0);
3246}
3247
Nate Begemance4d7fc2008-04-18 23:10:10 +00003248/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003249/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003250QualType
3251ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003252 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003253
Steve Naroff91fcddb2007-07-18 18:00:27 +00003254 // Check if we've already instantiated a vector of this type.
3255 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003256 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003257 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003258 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003259 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3260 return QualType(VTP, 0);
3261
3262 // If the element type isn't canonical, this won't be a canonical type either,
3263 // so fill in the canonical type field.
3264 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003265 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003266 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003267
Steve Naroff91fcddb2007-07-18 18:00:27 +00003268 // Get the new insert position for the node we care about.
3269 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003270 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003271 }
John McCall90d1c2d2009-09-24 23:30:46 +00003272 ExtVectorType *New = new (*this, TypeAlignment)
3273 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003274 VectorTypes.InsertNode(New, InsertPos);
3275 Types.push_back(New);
3276 return QualType(New, 0);
3277}
3278
Jay Foad39c79802011-01-12 09:06:06 +00003279QualType
3280ASTContext::getDependentSizedExtVectorType(QualType vecType,
3281 Expr *SizeExpr,
3282 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003283 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003284 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003285 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003286
Craig Topper36250ad2014-05-12 05:36:57 +00003287 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003288 DependentSizedExtVectorType *Canon
3289 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3290 DependentSizedExtVectorType *New;
3291 if (Canon) {
3292 // We already have a canonical version of this array type; use it as
3293 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003294 New = new (*this, TypeAlignment)
3295 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3296 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003297 } else {
3298 QualType CanonVecTy = getCanonicalType(vecType);
3299 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003300 New = new (*this, TypeAlignment)
3301 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3302 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003303
3304 DependentSizedExtVectorType *CanonCheck
3305 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3306 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3307 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003308 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3309 } else {
3310 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3311 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00003312 New = new (*this, TypeAlignment)
3313 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003314 }
3315 }
Mike Stump11289f42009-09-09 15:08:12 +00003316
Douglas Gregor758a8692009-06-17 21:51:59 +00003317 Types.push_back(New);
3318 return QualType(New, 0);
3319}
3320
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003321QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3322 Expr *AddrSpaceExpr,
3323 SourceLocation AttrLoc) const {
3324 assert(AddrSpaceExpr->isInstantiationDependent());
3325
3326 QualType canonPointeeType = getCanonicalType(PointeeType);
3327
3328 void *insertPos = nullptr;
3329 llvm::FoldingSetNodeID ID;
3330 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3331 AddrSpaceExpr);
3332
3333 DependentAddressSpaceType *canonTy =
3334 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3335
3336 if (!canonTy) {
3337 canonTy = new (*this, TypeAlignment)
3338 DependentAddressSpaceType(*this, canonPointeeType,
3339 QualType(), AddrSpaceExpr, AttrLoc);
3340 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3341 Types.push_back(canonTy);
3342 }
3343
3344 if (canonPointeeType == PointeeType &&
3345 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
3346 return QualType(canonTy, 0);
3347
3348 DependentAddressSpaceType *sugaredType
3349 = new (*this, TypeAlignment)
3350 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
3351 AddrSpaceExpr, AttrLoc);
3352 Types.push_back(sugaredType);
3353 return QualType(sugaredType, 0);
3354}
3355
John McCall18afab72016-03-01 00:49:02 +00003356/// \brief Determine whether \p T is canonical as the result type of a function.
3357static bool isCanonicalResultType(QualType T) {
3358 return T.isCanonical() &&
3359 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3360 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3361}
3362
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003363/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003364QualType
3365ASTContext::getFunctionNoProtoType(QualType ResultTy,
3366 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003367 // Unique functions, to guarantee there is only one function of a particular
3368 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003369 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003370 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003371
Craig Topper36250ad2014-05-12 05:36:57 +00003372 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003373 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003374 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003375 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003376
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003377 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003378 if (!isCanonicalResultType(ResultTy)) {
3379 Canonical =
3380 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003381
Chris Lattner47955de2007-01-27 08:37:20 +00003382 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003383 FunctionNoProtoType *NewIP =
3384 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003385 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003386 }
Mike Stump11289f42009-09-09 15:08:12 +00003387
John McCall90d1c2d2009-09-24 23:30:46 +00003388 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003389 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003390 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003391 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003392 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003393}
3394
Douglas Gregora602a152015-10-01 20:20:47 +00003395CanQualType
3396ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3397 CanQualType CanResultType = getCanonicalType(ResultType);
3398
3399 // Canonical result types do not have ARC lifetime qualifiers.
3400 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3401 Qualifiers Qs = CanResultType.getQualifiers();
3402 Qs.removeObjCLifetime();
3403 return CanQualType::CreateUnsafe(
3404 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3405 }
3406
3407 return CanResultType;
3408}
3409
Richard Smith3c4f8d22016-10-16 17:54:23 +00003410static bool isCanonicalExceptionSpecification(
3411 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3412 if (ESI.Type == EST_None)
3413 return true;
3414 if (!NoexceptInType)
3415 return false;
3416
3417 // C++17 onwards: exception specification is part of the type, as a simple
3418 // boolean "can this function type throw".
3419 if (ESI.Type == EST_BasicNoexcept)
3420 return true;
3421
3422 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003423 // expansions (so we can't tell whether it's non-throwing) and all its
3424 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003425 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003426 bool AnyPackExpansions = false;
3427 for (QualType ET : ESI.Exceptions) {
3428 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003429 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003430 if (ET->getAs<PackExpansionType>())
3431 AnyPackExpansions = true;
3432 }
3433 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003434 }
3435
Richard Smith2a2cda52016-10-18 19:29:18 +00003436 // A noexcept(expr) specification is (possibly) canonical if expr is
3437 // value-dependent.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003438 if (ESI.Type == EST_ComputedNoexcept)
3439 return ESI.NoexceptExpr && ESI.NoexceptExpr->isValueDependent();
3440
3441 return false;
3442}
3443
Richard Smith304b1242016-10-18 20:13:25 +00003444QualType ASTContext::getFunctionTypeInternal(
3445 QualType ResultTy, ArrayRef<QualType> ArgArray,
3446 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003447 size_t NumArgs = ArgArray.size();
3448
Richard Smith2a2cda52016-10-18 19:29:18 +00003449 // Unique functions, to guarantee there is only one function of a particular
3450 // structure.
3451 llvm::FoldingSetNodeID ID;
3452 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3453 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003454
Richard Smith2a2cda52016-10-18 19:29:18 +00003455 QualType Canonical;
3456 bool Unique = false;
3457
3458 void *InsertPos = nullptr;
3459 if (FunctionProtoType *FPT =
3460 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3461 QualType Existing = QualType(FPT, 0);
3462
3463 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3464 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003465 // noexcept expression, or we're just looking for a canonical type.
3466 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003467 // sugar node to hold the concrete expression.
Richard Smith304b1242016-10-18 20:13:25 +00003468 if (OnlyWantCanonical || EPI.ExceptionSpec.Type != EST_ComputedNoexcept ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003469 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3470 return Existing;
3471
3472 // We need a new type sugar node for this one, to hold the new noexcept
3473 // expression. We do no canonicalization here, but that's OK since we don't
3474 // expect to see the same noexcept expression much more than once.
3475 Canonical = getCanonicalType(Existing);
3476 Unique = true;
3477 }
3478
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003479 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003480 bool IsCanonicalExceptionSpec =
3481 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3482
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003483 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003484 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003485 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003486 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003487 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003488 isCanonical = false;
3489
Richard Smith304b1242016-10-18 20:13:25 +00003490 if (OnlyWantCanonical)
3491 assert(isCanonical &&
3492 "given non-canonical parameters constructing canonical type");
3493
Richard Smith2a2cda52016-10-18 19:29:18 +00003494 // If this type isn't canonical, get the canonical version of it if we don't
3495 // already have it. The exception spec is only partially part of the
3496 // canonical type, and only in C++17 onwards.
3497 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003498 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003499 CanonicalArgs.reserve(NumArgs);
3500 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003501 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003502
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003503 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003504 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003505 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003506
3507 if (IsCanonicalExceptionSpec) {
3508 // Exception spec is already OK.
3509 } else if (NoexceptInType) {
3510 switch (EPI.ExceptionSpec.Type) {
3511 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3512 // We don't know yet. It shouldn't matter what we pick here; no-one
3513 // should ever look at this.
3514 LLVM_FALLTHROUGH;
Richard Smith2a2cda52016-10-18 19:29:18 +00003515 case EST_None: case EST_MSAny:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003516 CanonicalEPI.ExceptionSpec.Type = EST_None;
3517 break;
3518
Richard Smith2a2cda52016-10-18 19:29:18 +00003519 // A dynamic exception specification is almost always "not noexcept",
3520 // with the exception that a pack expansion might expand to no types.
3521 case EST_Dynamic: {
3522 bool AnyPacks = false;
3523 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3524 if (ET->getAs<PackExpansionType>())
3525 AnyPacks = true;
3526 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3527 }
3528 if (!AnyPacks)
3529 CanonicalEPI.ExceptionSpec.Type = EST_None;
3530 else {
3531 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3532 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3533 }
3534 break;
3535 }
3536
Richard Smith3c4f8d22016-10-16 17:54:23 +00003537 case EST_DynamicNone: case EST_BasicNoexcept:
3538 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3539 break;
3540
3541 case EST_ComputedNoexcept:
3542 llvm::APSInt Value(1);
3543 auto *E = CanonicalEPI.ExceptionSpec.NoexceptExpr;
3544 if (!E || !E->isIntegerConstantExpr(Value, *this, nullptr,
3545 /*IsEvaluated*/false)) {
3546 // This noexcept specification is invalid.
3547 // FIXME: Should this be able to happen?
3548 CanonicalEPI.ExceptionSpec.Type = EST_None;
3549 break;
3550 }
3551
3552 CanonicalEPI.ExceptionSpec.Type =
3553 Value.getBoolValue() ? EST_BasicNoexcept : EST_None;
3554 break;
3555 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003556 } else {
3557 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3558 }
John McCalldb40c7f2010-12-14 08:05:40 +00003559
Douglas Gregora602a152015-10-01 20:20:47 +00003560 // Adjust the canonical function result type.
3561 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003562 Canonical =
3563 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003564
Chris Lattnerfd4de792007-01-27 01:15:32 +00003565 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003566 FunctionProtoType *NewIP =
3567 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003568 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003569 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003570
John McCall31168b02011-06-15 23:02:42 +00003571 // FunctionProtoType objects are allocated with extra bytes after
3572 // them for three variable size arrays at the end:
3573 // - parameter types
3574 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003575 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003576 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003577 // expression, or information used to resolve the exception
3578 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003579 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003580 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003581
Richard Smith8acb4282014-07-31 21:57:55 +00003582 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3583 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3584 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003585 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003586 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003587 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003588 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003589 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003590 }
John McCall18afab72016-03-01 00:49:02 +00003591
3592 // Put the ExtParameterInfos last. If all were equal, it would make
3593 // more sense to put these before the exception specification, because
3594 // it's much easier to skip past them compared to the elaborate switch
3595 // required to skip the exception specification. However, all is not
3596 // equal; ExtParameterInfos are used to model very uncommon features,
3597 // and it's better not to burden the more common paths.
3598 if (EPI.ExtParameterInfos) {
3599 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3600 }
John McCall31168b02011-06-15 23:02:42 +00003601
John McCalldb40c7f2010-12-14 08:05:40 +00003602 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003603 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003604 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003605 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003606 if (!Unique)
3607 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003608 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003609}
Chris Lattneref51c202006-11-10 07:17:23 +00003610
Joey Goulye3c85de2016-12-01 11:30:49 +00003611QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003612 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003613 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003614
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00003615 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00003616 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003617 return QualType(PT, 0);
3618
3619 // If the pipe element type isn't canonical, this won't be a canonical type
3620 // either, so fill in the canonical type field.
3621 QualType Canonical;
3622 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003623 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003624
3625 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003626 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003627 assert(!NewIP && "Shouldn't be in the map!");
3628 (void)NewIP;
3629 }
Joey Goulye3c85de2016-12-01 11:30:49 +00003630 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003631 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003632 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003633 return QualType(New, 0);
3634}
3635
Joey Goulye3c85de2016-12-01 11:30:49 +00003636QualType ASTContext::getReadPipeType(QualType T) const {
3637 return getPipeType(T, true);
3638}
3639
Joey Gouly5788b782016-11-18 14:10:54 +00003640QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003641 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003642}
3643
John McCalle78aac42010-03-10 03:28:59 +00003644#ifndef NDEBUG
3645static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3646 if (!isa<CXXRecordDecl>(D)) return false;
3647 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3648 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3649 return true;
3650 if (RD->getDescribedClassTemplate() &&
3651 !isa<ClassTemplateSpecializationDecl>(RD))
3652 return true;
3653 return false;
3654}
3655#endif
3656
3657/// getInjectedClassNameType - Return the unique reference to the
3658/// injected class name type for the specified templated declaration.
3659QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003660 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003661 assert(NeedsInjectedClassNameType(Decl));
3662 if (Decl->TypeForDecl) {
3663 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003664 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003665 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3666 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3667 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3668 } else {
John McCall424cec92011-01-19 06:33:43 +00003669 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003670 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003671 Decl->TypeForDecl = newType;
3672 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003673 }
3674 return QualType(Decl->TypeForDecl, 0);
3675}
3676
Douglas Gregor83a586e2008-04-13 21:07:44 +00003677/// getTypeDeclType - Return the unique reference to the type for the
3678/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003679QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003680 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003681 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003682
Richard Smithdda56e42011-04-15 14:24:37 +00003683 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003684 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003685
John McCall96f0b5f2010-03-10 06:48:02 +00003686 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3687 "Template type parameter types are always available.");
3688
John McCall81e38502010-02-16 03:57:14 +00003689 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003690 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003691 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003692 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003693 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003694 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003695 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003696 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003697 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003698 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3699 Decl->TypeForDecl = newType;
3700 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003701 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003702 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003703
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003704 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003705}
3706
Chris Lattner32d920b2007-01-26 02:01:53 +00003707/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003708/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003709QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003710ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3711 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003712 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003713
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003714 if (Canonical.isNull())
3715 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003716 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003717 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003718 Decl->TypeForDecl = newType;
3719 Types.push_back(newType);
3720 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003721}
3722
Jay Foad39c79802011-01-12 09:06:06 +00003723QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003724 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3725
Douglas Gregorec9fd132012-01-14 16:38:05 +00003726 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003727 if (PrevDecl->TypeForDecl)
3728 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3729
John McCall424cec92011-01-19 06:33:43 +00003730 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3731 Decl->TypeForDecl = newType;
3732 Types.push_back(newType);
3733 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003734}
3735
Jay Foad39c79802011-01-12 09:06:06 +00003736QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003737 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3738
Douglas Gregorec9fd132012-01-14 16:38:05 +00003739 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003740 if (PrevDecl->TypeForDecl)
3741 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3742
John McCall424cec92011-01-19 06:33:43 +00003743 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3744 Decl->TypeForDecl = newType;
3745 Types.push_back(newType);
3746 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003747}
3748
John McCall81904512011-01-06 01:58:22 +00003749QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3750 QualType modifiedType,
3751 QualType equivalentType) {
3752 llvm::FoldingSetNodeID id;
3753 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3754
Craig Topper36250ad2014-05-12 05:36:57 +00003755 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003756 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3757 if (type) return QualType(type, 0);
3758
3759 QualType canon = getCanonicalType(equivalentType);
3760 type = new (*this, TypeAlignment)
3761 AttributedType(canon, attrKind, modifiedType, equivalentType);
3762
3763 Types.push_back(type);
3764 AttributedTypes.InsertNode(type, insertPos);
3765
3766 return QualType(type, 0);
3767}
3768
John McCallcebee162009-10-18 09:09:24 +00003769/// \brief Retrieve a substitution-result type.
3770QualType
3771ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003772 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003773 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003774 && "replacement types must always be canonical");
3775
3776 llvm::FoldingSetNodeID ID;
3777 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003778 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003779 SubstTemplateTypeParmType *SubstParm
3780 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3781
3782 if (!SubstParm) {
3783 SubstParm = new (*this, TypeAlignment)
3784 SubstTemplateTypeParmType(Parm, Replacement);
3785 Types.push_back(SubstParm);
3786 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3787 }
3788
3789 return QualType(SubstParm, 0);
3790}
3791
Douglas Gregorada4b792011-01-14 02:55:32 +00003792/// \brief Retrieve a
3793QualType ASTContext::getSubstTemplateTypeParmPackType(
3794 const TemplateTypeParmType *Parm,
3795 const TemplateArgument &ArgPack) {
3796#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003797 for (const auto &P : ArgPack.pack_elements()) {
3798 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3799 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003800 }
3801#endif
3802
3803 llvm::FoldingSetNodeID ID;
3804 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003805 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003806 if (SubstTemplateTypeParmPackType *SubstParm
3807 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3808 return QualType(SubstParm, 0);
3809
3810 QualType Canon;
3811 if (!Parm->isCanonicalUnqualified()) {
3812 Canon = getCanonicalType(QualType(Parm, 0));
3813 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3814 ArgPack);
3815 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3816 }
3817
3818 SubstTemplateTypeParmPackType *SubstParm
3819 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3820 ArgPack);
3821 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00003822 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Douglas Gregorada4b792011-01-14 02:55:32 +00003823 return QualType(SubstParm, 0);
3824}
3825
Douglas Gregoreff93e02009-02-05 23:33:38 +00003826/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003827/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003828/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003829QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003830 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003831 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003832 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003833 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003834 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003835 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003836 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3837
3838 if (TypeParm)
3839 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003840
Chandler Carruth08836322011-05-01 00:51:33 +00003841 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003842 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003843 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003844
3845 TemplateTypeParmType *TypeCheck
3846 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3847 assert(!TypeCheck && "Template type parameter canonical type broken");
3848 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003849 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003850 TypeParm = new (*this, TypeAlignment)
3851 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003852
3853 Types.push_back(TypeParm);
3854 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3855
3856 return QualType(TypeParm, 0);
3857}
3858
John McCalle78aac42010-03-10 03:28:59 +00003859TypeSourceInfo *
3860ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3861 SourceLocation NameLoc,
3862 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003863 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003864 assert(!Name.getAsDependentTemplateName() &&
3865 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003866 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003867
3868 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003869 TemplateSpecializationTypeLoc TL =
3870 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003871 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003872 TL.setTemplateNameLoc(NameLoc);
3873 TL.setLAngleLoc(Args.getLAngleLoc());
3874 TL.setRAngleLoc(Args.getRAngleLoc());
3875 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3876 TL.setArgLocInfo(i, Args[i].getLocInfo());
3877 return DI;
3878}
3879
Mike Stump11289f42009-09-09 15:08:12 +00003880QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003881ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003882 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003883 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003884 assert(!Template.getAsDependentTemplateName() &&
3885 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00003886
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003887 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00003888 ArgVec.reserve(Args.size());
3889 for (const TemplateArgumentLoc &Arg : Args.arguments())
3890 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00003891
David Majnemer6fbeee32016-07-07 04:43:07 +00003892 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003893}
3894
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003895#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00003896static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3897 for (const TemplateArgument &Arg : Args)
3898 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003899 return true;
3900
3901 return true;
3902}
3903#endif
3904
John McCall0ad16662009-10-29 08:12:44 +00003905QualType
3906ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00003907 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003908 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003909 assert(!Template.getAsDependentTemplateName() &&
3910 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003911 // Look through qualified template names.
3912 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3913 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003914
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003915 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003916 Template.getAsTemplateDecl() &&
3917 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003918 QualType CanonType;
3919 if (!Underlying.isNull())
3920 CanonType = getCanonicalType(Underlying);
3921 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003922 // We can get here with an alias template when the specialization contains
3923 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00003924 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003925 "Caller must compute aliased type");
3926 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003927 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003928 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003929
Douglas Gregora8e02e72009-07-28 23:00:59 +00003930 // Allocate the (non-canonical) template specialization type, but don't
3931 // try to unique it: these types typically have location information that
3932 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003933 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00003934 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003935 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003936 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003937 TemplateSpecializationType *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00003938 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003939 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003940
Douglas Gregor8bf42052009-02-09 18:46:07 +00003941 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003942 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003943}
3944
David Majnemer6fbeee32016-07-07 04:43:07 +00003945QualType ASTContext::getCanonicalTemplateSpecializationType(
3946 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003947 assert(!Template.getAsDependentTemplateName() &&
3948 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003949
Douglas Gregore29139c2011-03-03 17:04:51 +00003950 // Look through qualified template names.
3951 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3952 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003953
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003954 // Build the canonical template specialization type.
3955 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003956 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00003957 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003958 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00003959 for (const TemplateArgument &Arg : Args)
3960 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003961
3962 // Determine whether this canonical template specialization type already
3963 // exists.
3964 llvm::FoldingSetNodeID ID;
3965 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003966 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003967
Craig Topper36250ad2014-05-12 05:36:57 +00003968 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003969 TemplateSpecializationType *Spec
3970 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3971
3972 if (!Spec) {
3973 // Allocate a new canonical template specialization type.
3974 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3975 sizeof(TemplateArgument) * NumArgs),
3976 TypeAlignment);
3977 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003978 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003979 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003980 Types.push_back(Spec);
3981 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3982 }
3983
3984 assert(Spec->isDependentType() &&
3985 "Non-dependent template-id type must have a canonical type");
3986 return QualType(Spec, 0);
3987}
3988
3989QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003990ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3991 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003992 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003993 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003994 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003995
Craig Topper36250ad2014-05-12 05:36:57 +00003996 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003997 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003998 if (T)
3999 return QualType(T, 0);
4000
Douglas Gregorc42075a2010-02-04 18:10:26 +00004001 QualType Canon = NamedType;
4002 if (!Canon.isCanonical()) {
4003 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004004 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4005 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004006 (void)CheckT;
4007 }
4008
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004009 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00004010 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004011 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004012 return QualType(T, 0);
4013}
4014
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004015QualType
Jay Foad39c79802011-01-12 09:06:06 +00004016ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004017 llvm::FoldingSetNodeID ID;
4018 ParenType::Profile(ID, InnerType);
4019
Craig Topper36250ad2014-05-12 05:36:57 +00004020 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004021 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4022 if (T)
4023 return QualType(T, 0);
4024
4025 QualType Canon = InnerType;
4026 if (!Canon.isCanonical()) {
4027 Canon = getCanonicalType(InnerType);
4028 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4029 assert(!CheckT && "Paren canonical type broken");
4030 (void)CheckT;
4031 }
4032
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004033 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004034 Types.push_back(T);
4035 ParenTypes.InsertNode(T, InsertPos);
4036 return QualType(T, 0);
4037}
4038
Douglas Gregor02085352010-03-31 20:19:30 +00004039QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4040 NestedNameSpecifier *NNS,
4041 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004042 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004043 if (Canon.isNull()) {
4044 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004045 if (CanonNNS != NNS)
4046 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004047 }
4048
4049 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004050 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004051
Craig Topper36250ad2014-05-12 05:36:57 +00004052 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004053 DependentNameType *T
4054 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004055 if (T)
4056 return QualType(T, 0);
4057
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004058 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004059 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004060 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004061 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004062}
4063
Mike Stump11289f42009-09-09 15:08:12 +00004064QualType
John McCallc392f372010-06-11 00:33:02 +00004065ASTContext::getDependentTemplateSpecializationType(
4066 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004067 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004068 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004069 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004070 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004071 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004072 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4073 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004074 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004075}
4076
4077QualType
4078ASTContext::getDependentTemplateSpecializationType(
4079 ElaboratedTypeKeyword Keyword,
4080 NestedNameSpecifier *NNS,
4081 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004082 ArrayRef<TemplateArgument> Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00004083 assert((!NNS || NNS->isDependent()) &&
4084 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004085
Douglas Gregorc42075a2010-02-04 18:10:26 +00004086 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004087 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004088 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004089
Craig Topper36250ad2014-05-12 05:36:57 +00004090 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004091 DependentTemplateSpecializationType *T
4092 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004093 if (T)
4094 return QualType(T, 0);
4095
John McCallc392f372010-06-11 00:33:02 +00004096 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004097
John McCallc392f372010-06-11 00:33:02 +00004098 ElaboratedTypeKeyword CanonKeyword = Keyword;
4099 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4100
4101 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004102 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004103 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004104 for (unsigned I = 0; I != NumArgs; ++I) {
4105 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4106 if (!CanonArgs[I].structurallyEquals(Args[I]))
4107 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004108 }
4109
John McCallc392f372010-06-11 00:33:02 +00004110 QualType Canon;
4111 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4112 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004113 Name,
4114 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004115
4116 // Find the insert position again.
4117 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4118 }
4119
4120 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4121 sizeof(TemplateArgument) * NumArgs),
4122 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004123 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004124 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004125 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004126 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004127 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004128}
4129
Richard Smith32918772017-02-14 00:25:28 +00004130TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4131 TemplateArgument Arg;
4132 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4133 QualType ArgType = getTypeDeclType(TTP);
4134 if (TTP->isParameterPack())
4135 ArgType = getPackExpansionType(ArgType, None);
4136
4137 Arg = TemplateArgument(ArgType);
4138 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4139 Expr *E = new (*this) DeclRefExpr(
4140 NTTP, /*enclosing*/false,
4141 NTTP->getType().getNonLValueExprType(*this),
4142 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4143
4144 if (NTTP->isParameterPack())
4145 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4146 None);
4147 Arg = TemplateArgument(E);
4148 } else {
4149 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4150 if (TTP->isParameterPack())
4151 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4152 else
4153 Arg = TemplateArgument(TemplateName(TTP));
4154 }
4155
4156 if (Param->isTemplateParameterPack())
4157 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4158
4159 return Arg;
4160}
4161
Richard Smith43e14d22016-12-23 02:10:11 +00004162void
4163ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4164 SmallVectorImpl<TemplateArgument> &Args) {
4165 Args.reserve(Args.size() + Params->size());
4166
Richard Smith32918772017-02-14 00:25:28 +00004167 for (NamedDecl *Param : *Params)
4168 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004169}
4170
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004171QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004172 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004173 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004174 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004175
4176 assert(Pattern->containsUnexpandedParameterPack() &&
4177 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004178 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004179 PackExpansionType *T
4180 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4181 if (T)
4182 return QualType(T, 0);
4183
4184 QualType Canon;
4185 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004186 Canon = getCanonicalType(Pattern);
4187 // The canonical type might not contain an unexpanded parameter pack, if it
4188 // contains an alias template specialization which ignores one of its
4189 // parameters.
4190 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004191 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004192
Richard Smith68eea502012-07-16 00:20:35 +00004193 // Find the insert position again, in case we inserted an element into
4194 // PackExpansionTypes and invalidated our insert position.
4195 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4196 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004197 }
4198
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004199 T = new (*this, TypeAlignment)
4200 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004201 Types.push_back(T);
4202 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004203 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004204}
4205
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004206/// CmpProtocolNames - Comparison predicate for sorting protocols
4207/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004208static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4209 ObjCProtocolDecl *const *RHS) {
4210 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004211}
4212
Craig Topper1f26d5b2016-01-03 19:43:23 +00004213static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4214 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004215
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004216 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4217 return false;
4218
Craig Topper1f26d5b2016-01-03 19:43:23 +00004219 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004220 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004221 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004222 return false;
4223 return true;
4224}
4225
Craig Topper6a8c1512015-10-22 01:56:18 +00004226static void
4227SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004228 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004229 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004230
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004231 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004232 for (ObjCProtocolDecl *&P : Protocols)
4233 P = P->getCanonicalDecl();
4234
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004235 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004236 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4237 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004238}
4239
John McCall8b07ec22010-05-15 11:32:37 +00004240QualType ASTContext::getObjCObjectType(QualType BaseType,
4241 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004242 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004243 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004244 llvm::makeArrayRef(Protocols, NumProtocols),
4245 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004246}
4247
4248QualType ASTContext::getObjCObjectType(
4249 QualType baseType,
4250 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004251 ArrayRef<ObjCProtocolDecl *> protocols,
4252 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004253 // If the base type is an interface and there aren't any protocols or
4254 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004255 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4256 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004257 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004258
4259 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004260 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004261 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004262 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004263 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4264 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004265
Douglas Gregore9d95f12015-07-07 03:57:35 +00004266 // Determine the type arguments to be used for canonicalization,
4267 // which may be explicitly specified here or written on the base
4268 // type.
4269 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4270 if (effectiveTypeArgs.empty()) {
4271 if (auto baseObject = baseType->getAs<ObjCObjectType>())
4272 effectiveTypeArgs = baseObject->getTypeArgs();
4273 }
John McCallfc93cf92009-10-22 22:37:11 +00004274
Douglas Gregore9d95f12015-07-07 03:57:35 +00004275 // Build the canonical type, which has the canonical base type and a
4276 // sorted-and-uniqued list of protocols and the type arguments
4277 // canonicalized.
4278 QualType canonical;
4279 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4280 effectiveTypeArgs.end(),
4281 [&](QualType type) {
4282 return type.isCanonical();
4283 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004284 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004285 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4286 // Determine the canonical type arguments.
4287 ArrayRef<QualType> canonTypeArgs;
4288 SmallVector<QualType, 4> canonTypeArgsVec;
4289 if (!typeArgsAreCanonical) {
4290 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4291 for (auto typeArg : effectiveTypeArgs)
4292 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4293 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004294 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004295 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004296 }
4297
Douglas Gregore9d95f12015-07-07 03:57:35 +00004298 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4299 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4300 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004301 canonProtocolsVec.append(protocols.begin(), protocols.end());
4302 SortAndUniqueProtocols(canonProtocolsVec);
4303 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004304 } else {
4305 canonProtocols = protocols;
4306 }
4307
4308 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004309 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004310
John McCallfc93cf92009-10-22 22:37:11 +00004311 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004312 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4313 }
4314
Douglas Gregore9d95f12015-07-07 03:57:35 +00004315 unsigned size = sizeof(ObjCObjectTypeImpl);
4316 size += typeArgs.size() * sizeof(QualType);
4317 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4318 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00004319 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004320 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4321 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004322
4323 Types.push_back(T);
4324 ObjCObjectTypes.InsertNode(T, InsertPos);
4325 return QualType(T, 0);
4326}
4327
Manman Ren3569eb52016-09-13 17:03:12 +00004328/// Apply Objective-C protocol qualifiers to the given type.
4329/// If this is for the canonical type of a type parameter, we can apply
4330/// protocol qualifiers on the ObjCObjectPointerType.
4331QualType
4332ASTContext::applyObjCProtocolQualifiers(QualType type,
4333 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4334 bool allowOnPointerType) const {
4335 hasError = false;
4336
Manman Renc5705ba2016-09-13 17:41:05 +00004337 if (const ObjCTypeParamType *objT =
4338 dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4339 return getObjCTypeParamType(objT->getDecl(), protocols);
4340 }
4341
Manman Ren3569eb52016-09-13 17:03:12 +00004342 // Apply protocol qualifiers to ObjCObjectPointerType.
4343 if (allowOnPointerType) {
4344 if (const ObjCObjectPointerType *objPtr =
4345 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4346 const ObjCObjectType *objT = objPtr->getObjectType();
4347 // Merge protocol lists and construct ObjCObjectType.
4348 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4349 protocolsVec.append(objT->qual_begin(),
4350 objT->qual_end());
4351 protocolsVec.append(protocols.begin(), protocols.end());
4352 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4353 type = getObjCObjectType(
4354 objT->getBaseType(),
4355 objT->getTypeArgsAsWritten(),
4356 protocols,
4357 objT->isKindOfTypeAsWritten());
4358 return getObjCObjectPointerType(type);
4359 }
4360 }
4361
4362 // Apply protocol qualifiers to ObjCObjectType.
4363 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4364 // FIXME: Check for protocols to which the class type is already
4365 // known to conform.
4366
4367 return getObjCObjectType(objT->getBaseType(),
4368 objT->getTypeArgsAsWritten(),
4369 protocols,
4370 objT->isKindOfTypeAsWritten());
4371 }
4372
4373 // If the canonical type is ObjCObjectType, ...
4374 if (type->isObjCObjectType()) {
4375 // Silently overwrite any existing protocol qualifiers.
4376 // TODO: determine whether that's the right thing to do.
4377
4378 // FIXME: Check for protocols to which the class type is already
4379 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004380 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004381 }
4382
4383 // id<protocol-list>
4384 if (type->isObjCIdType()) {
4385 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004386 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004387 objPtr->isKindOfType());
4388 return getObjCObjectPointerType(type);
4389 }
4390
4391 // Class<protocol-list>
4392 if (type->isObjCClassType()) {
4393 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004394 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004395 objPtr->isKindOfType());
4396 return getObjCObjectPointerType(type);
4397 }
4398
4399 hasError = true;
4400 return type;
4401}
4402
Manman Rene6be26c2016-09-13 17:25:08 +00004403QualType
4404ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4405 ArrayRef<ObjCProtocolDecl *> protocols,
4406 QualType Canonical) const {
4407 // Look in the folding set for an existing type.
4408 llvm::FoldingSetNodeID ID;
4409 ObjCTypeParamType::Profile(ID, Decl, protocols);
4410 void *InsertPos = nullptr;
4411 if (ObjCTypeParamType *TypeParam =
4412 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4413 return QualType(TypeParam, 0);
4414
4415 if (Canonical.isNull()) {
4416 // We canonicalize to the underlying type.
4417 Canonical = getCanonicalType(Decl->getUnderlyingType());
4418 if (!protocols.empty()) {
4419 // Apply the protocol qualifers.
4420 bool hasError;
4421 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4422 true/*allowOnPointerType*/);
4423 assert(!hasError && "Error when apply protocol qualifier to bound type");
4424 }
4425 }
4426
4427 unsigned size = sizeof(ObjCTypeParamType);
4428 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4429 void *mem = Allocate(size, TypeAlignment);
4430 ObjCTypeParamType *newType = new (mem)
4431 ObjCTypeParamType(Decl, Canonical, protocols);
4432
4433 Types.push_back(newType);
4434 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4435 return QualType(newType, 0);
4436}
4437
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004438/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4439/// protocol list adopt all protocols in QT's qualified-id protocol
4440/// list.
4441bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4442 ObjCInterfaceDecl *IC) {
4443 if (!QT->isObjCQualifiedIdType())
4444 return false;
4445
4446 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
4447 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004448 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004449 if (!IC->ClassImplementsProtocol(Proto, false))
4450 return false;
4451 }
4452 return true;
4453 }
4454 return false;
4455}
4456
4457/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4458/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4459/// of protocols.
4460bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4461 ObjCInterfaceDecl *IDecl) {
4462 if (!QT->isObjCQualifiedIdType())
4463 return false;
4464 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
4465 if (!OPT)
4466 return false;
4467 if (!IDecl->hasDefinition())
4468 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004469 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4470 CollectInheritedProtocols(IDecl, InheritedProtocols);
4471 if (InheritedProtocols.empty())
4472 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004473 // Check that if every protocol in list of id<plist> conforms to a protcol
4474 // of IDecl's, then bridge casting is ok.
4475 bool Conforms = false;
4476 for (auto *Proto : OPT->quals()) {
4477 Conforms = false;
4478 for (auto *PI : InheritedProtocols) {
4479 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4480 Conforms = true;
4481 break;
4482 }
4483 }
4484 if (!Conforms)
4485 break;
4486 }
4487 if (Conforms)
4488 return true;
4489
Aaron Ballman83731462014-03-17 16:14:00 +00004490 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004491 // If both the right and left sides have qualifiers.
4492 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004493 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004494 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004495 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004496 break;
4497 }
4498 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004499 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004500 }
4501 return true;
4502}
4503
John McCall8b07ec22010-05-15 11:32:37 +00004504/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4505/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004506QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004507 llvm::FoldingSetNodeID ID;
4508 ObjCObjectPointerType::Profile(ID, ObjectT);
4509
Craig Topper36250ad2014-05-12 05:36:57 +00004510 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004511 if (ObjCObjectPointerType *QT =
4512 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4513 return QualType(QT, 0);
4514
4515 // Find the canonical object type.
4516 QualType Canonical;
4517 if (!ObjectT.isCanonical()) {
4518 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4519
4520 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004521 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4522 }
4523
Douglas Gregorf85bee62010-02-08 22:59:26 +00004524 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004525 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4526 ObjCObjectPointerType *QType =
4527 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004528
Steve Narofffb4330f2009-06-17 22:40:22 +00004529 Types.push_back(QType);
4530 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004531 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004532}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004533
Douglas Gregor1c283312010-08-11 12:19:30 +00004534/// getObjCInterfaceType - Return the unique reference to the type for the
4535/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004536QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4537 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004538 if (Decl->TypeForDecl)
4539 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004540
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004541 if (PrevDecl) {
4542 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4543 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4544 return QualType(PrevDecl->TypeForDecl, 0);
4545 }
4546
Douglas Gregor7671e532011-12-16 16:34:57 +00004547 // Prefer the definition, if there is one.
4548 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4549 Decl = Def;
4550
Douglas Gregor1c283312010-08-11 12:19:30 +00004551 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4552 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
4553 Decl->TypeForDecl = T;
4554 Types.push_back(T);
4555 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004556}
4557
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004558/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4559/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004560/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004561/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004562/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004563QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004564 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004565 if (tofExpr->isTypeDependent()) {
4566 llvm::FoldingSetNodeID ID;
4567 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004568
Craig Topper36250ad2014-05-12 05:36:57 +00004569 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004570 DependentTypeOfExprType *Canon
4571 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4572 if (Canon) {
4573 // We already have a "canonical" version of an identical, dependent
4574 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004575 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004576 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004577 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004578 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004579 Canon
4580 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004581 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4582 toe = Canon;
4583 }
4584 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004585 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004586 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004587 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004588 Types.push_back(toe);
4589 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004590}
4591
Steve Naroffa773cd52007-08-01 18:02:17 +00004592/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004593/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004594/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004595/// an issue. This doesn't affect the type checker, since it operates
4596/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004597QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004598 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00004599 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004600 Types.push_back(tot);
4601 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004602}
4603
Richard Smith8eb1d322014-06-05 20:13:13 +00004604/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4605/// nodes. This would never be helpful, since each such type has its own
4606/// expression, and would not give a significant memory saving, since there
4607/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004608QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004609 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004610
4611 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004612 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004613 // unique dependent type. Two such decltype-specifiers refer to the same
4614 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004615 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004616 llvm::FoldingSetNodeID ID;
4617 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004618
Craig Topper36250ad2014-05-12 05:36:57 +00004619 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004620 DependentDecltypeType *Canon
4621 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004622 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004623 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004624 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004625 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004626 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004627 dt = new (*this, TypeAlignment)
4628 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004629 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004630 dt = new (*this, TypeAlignment)
4631 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004632 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004633 Types.push_back(dt);
4634 return QualType(dt, 0);
4635}
4636
Alexis Hunte852b102011-05-24 22:41:36 +00004637/// getUnaryTransformationType - We don't unique these, since the memory
4638/// savings are minimal and these are rare.
4639QualType ASTContext::getUnaryTransformType(QualType BaseType,
4640 QualType UnderlyingType,
4641 UnaryTransformType::UTTKind Kind)
4642 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004643 UnaryTransformType *ut = nullptr;
4644
4645 if (BaseType->isDependentType()) {
4646 // Look in the folding set for an existing type.
4647 llvm::FoldingSetNodeID ID;
4648 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4649
4650 void *InsertPos = nullptr;
4651 DependentUnaryTransformType *Canon
4652 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4653
4654 if (!Canon) {
4655 // Build a new, canonical __underlying_type(type) type.
4656 Canon = new (*this, TypeAlignment)
4657 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4658 Kind);
4659 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4660 }
4661 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4662 QualType(), Kind,
4663 QualType(Canon, 0));
4664 } else {
4665 QualType CanonType = getCanonicalType(UnderlyingType);
4666 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4667 UnderlyingType, Kind,
4668 CanonType);
4669 }
4670 Types.push_back(ut);
4671 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004672}
4673
Richard Smith2a7d4812013-05-04 07:00:32 +00004674/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4675/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4676/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004677QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004678 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004679 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004680 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004681
Richard Smith2a7d4812013-05-04 07:00:32 +00004682 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004683 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004684 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004685 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004686 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4687 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004688
Richard Smith74aeef52013-04-26 16:15:35 +00004689 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004690 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004691 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004692 Types.push_back(AT);
4693 if (InsertPos)
4694 AutoTypes.InsertNode(AT, InsertPos);
4695 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004696}
4697
Richard Smith600b5262017-01-26 20:40:47 +00004698/// Return the uniqued reference to the deduced template specialization type
4699/// which has been deduced to the given type, or to the canonical undeduced
4700/// such type, or the canonical deduced-but-dependent such type.
4701QualType ASTContext::getDeducedTemplateSpecializationType(
4702 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4703 // Look in the folding set for an existing type.
4704 void *InsertPos = nullptr;
4705 llvm::FoldingSetNodeID ID;
4706 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4707 IsDependent);
4708 if (DeducedTemplateSpecializationType *DTST =
4709 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4710 return QualType(DTST, 0);
4711
4712 DeducedTemplateSpecializationType *DTST = new (*this, TypeAlignment)
4713 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4714 Types.push_back(DTST);
4715 if (InsertPos)
4716 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4717 return QualType(DTST, 0);
4718}
4719
Eli Friedman0dfb8892011-10-06 23:00:33 +00004720/// getAtomicType - Return the uniqued reference to the atomic type for
4721/// the given value type.
4722QualType ASTContext::getAtomicType(QualType T) const {
4723 // Unique pointers, to guarantee there is only one pointer of a particular
4724 // structure.
4725 llvm::FoldingSetNodeID ID;
4726 AtomicType::Profile(ID, T);
4727
Craig Topper36250ad2014-05-12 05:36:57 +00004728 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004729 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4730 return QualType(AT, 0);
4731
4732 // If the atomic value type isn't canonical, this won't be a canonical type
4733 // either, so fill in the canonical type field.
4734 QualType Canonical;
4735 if (!T.isCanonical()) {
4736 Canonical = getAtomicType(getCanonicalType(T));
4737
4738 // Get the new insert position for the node we care about.
4739 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004740 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004741 }
4742 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4743 Types.push_back(New);
4744 AtomicTypes.InsertNode(New, InsertPos);
4745 return QualType(New, 0);
4746}
4747
Richard Smith02e85f32011-04-14 22:09:26 +00004748/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4749QualType ASTContext::getAutoDeductType() const {
4750 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004751 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004752 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004753 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004754 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004755 return AutoDeductTy;
4756}
4757
4758/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4759QualType ASTContext::getAutoRRefDeductType() const {
4760 if (AutoRRefDeductTy.isNull())
4761 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4762 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4763 return AutoRRefDeductTy;
4764}
4765
Chris Lattnerfb072462007-01-23 05:45:31 +00004766/// getTagDeclType - Return the unique reference to the type for the
4767/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004768QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004769 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004770 // FIXME: What is the design on getTagDeclType when it requires casting
4771 // away const? mutable?
4772 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004773}
4774
Mike Stump11289f42009-09-09 15:08:12 +00004775/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4776/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4777/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004778CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004779 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004780}
Chris Lattnerfb072462007-01-23 05:45:31 +00004781
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00004782/// Return the unique signed counterpart of the integer type
4783/// corresponding to size_t.
4784CanQualType ASTContext::getSignedSizeType() const {
4785 return getFromTargetType(Target->getSignedSizeType());
4786}
4787
Hans Wennborg27541db2011-10-27 08:29:09 +00004788/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4789CanQualType ASTContext::getIntMaxType() const {
4790 return getFromTargetType(Target->getIntMaxType());
4791}
4792
4793/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4794CanQualType ASTContext::getUIntMaxType() const {
4795 return getFromTargetType(Target->getUIntMaxType());
4796}
4797
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004798/// getSignedWCharType - Return the type of "signed wchar_t".
4799/// Used when in C++, as a GCC extension.
4800QualType ASTContext::getSignedWCharType() const {
4801 // FIXME: derive from "Target" ?
4802 return WCharTy;
4803}
4804
4805/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4806/// Used when in C++, as a GCC extension.
4807QualType ASTContext::getUnsignedWCharType() const {
4808 // FIXME: derive from "Target" ?
4809 return UnsignedIntTy;
4810}
4811
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004812QualType ASTContext::getIntPtrType() const {
4813 return getFromTargetType(Target->getIntPtrType());
4814}
4815
4816QualType ASTContext::getUIntPtrType() const {
4817 return getCorrespondingUnsignedType(getIntPtrType());
4818}
4819
Hans Wennborg27541db2011-10-27 08:29:09 +00004820/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004821/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4822QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004823 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004824}
4825
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00004826/// \brief Return the unique unsigned counterpart of "ptrdiff_t"
4827/// integer type. The standard (C11 7.21.6.1p7) refers to this type
4828/// in the definition of %tu format specifier.
4829QualType ASTContext::getUnsignedPointerDiffType() const {
4830 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
4831}
4832
Eli Friedman4e91899e2012-11-27 02:58:24 +00004833/// \brief Return the unique type for "pid_t" defined in
4834/// <sys/types.h>. We need this to compute the correct type for vfork().
4835QualType ASTContext::getProcessIDType() const {
4836 return getFromTargetType(Target->getProcessIDType());
4837}
4838
Chris Lattnera21ad802008-04-02 05:18:44 +00004839//===----------------------------------------------------------------------===//
4840// Type Operators
4841//===----------------------------------------------------------------------===//
4842
Jay Foad39c79802011-01-12 09:06:06 +00004843CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004844 // Push qualifiers into arrays, and then discard any remaining
4845 // qualifiers.
4846 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004847 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004848 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004849 QualType Result;
4850 if (isa<ArrayType>(Ty)) {
4851 Result = getArrayDecayedType(QualType(Ty,0));
4852 } else if (isa<FunctionType>(Ty)) {
4853 Result = getPointerType(QualType(Ty, 0));
4854 } else {
4855 Result = QualType(Ty, 0);
4856 }
4857
4858 return CanQualType::CreateUnsafe(Result);
4859}
4860
John McCall6c9dd522011-01-18 07:41:22 +00004861QualType ASTContext::getUnqualifiedArrayType(QualType type,
4862 Qualifiers &quals) {
4863 SplitQualType splitType = type.getSplitUnqualifiedType();
4864
4865 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4866 // the unqualified desugared type and then drops it on the floor.
4867 // We then have to strip that sugar back off with
4868 // getUnqualifiedDesugaredType(), which is silly.
4869 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004870 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004871
4872 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004873 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004874 quals = splitType.Quals;
4875 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004876 }
4877
John McCall6c9dd522011-01-18 07:41:22 +00004878 // Otherwise, recurse on the array's element type.
4879 QualType elementType = AT->getElementType();
4880 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4881
4882 // If that didn't change the element type, AT has no qualifiers, so we
4883 // can just use the results in splitType.
4884 if (elementType == unqualElementType) {
4885 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004886 quals = splitType.Quals;
4887 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004888 }
4889
4890 // Otherwise, add in the qualifiers from the outermost type, then
4891 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004892 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004893
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004894 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004895 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004896 CAT->getSizeModifier(), 0);
4897 }
4898
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004899 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004900 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004901 }
4902
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004903 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004904 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004905 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004906 VAT->getSizeModifier(),
4907 VAT->getIndexTypeCVRQualifiers(),
4908 VAT->getBracketsRange());
4909 }
4910
4911 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004912 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004913 DSAT->getSizeModifier(), 0,
4914 SourceRange());
4915}
4916
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004917/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4918/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4919/// they point to and return true. If T1 and T2 aren't pointer types
4920/// or pointer-to-member types, or if they are not similar at this
4921/// level, returns false and leaves T1 and T2 unchanged. Top-level
4922/// qualifiers on T1 and T2 are ignored. This function will typically
4923/// be called in a loop that successively "unwraps" pointer and
4924/// pointer-to-member types to compare them at each level.
4925bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4926 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4927 *T2PtrType = T2->getAs<PointerType>();
4928 if (T1PtrType && T2PtrType) {
4929 T1 = T1PtrType->getPointeeType();
4930 T2 = T2PtrType->getPointeeType();
4931 return true;
4932 }
4933
4934 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4935 *T2MPType = T2->getAs<MemberPointerType>();
4936 if (T1MPType && T2MPType &&
4937 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4938 QualType(T2MPType->getClass(), 0))) {
4939 T1 = T1MPType->getPointeeType();
4940 T2 = T2MPType->getPointeeType();
4941 return true;
4942 }
4943
David Blaikiebbafb8a2012-03-11 07:00:24 +00004944 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004945 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4946 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4947 if (T1OPType && T2OPType) {
4948 T1 = T1OPType->getPointeeType();
4949 T2 = T2OPType->getPointeeType();
4950 return true;
4951 }
4952 }
4953
4954 // FIXME: Block pointers, too?
4955
4956 return false;
4957}
4958
Jay Foad39c79802011-01-12 09:06:06 +00004959DeclarationNameInfo
4960ASTContext::getNameForTemplate(TemplateName Name,
4961 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004962 switch (Name.getKind()) {
4963 case TemplateName::QualifiedTemplate:
4964 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004965 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004966 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4967 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004968
John McCalld9dfe3a2011-06-30 08:33:18 +00004969 case TemplateName::OverloadedTemplate: {
4970 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4971 // DNInfo work in progress: CHECKME: what about DNLoc?
4972 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4973 }
4974
4975 case TemplateName::DependentTemplate: {
4976 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004977 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004978 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004979 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4980 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004981 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004982 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4983 // DNInfo work in progress: FIXME: source locations?
4984 DeclarationNameLoc DNLoc;
4985 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4986 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4987 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004988 }
4989 }
4990
John McCalld9dfe3a2011-06-30 08:33:18 +00004991 case TemplateName::SubstTemplateTemplateParm: {
4992 SubstTemplateTemplateParmStorage *subst
4993 = Name.getAsSubstTemplateTemplateParm();
4994 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4995 NameLoc);
4996 }
4997
4998 case TemplateName::SubstTemplateTemplateParmPack: {
4999 SubstTemplateTemplateParmPackStorage *subst
5000 = Name.getAsSubstTemplateTemplateParmPack();
5001 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5002 NameLoc);
5003 }
5004 }
5005
5006 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005007}
5008
Jay Foad39c79802011-01-12 09:06:06 +00005009TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005010 switch (Name.getKind()) {
5011 case TemplateName::QualifiedTemplate:
5012 case TemplateName::Template: {
5013 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005014 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00005015 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005016 Template = getCanonicalTemplateTemplateParmDecl(TTP);
5017
5018 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005019 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005020 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005021
John McCalld9dfe3a2011-06-30 08:33:18 +00005022 case TemplateName::OverloadedTemplate:
5023 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00005024
John McCalld9dfe3a2011-06-30 08:33:18 +00005025 case TemplateName::DependentTemplate: {
5026 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5027 assert(DTN && "Non-dependent template names must refer to template decls.");
5028 return DTN->CanonicalTemplateName;
5029 }
5030
5031 case TemplateName::SubstTemplateTemplateParm: {
5032 SubstTemplateTemplateParmStorage *subst
5033 = Name.getAsSubstTemplateTemplateParm();
5034 return getCanonicalTemplateName(subst->getReplacement());
5035 }
5036
5037 case TemplateName::SubstTemplateTemplateParmPack: {
5038 SubstTemplateTemplateParmPackStorage *subst
5039 = Name.getAsSubstTemplateTemplateParmPack();
5040 TemplateTemplateParmDecl *canonParameter
5041 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5042 TemplateArgument canonArgPack
5043 = getCanonicalTemplateArgument(subst->getArgumentPack());
5044 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5045 }
5046 }
5047
5048 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005049}
5050
Douglas Gregoradee3e32009-11-11 23:06:43 +00005051bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5052 X = getCanonicalTemplateName(X);
5053 Y = getCanonicalTemplateName(Y);
5054 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5055}
5056
Mike Stump11289f42009-09-09 15:08:12 +00005057TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005058ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005059 switch (Arg.getKind()) {
5060 case TemplateArgument::Null:
5061 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005062
Douglas Gregora8e02e72009-07-28 23:00:59 +00005063 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005064 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005065
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005066 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00005067 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005068 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005069 }
Mike Stump11289f42009-09-09 15:08:12 +00005070
Eli Friedmanb826a002012-09-26 02:36:12 +00005071 case TemplateArgument::NullPtr:
5072 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5073 /*isNullPtr*/true);
5074
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005075 case TemplateArgument::Template:
5076 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005077
5078 case TemplateArgument::TemplateExpansion:
5079 return TemplateArgument(getCanonicalTemplateName(
5080 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005081 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005082
Douglas Gregora8e02e72009-07-28 23:00:59 +00005083 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005084 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005085
Douglas Gregora8e02e72009-07-28 23:00:59 +00005086 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005087 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005088
Douglas Gregora8e02e72009-07-28 23:00:59 +00005089 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005090 if (Arg.pack_size() == 0)
5091 return Arg;
5092
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005093 TemplateArgument *CanonArgs
5094 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005095 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005096 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005097 AEnd = Arg.pack_end();
5098 A != AEnd; (void)++A, ++Idx)
5099 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005100
Benjamin Kramercce63472015-08-05 09:40:22 +00005101 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005102 }
5103 }
5104
5105 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005106 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005107}
5108
Douglas Gregor333489b2009-03-27 23:10:48 +00005109NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005110ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005111 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005112 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005113
5114 switch (NNS->getKind()) {
5115 case NestedNameSpecifier::Identifier:
5116 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005117 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005118 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5119 NNS->getAsIdentifier());
5120
5121 case NestedNameSpecifier::Namespace:
5122 // A namespace is canonical; build a nested-name-specifier with
5123 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005124 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005125 NNS->getAsNamespace()->getOriginalNamespace());
5126
5127 case NestedNameSpecifier::NamespaceAlias:
5128 // A namespace is canonical; build a nested-name-specifier with
5129 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005130 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005131 NNS->getAsNamespaceAlias()->getNamespace()
5132 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005133
5134 case NestedNameSpecifier::TypeSpec:
5135 case NestedNameSpecifier::TypeSpecWithTemplate: {
5136 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005137
5138 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5139 // break it apart into its prefix and identifier, then reconsititute those
5140 // as the canonical nested-name-specifier. This is required to canonicalize
5141 // a dependent nested-name-specifier involving typedefs of dependent-name
5142 // types, e.g.,
5143 // typedef typename T::type T1;
5144 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00005145 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
5146 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005147 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005148
Eli Friedman5358a0a2012-03-03 04:09:56 +00005149 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5150 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5151 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005152 return NestedNameSpecifier::Create(*this, nullptr, false,
5153 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005154 }
5155
5156 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005157 case NestedNameSpecifier::Super:
5158 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005159 return NNS;
5160 }
5161
David Blaikie8a40f702012-01-17 06:56:22 +00005162 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005163}
5164
Jay Foad39c79802011-01-12 09:06:06 +00005165const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005166 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005167 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005168 // Handle the common positive case fast.
5169 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
5170 return AT;
5171 }
Mike Stump11289f42009-09-09 15:08:12 +00005172
John McCall8ccfcb52009-09-24 19:53:00 +00005173 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005174 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005175 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005176
John McCall8ccfcb52009-09-24 19:53:00 +00005177 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005178 // implements C99 6.7.3p8: "If the specification of an array type includes
5179 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005180
Chris Lattner7adf0762008-08-04 07:31:14 +00005181 // If we get here, we either have type qualifiers on the type, or we have
5182 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005183 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005184
John McCall33ddac02011-01-19 10:06:00 +00005185 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005186 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005187
Chris Lattner7adf0762008-08-04 07:31:14 +00005188 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00005189 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005190 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005191 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005192
Chris Lattner7adf0762008-08-04 07:31:14 +00005193 // Otherwise, we have an array and we have qualifiers on it. Push the
5194 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005195 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005196
Chris Lattner7adf0762008-08-04 07:31:14 +00005197 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
5198 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5199 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005200 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00005201 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
5202 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5203 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005204 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005205
Mike Stump11289f42009-09-09 15:08:12 +00005206 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00005207 = dyn_cast<DependentSizedArrayType>(ATy))
5208 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005209 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005210 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005211 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005212 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005213 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005214
Chris Lattner7adf0762008-08-04 07:31:14 +00005215 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005216 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005217 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005218 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005219 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005220 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005221}
5222
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005223QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005224 if (T->isArrayType() || T->isFunctionType())
5225 return getDecayedType(T);
5226 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005227}
5228
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005229QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005230 T = getVariableArrayDecayedType(T);
5231 T = getAdjustedParameterType(T);
5232 return T.getUnqualifiedType();
5233}
5234
David Majnemerd09a51c2015-03-03 01:50:05 +00005235QualType ASTContext::getExceptionObjectType(QualType T) const {
5236 // C++ [except.throw]p3:
5237 // A throw-expression initializes a temporary object, called the exception
5238 // object, the type of which is determined by removing any top-level
5239 // cv-qualifiers from the static type of the operand of throw and adjusting
5240 // the type from "array of T" or "function returning T" to "pointer to T"
5241 // or "pointer to function returning T", [...]
5242 T = getVariableArrayDecayedType(T);
5243 if (T->isArrayType() || T->isFunctionType())
5244 T = getDecayedType(T);
5245 return T.getUnqualifiedType();
5246}
5247
Chris Lattnera21ad802008-04-02 05:18:44 +00005248/// getArrayDecayedType - Return the properly qualified result of decaying the
5249/// specified array type to a pointer. This operation is non-trivial when
5250/// handling typedefs etc. The canonical type of "T" must be an array type,
5251/// this returns a pointer to a properly qualified element of the array.
5252///
5253/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005254QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005255 // Get the element type with 'getAsArrayType' so that we don't lose any
5256 // typedefs in the element type of the array. This also handles propagation
5257 // of type qualifiers from the array type into the element type if present
5258 // (C99 6.7.3p8).
5259 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5260 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005261
Chris Lattner7adf0762008-08-04 07:31:14 +00005262 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005263
5264 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005265 QualType Result = getQualifiedType(PtrTy,
5266 PrettyArrayType->getIndexTypeQualifiers());
5267
5268 // int x[_Nullable] -> int * _Nullable
5269 if (auto Nullability = Ty->getNullability(*this)) {
5270 Result = const_cast<ASTContext *>(this)->getAttributedType(
5271 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5272 }
5273 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005274}
5275
John McCall33ddac02011-01-19 10:06:00 +00005276QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5277 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005278}
5279
John McCall33ddac02011-01-19 10:06:00 +00005280QualType ASTContext::getBaseElementType(QualType type) const {
5281 Qualifiers qs;
5282 while (true) {
5283 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005284 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005285 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005286
John McCall33ddac02011-01-19 10:06:00 +00005287 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005288 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005289 }
Mike Stump11289f42009-09-09 15:08:12 +00005290
John McCall33ddac02011-01-19 10:06:00 +00005291 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005292}
5293
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005294/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005295uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005296ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5297 uint64_t ElementCount = 1;
5298 do {
5299 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005300 CA = dyn_cast_or_null<ConstantArrayType>(
5301 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005302 } while (CA);
5303 return ElementCount;
5304}
5305
Steve Naroff0af91202007-04-27 21:51:21 +00005306/// getFloatingRank - Return a relative rank for floating point types.
5307/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005308static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00005309 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005310 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005311
John McCall9dd450b2009-09-21 23:43:11 +00005312 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5313 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005314 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005315 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005316 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005317 case BuiltinType::Float: return FloatRank;
5318 case BuiltinType::Double: return DoubleRank;
5319 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005320 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005321 }
5322}
5323
Mike Stump11289f42009-09-09 15:08:12 +00005324/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5325/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005326/// 'typeDomain' is a real floating point or complex type.
5327/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005328QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5329 QualType Domain) const {
5330 FloatingRank EltRank = getFloatingRank(Size);
5331 if (Domain->isComplexType()) {
5332 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005333 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005334 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005335 case FloatRank: return FloatComplexTy;
5336 case DoubleRank: return DoubleComplexTy;
5337 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005338 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005339 }
Steve Naroff0af91202007-04-27 21:51:21 +00005340 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005341
5342 assert(Domain->isRealFloatingType() && "Unknown domain!");
5343 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005344 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005345 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005346 case FloatRank: return FloatTy;
5347 case DoubleRank: return DoubleTy;
5348 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005349 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005350 }
David Blaikief47fa302012-01-17 02:30:50 +00005351 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005352}
5353
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005354/// getFloatingTypeOrder - Compare the rank of the two specified floating
5355/// point types, ignoring the domain of the type (i.e. 'double' ==
5356/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005357/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005358int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005359 FloatingRank LHSR = getFloatingRank(LHS);
5360 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005361
Chris Lattnerb90739d2008-04-06 23:38:49 +00005362 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005363 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005364 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005365 return 1;
5366 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005367}
5368
Chris Lattner76a00cf2008-04-06 22:59:24 +00005369/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5370/// routine will assert if passed a built-in type that isn't an integer or enum,
5371/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005372unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005373 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005374
Chris Lattner76a00cf2008-04-06 22:59:24 +00005375 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005376 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005377 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005378 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005379 case BuiltinType::Char_S:
5380 case BuiltinType::Char_U:
5381 case BuiltinType::SChar:
5382 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005383 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005384 case BuiltinType::Short:
5385 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005386 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005387 case BuiltinType::Int:
5388 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005389 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005390 case BuiltinType::Long:
5391 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005392 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005393 case BuiltinType::LongLong:
5394 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005395 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005396 case BuiltinType::Int128:
5397 case BuiltinType::UInt128:
5398 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005399 }
5400}
5401
Eli Friedman629ffb92009-08-20 04:21:42 +00005402/// \brief Whether this is a promotable bitfield reference according
5403/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5404///
5405/// \returns the type this bit-field will promote to, or NULL if no
5406/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005407QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005408 if (E->isTypeDependent() || E->isValueDependent())
5409 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00005410
5411 // FIXME: We should not do this unless E->refersToBitField() is true. This
5412 // matters in C where getSourceBitField() will find bit-fields for various
5413 // cases where the source expression is not a bit-field designator.
5414
John McCalld25db7e2013-05-06 21:39:12 +00005415 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005416 if (!Field)
5417 return QualType();
5418
5419 QualType FT = Field->getType();
5420
Richard Smithcaf33902011-10-10 18:28:20 +00005421 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005422 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005423 // C++ [conv.prom]p5:
5424 // A prvalue for an integral bit-field can be converted to a prvalue of type
5425 // int if int can represent all the values of the bit-field; otherwise, it
5426 // can be converted to unsigned int if unsigned int can represent all the
5427 // values of the bit-field. If the bit-field is larger yet, no integral
5428 // promotion applies to it.
5429 // C11 6.3.1.1/2:
5430 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5431 // If an int can represent all values of the original type (as restricted by
5432 // the width, for a bit-field), the value is converted to an int; otherwise,
5433 // it is converted to an unsigned int.
5434 //
5435 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5436 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00005437 if (BitWidth < IntSize)
5438 return IntTy;
5439
5440 if (BitWidth == IntSize)
5441 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5442
5443 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005444 // like the base type. GCC has some weird bugs in this area that we
5445 // deliberately do not follow (GCC follows a pre-standard resolution to
5446 // C's DR315 which treats bit-width as being part of the type, and this leaks
5447 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00005448 return QualType();
5449}
5450
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005451/// getPromotedIntegerType - Returns the type that Promotable will
5452/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5453/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005454QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005455 assert(!Promotable.isNull());
5456 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00005457 if (const EnumType *ET = Promotable->getAs<EnumType>())
5458 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005459
5460 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
5461 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5462 // (3.9.1) can be converted to a prvalue of the first of the following
5463 // types that can represent all the values of its underlying type:
5464 // int, unsigned int, long int, unsigned long int, long long int, or
5465 // unsigned long long int [...]
5466 // FIXME: Is there some better way to compute this?
5467 if (BT->getKind() == BuiltinType::WChar_S ||
5468 BT->getKind() == BuiltinType::WChar_U ||
5469 BT->getKind() == BuiltinType::Char16 ||
5470 BT->getKind() == BuiltinType::Char32) {
5471 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5472 uint64_t FromSize = getTypeSize(BT);
5473 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5474 LongLongTy, UnsignedLongLongTy };
5475 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5476 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5477 if (FromSize < ToSize ||
5478 (FromSize == ToSize &&
5479 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5480 return PromoteTypes[Idx];
5481 }
5482 llvm_unreachable("char type should fit into long long");
5483 }
5484 }
5485
5486 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005487 if (Promotable->isSignedIntegerType())
5488 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005489 uint64_t PromotableSize = getIntWidth(Promotable);
5490 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005491 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5492 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5493}
5494
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005495/// \brief Recurses in pointer/array types until it finds an objc retainable
5496/// type and returns its ownership.
5497Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5498 while (!T.isNull()) {
5499 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5500 return T.getObjCLifetime();
5501 if (T->isArrayType())
5502 T = getBaseElementType(T);
5503 else if (const PointerType *PT = T->getAs<PointerType>())
5504 T = PT->getPointeeType();
5505 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005506 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005507 else
5508 break;
5509 }
5510
5511 return Qualifiers::OCL_None;
5512}
5513
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005514static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5515 // Incomplete enum types are not treated as integer types.
5516 // FIXME: In C++, enum types are never integer types.
5517 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5518 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005519 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005520}
5521
Mike Stump11289f42009-09-09 15:08:12 +00005522/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005523/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005524/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005525int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005526 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5527 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005528
5529 // Unwrap enums to their underlying type.
5530 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
5531 LHSC = getIntegerTypeForEnum(ET);
5532 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
5533 RHSC = getIntegerTypeForEnum(ET);
5534
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005535 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005536
Chris Lattner76a00cf2008-04-06 22:59:24 +00005537 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5538 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005539
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005540 unsigned LHSRank = getIntegerRank(LHSC);
5541 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005542
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005543 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5544 if (LHSRank == RHSRank) return 0;
5545 return LHSRank > RHSRank ? 1 : -1;
5546 }
Mike Stump11289f42009-09-09 15:08:12 +00005547
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005548 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5549 if (LHSUnsigned) {
5550 // If the unsigned [LHS] type is larger, return it.
5551 if (LHSRank >= RHSRank)
5552 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005553
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005554 // If the signed type can represent all values of the unsigned type, it
5555 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005556 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005557 return -1;
5558 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005559
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005560 // If the unsigned [RHS] type is larger, return it.
5561 if (RHSRank >= LHSRank)
5562 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005563
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005564 // If the signed type can represent all values of the unsigned type, it
5565 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005566 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005567 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005568}
Anders Carlsson98f07902007-08-17 05:31:46 +00005569
Ben Langmuirf5416742016-02-04 00:55:24 +00005570TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00005571 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005572 assert(!CFConstantStringTagDecl &&
5573 "tag and typedef should be initialized together");
5574 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5575 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00005576
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005577 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00005578 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00005579
Anders Carlsson98f07902007-08-17 05:31:46 +00005580 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00005581 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005582 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005583 // int flags;
5584 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005585 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00005586 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00005587 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005588 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00005589 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00005590 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005591 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00005592
Anders Carlsson98f07902007-08-17 05:31:46 +00005593 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00005594 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005595 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005596 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00005597 SourceLocation(),
5598 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005599 FieldTypes[i], /*TInfo=*/nullptr,
5600 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00005601 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00005602 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005603 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00005604 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00005605 }
5606
Ben Langmuirf5416742016-02-04 00:55:24 +00005607 CFConstantStringTagDecl->completeDefinition();
5608 // This type is designed to be compatible with NSConstantString, but cannot
5609 // use the same name, since NSConstantString is an interface.
5610 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5611 CFConstantStringTypeDecl =
5612 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00005613 }
Mike Stump11289f42009-09-09 15:08:12 +00005614
Quentin Colombet043406b2016-02-03 22:41:00 +00005615 return CFConstantStringTypeDecl;
5616}
5617
Ben Langmuirf5416742016-02-04 00:55:24 +00005618RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5619 if (!CFConstantStringTagDecl)
5620 getCFConstantStringDecl(); // Build the tag and the typedef.
5621 return CFConstantStringTagDecl;
5622}
5623
Quentin Colombet043406b2016-02-03 22:41:00 +00005624// getCFConstantStringType - Return the type used for constant CFStrings.
5625QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005626 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005627}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005628
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005629QualType ASTContext::getObjCSuperType() const {
5630 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005631 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005632 TUDecl->addDecl(ObjCSuperTypeDecl);
5633 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5634 }
5635 return ObjCSuperType;
5636}
5637
Douglas Gregor512b0772009-04-23 22:29:11 +00005638void ASTContext::setCFConstantStringType(QualType T) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005639 const TypedefType *TD = T->getAs<TypedefType>();
5640 assert(TD && "Invalid CFConstantStringType");
5641 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5642 auto TagType =
5643 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5644 assert(TagType && "Invalid CFConstantStringType");
5645 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005646}
5647
Jay Foad39c79802011-01-12 09:06:06 +00005648QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005649 if (BlockDescriptorType)
5650 return getTagDeclType(BlockDescriptorType);
5651
Alp Toker2dea15b2013-12-17 01:22:38 +00005652 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005653 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005654 RD = buildImplicitRecord("__block_descriptor");
5655 RD->startDefinition();
5656
Mike Stumpd0153282009-10-20 02:12:22 +00005657 QualType FieldTypes[] = {
5658 UnsignedLongTy,
5659 UnsignedLongTy,
5660 };
5661
Craig Topperd6d31ac2013-07-15 08:24:27 +00005662 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005663 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005664 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005665 };
5666
5667 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005668 FieldDecl *Field = FieldDecl::Create(
5669 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005670 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5671 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005672 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005673 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005674 }
5675
Alp Toker2dea15b2013-12-17 01:22:38 +00005676 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005677
Alp Toker2dea15b2013-12-17 01:22:38 +00005678 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005679
5680 return getTagDeclType(BlockDescriptorType);
5681}
5682
Jay Foad39c79802011-01-12 09:06:06 +00005683QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005684 if (BlockDescriptorExtendedType)
5685 return getTagDeclType(BlockDescriptorExtendedType);
5686
Alp Toker2dea15b2013-12-17 01:22:38 +00005687 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005688 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005689 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5690 RD->startDefinition();
5691
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005692 QualType FieldTypes[] = {
5693 UnsignedLongTy,
5694 UnsignedLongTy,
5695 getPointerType(VoidPtrTy),
5696 getPointerType(VoidPtrTy)
5697 };
5698
Craig Topperd6d31ac2013-07-15 08:24:27 +00005699 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005700 "reserved",
5701 "Size",
5702 "CopyFuncPtr",
5703 "DestroyFuncPtr"
5704 };
5705
5706 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005707 FieldDecl *Field = FieldDecl::Create(
5708 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005709 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5710 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005711 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005712 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005713 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005714 }
5715
Alp Toker2dea15b2013-12-17 01:22:38 +00005716 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005717
Alp Toker2dea15b2013-12-17 01:22:38 +00005718 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005719 return getTagDeclType(BlockDescriptorExtendedType);
5720}
5721
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00005722TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
5723 auto BT = dyn_cast<BuiltinType>(T);
5724
5725 if (!BT) {
5726 if (isa<PipeType>(T))
5727 return TargetInfo::OCLTK_Pipe;
5728
5729 return TargetInfo::OCLTK_Default;
5730 }
5731
5732 switch (BT->getKind()) {
5733#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5734 case BuiltinType::Id: \
5735 return TargetInfo::OCLTK_Image;
5736#include "clang/Basic/OpenCLImageTypes.def"
5737
5738 case BuiltinType::OCLClkEvent:
5739 return TargetInfo::OCLTK_ClkEvent;
5740
5741 case BuiltinType::OCLEvent:
5742 return TargetInfo::OCLTK_Event;
5743
5744 case BuiltinType::OCLQueue:
5745 return TargetInfo::OCLTK_Queue;
5746
5747 case BuiltinType::OCLReserveID:
5748 return TargetInfo::OCLTK_ReserveID;
5749
5750 case BuiltinType::OCLSampler:
5751 return TargetInfo::OCLTK_Sampler;
5752
5753 default:
5754 return TargetInfo::OCLTK_Default;
5755 }
5756}
5757
5758LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
5759 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
5760}
5761
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005762/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5763/// requires copy/dispose. Note that this must match the logic
5764/// in buildByrefHelpers.
5765bool ASTContext::BlockRequiresCopying(QualType Ty,
5766 const VarDecl *D) {
5767 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5768 const Expr *copyExpr = getBlockVarCopyInits(D);
5769 if (!copyExpr && record->hasTrivialDestructor()) return false;
5770
Mike Stump94967902009-10-21 18:16:27 +00005771 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005772 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005773
5774 if (!Ty->isObjCRetainableType()) return false;
5775
5776 Qualifiers qs = Ty.getQualifiers();
5777
5778 // If we have lifetime, that dominates.
5779 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005780 switch (lifetime) {
5781 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5782
5783 // These are just bits as far as the runtime is concerned.
5784 case Qualifiers::OCL_ExplicitNone:
5785 case Qualifiers::OCL_Autoreleasing:
5786 return false;
5787
5788 // Tell the runtime that this is ARC __weak, called by the
5789 // byref routines.
5790 case Qualifiers::OCL_Weak:
5791 // ARC __strong __block variables need to be retained.
5792 case Qualifiers::OCL_Strong:
5793 return true;
5794 }
5795 llvm_unreachable("fell out of lifetime switch!");
5796 }
5797 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5798 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005799}
5800
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005801bool ASTContext::getByrefLifetime(QualType Ty,
5802 Qualifiers::ObjCLifetime &LifeTime,
5803 bool &HasByrefExtendedLayout) const {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005804 if (!getLangOpts().ObjC1 ||
5805 getLangOpts().getGC() != LangOptions::NonGC)
5806 return false;
5807
5808 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005809 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005810 HasByrefExtendedLayout = true;
5811 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005812 } else if ((LifeTime = Ty.getObjCLifetime())) {
5813 // Honor the ARC qualifiers.
5814 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5815 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005816 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005817 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005818 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005819 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005820 return true;
5821}
5822
Douglas Gregorbab8a962011-09-08 01:46:34 +00005823TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5824 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005825 ObjCInstanceTypeDecl =
5826 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005827 return ObjCInstanceTypeDecl;
5828}
5829
Anders Carlsson18acd442007-10-29 06:33:42 +00005830// This returns true if a type has been typedefed to BOOL:
5831// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005832static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005833 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005834 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5835 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005836
Anders Carlssond8499822007-10-29 05:01:08 +00005837 return false;
5838}
5839
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005840/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005841/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005842CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005843 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5844 return CharUnits::Zero();
5845
Ken Dyck40775002010-01-11 17:06:35 +00005846 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005847
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005848 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005849 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005850 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005851 // Treat arrays as pointers, since that's how they're passed in.
5852 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005853 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005854 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005855}
5856
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005857bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005858 return getTargetInfo().getCXXABI().isMicrosoft() &&
5859 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00005860 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00005861 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005862}
5863
Richard Smithd9b90092016-07-02 01:32:16 +00005864ASTContext::InlineVariableDefinitionKind
5865ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5866 if (!VD->isInline())
5867 return InlineVariableDefinitionKind::None;
5868
5869 // In almost all cases, it's a weak definition.
5870 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00005871 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00005872 return InlineVariableDefinitionKind::Weak;
5873
5874 // If there's a file-context declaration in this translation unit, it's a
5875 // non-discardable definition.
5876 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00005877 if (D->getLexicalDeclContext()->isFileContext() &&
5878 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00005879 return InlineVariableDefinitionKind::Strong;
5880
5881 // If we've not seen one yet, we don't know.
5882 return InlineVariableDefinitionKind::WeakUnknown;
5883}
5884
Ken Dyck40775002010-01-11 17:06:35 +00005885static inline
5886std::string charUnitsToString(const CharUnits &CU) {
5887 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005888}
5889
John McCall351762c2011-02-07 10:33:21 +00005890/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005891/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005892std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5893 std::string S;
5894
David Chisnall950a9512009-11-17 19:33:30 +00005895 const BlockDecl *Decl = Expr->getBlockDecl();
5896 QualType BlockTy =
5897 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5898 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005899 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005900 getObjCEncodingForMethodParameter(
5901 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5902 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005903 else
Alp Toker314cc812014-01-25 16:55:45 +00005904 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005905 // Compute size of all parameters.
5906 // Start with computing size of a pointer in number of bytes.
5907 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00005908 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5909 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005910 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005911 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005912 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005913 if (sz.isZero())
5914 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00005915 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005916 ParmOffset += sz;
5917 }
5918 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005919 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005920 // Block pointer and offset.
5921 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005922
5923 // Argument types.
5924 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005925 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005926 QualType PType = PVDecl->getOriginalType();
5927 if (const ArrayType *AT =
5928 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5929 // Use array's original type only if it has known number of
5930 // elements.
5931 if (!isa<ConstantArrayType>(AT))
5932 PType = PVDecl->getType();
5933 } else if (PType->isFunctionType())
5934 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005935 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005936 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5937 S, true /*Extended*/);
5938 else
5939 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005940 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005941 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005942 }
John McCall351762c2011-02-07 10:33:21 +00005943
5944 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005945}
5946
John McCall843dfcc2016-11-29 21:57:00 +00005947std::string
5948ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
5949 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005950 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005951 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005952 CharUnits ParmOffset;
5953 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00005954 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005955 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005956 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005957 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005958 continue;
5959
John McCall843dfcc2016-11-29 21:57:00 +00005960 assert(sz.isPositive() &&
5961 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005962 ParmOffset += sz;
5963 }
5964 S += charUnitsToString(ParmOffset);
5965 ParmOffset = CharUnits::Zero();
5966
5967 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00005968 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005969 QualType PType = PVDecl->getOriginalType();
5970 if (const ArrayType *AT =
5971 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5972 // Use array's original type only if it has known number of
5973 // elements.
5974 if (!isa<ConstantArrayType>(AT))
5975 PType = PVDecl->getType();
5976 } else if (PType->isFunctionType())
5977 PType = PVDecl->getType();
5978 getObjCEncodingForType(PType, S);
5979 S += charUnitsToString(ParmOffset);
5980 ParmOffset += getObjCEncodingTypeSize(PType);
5981 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005982
John McCall843dfcc2016-11-29 21:57:00 +00005983 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005984}
5985
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005986/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5987/// method parameter or return type. If Extended, include class names and
5988/// block object types.
5989void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5990 QualType T, std::string& S,
5991 bool Extended) const {
5992 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5993 getObjCEncodingForTypeQualifier(QT, S);
5994 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005995 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005996 true /*OutermostType*/,
5997 false /*EncodingProperty*/,
5998 false /*StructField*/,
5999 Extended /*EncodeBlockParameters*/,
6000 Extended /*EncodeClassNames*/);
6001}
6002
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006003/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006004/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00006005std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6006 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006007 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006008 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006009 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006010 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6011 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006012 // Compute size of all parameters.
6013 // Start with computing size of a pointer in number of bytes.
6014 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006015 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006016 // The first two arguments (self and _cmd) are pointers; account for
6017 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006018 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006019 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006020 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006021 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006022 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006023 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006024 continue;
6025
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006026 assert(sz.isPositive() &&
6027 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006028 ParmOffset += sz;
6029 }
Ken Dyck40775002010-01-11 17:06:35 +00006030 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006031 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006032 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006033
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006034 // Argument types.
6035 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006036 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006037 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006038 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006039 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00006040 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00006041 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6042 // Use array's original type only if it has known number of
6043 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006044 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006045 PType = PVDecl->getType();
6046 } else if (PType->isFunctionType())
6047 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006048 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
6049 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006050 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006051 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006052 }
Douglas Gregora9d84932011-05-27 01:19:52 +00006053
John McCall843dfcc2016-11-29 21:57:00 +00006054 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006055}
6056
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006057ObjCPropertyImplDecl *
6058ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6059 const ObjCPropertyDecl *PD,
6060 const Decl *Container) const {
6061 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006062 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006063 if (const ObjCCategoryImplDecl *CID =
6064 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006065 for (auto *PID : CID->property_impls())
6066 if (PID->getPropertyDecl() == PD)
6067 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006068 } else {
6069 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
6070 for (auto *PID : OID->property_impls())
6071 if (PID->getPropertyDecl() == PD)
6072 return PID;
6073 }
6074 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006075}
6076
Daniel Dunbar4932b362008-08-28 04:38:10 +00006077/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006078/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006079/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6080/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006081/// Property attributes are stored as a comma-delimited C string. The simple
6082/// attributes readonly and bycopy are encoded as single characters. The
6083/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6084/// encoded as single characters, followed by an identifier. Property types
6085/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006086/// these attributes are defined by the following enumeration:
6087/// @code
6088/// enum PropertyAttributes {
6089/// kPropertyReadOnly = 'R', // property is read-only.
6090/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6091/// kPropertyByref = '&', // property is a reference to the value last assigned
6092/// kPropertyDynamic = 'D', // property is dynamic
6093/// kPropertyGetter = 'G', // followed by getter selector name
6094/// kPropertySetter = 'S', // followed by setter selector name
6095/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006096/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006097/// kPropertyWeak = 'W' // 'weak' property
6098/// kPropertyStrong = 'P' // property GC'able
6099/// kPropertyNonAtomic = 'N' // property non-atomic
6100/// };
6101/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006102std::string
6103ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6104 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006105 // Collect information from the property implementation decl(s).
6106 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006107 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006108
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006109 if (ObjCPropertyImplDecl *PropertyImpDecl =
6110 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6111 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6112 Dynamic = true;
6113 else
6114 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006115 }
6116
6117 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006118 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006119
6120 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006121 // GCC has some special rules regarding encoding of properties which
6122 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006123 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006124
6125 if (PD->isReadOnly()) {
6126 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006127 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6128 S += ",C";
6129 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6130 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006131 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6132 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006133 } else {
6134 switch (PD->getSetterKind()) {
6135 case ObjCPropertyDecl::Assign: break;
6136 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006137 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006138 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006139 }
6140 }
6141
6142 // It really isn't clear at all what this means, since properties
6143 // are "dynamic by default".
6144 if (Dynamic)
6145 S += ",D";
6146
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006147 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6148 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006149
Daniel Dunbar4932b362008-08-28 04:38:10 +00006150 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6151 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006152 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006153 }
6154
6155 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6156 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006157 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006158 }
6159
6160 if (SynthesizePID) {
6161 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6162 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006163 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006164 }
6165
6166 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006167 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006168}
6169
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006170/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006171/// Another legacy compatibility encoding: 32-bit longs are encoded as
6172/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006173/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006174void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006175 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00006176 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006177 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006178 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006179 else
Jay Foad39c79802011-01-12 09:06:06 +00006180 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006181 PointeeTy = IntTy;
6182 }
6183 }
6184}
6185
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006186void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006187 const FieldDecl *Field,
6188 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006189 // We follow the behavior of gcc, expanding structures which are
6190 // directly pointed to, and expanding embedded structures. Note that
6191 // these rules are sufficient to prevent recursive encoding of the
6192 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00006193 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006194 true /* outermost type */, false, false,
6195 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006196}
6197
Joe Groff98ac7d22014-07-07 22:25:15 +00006198void ASTContext::getObjCEncodingForPropertyType(QualType T,
6199 std::string& S) const {
6200 // Encode result type.
6201 // GCC has some special rules regarding encoding of properties which
6202 // closely resembles encoding of ivars.
6203 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
6204 true /* outermost type */,
6205 true /* encoding property */);
6206}
6207
John McCall393a78d2012-12-20 02:45:14 +00006208static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
6209 BuiltinType::Kind kind) {
6210 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006211 case BuiltinType::Void: return 'v';
6212 case BuiltinType::Bool: return 'B';
6213 case BuiltinType::Char_U:
6214 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006215 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006216 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006217 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006218 case BuiltinType::UInt: return 'I';
6219 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006220 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006221 case BuiltinType::UInt128: return 'T';
6222 case BuiltinType::ULongLong: return 'Q';
6223 case BuiltinType::Char_S:
6224 case BuiltinType::SChar: return 'c';
6225 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006226 case BuiltinType::WChar_S:
6227 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006228 case BuiltinType::Int: return 'i';
6229 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006230 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006231 case BuiltinType::LongLong: return 'q';
6232 case BuiltinType::Int128: return 't';
6233 case BuiltinType::Float: return 'f';
6234 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006235 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006236 case BuiltinType::NullPtr: return '*'; // like char*
6237
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006238 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006239 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006240 case BuiltinType::Half:
6241 // FIXME: potentially need @encodes for these!
6242 return ' ';
6243
6244 case BuiltinType::ObjCId:
6245 case BuiltinType::ObjCClass:
6246 case BuiltinType::ObjCSel:
6247 llvm_unreachable("@encoding ObjC primitive type");
6248
6249 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006250#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6251 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006252#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006253 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006254 case BuiltinType::OCLClkEvent:
6255 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006256 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006257 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006258 case BuiltinType::Dependent:
6259#define BUILTIN_TYPE(KIND, ID)
6260#define PLACEHOLDER_TYPE(KIND, ID) \
6261 case BuiltinType::KIND:
6262#include "clang/AST/BuiltinTypes.def"
6263 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006264 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006265 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006266}
6267
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006268static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6269 EnumDecl *Enum = ET->getDecl();
6270
6271 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6272 if (!Enum->isFixed())
6273 return 'i';
6274
6275 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00006276 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
6277 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006278}
6279
Jay Foad39c79802011-01-12 09:06:06 +00006280static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006281 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006282 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006283 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006284 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6285 // The GNU runtime requires more information; bitfields are encoded as b,
6286 // then the offset (in bits) of the first element, then the type of the
6287 // bitfield, then the size in bits. For example, in this structure:
6288 //
6289 // struct
6290 // {
6291 // int integer;
6292 // int flags:2;
6293 // };
6294 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6295 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6296 // information is not especially sensible, but we're stuck with it for
6297 // compatibility with GCC, although providing it breaks anything that
6298 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006299 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006300 uint64_t Offset;
6301
6302 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6303 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6304 IVD);
6305 } else {
6306 const RecordDecl *RD = FD->getParent();
6307 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6308 Offset = RL.getFieldOffset(FD->getFieldIndex());
6309 }
6310
6311 S += llvm::utostr(Offset);
6312
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006313 if (const EnumType *ET = T->getAs<EnumType>())
6314 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006315 else {
6316 const BuiltinType *BT = T->castAs<BuiltinType>();
6317 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6318 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006319 }
Richard Smithcaf33902011-10-10 18:28:20 +00006320 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006321}
6322
Daniel Dunbar07d07852009-10-18 21:17:35 +00006323// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006324void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6325 bool ExpandPointedToStructures,
6326 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006327 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006328 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006329 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006330 bool StructField,
6331 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006332 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006333 bool EncodePointerToObjCTypedef,
6334 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006335 CanQualType CT = getCanonicalType(T);
6336 switch (CT->getTypeClass()) {
6337 case Type::Builtin:
6338 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006339 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006340 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00006341 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
6342 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6343 else
6344 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006345 return;
Mike Stump11289f42009-09-09 15:08:12 +00006346
John McCall393a78d2012-12-20 02:45:14 +00006347 case Type::Complex: {
6348 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006349 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006350 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006351 return;
6352 }
John McCall393a78d2012-12-20 02:45:14 +00006353
6354 case Type::Atomic: {
6355 const AtomicType *AT = T->castAs<AtomicType>();
6356 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006357 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006358 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006359 }
John McCall393a78d2012-12-20 02:45:14 +00006360
6361 // encoding for pointer or reference types.
6362 case Type::Pointer:
6363 case Type::LValueReference:
6364 case Type::RValueReference: {
6365 QualType PointeeTy;
6366 if (isa<PointerType>(CT)) {
6367 const PointerType *PT = T->castAs<PointerType>();
6368 if (PT->isObjCSelType()) {
6369 S += ':';
6370 return;
6371 }
6372 PointeeTy = PT->getPointeeType();
6373 } else {
6374 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6375 }
6376
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006377 bool isReadOnly = false;
6378 // For historical/compatibility reasons, the read-only qualifier of the
6379 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6380 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006381 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006382 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006383 if (OutermostType && T.isConstQualified()) {
6384 isReadOnly = true;
6385 S += 'r';
6386 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006387 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006388 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006389 while (P->getAs<PointerType>())
6390 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006391 if (P.isConstQualified()) {
6392 isReadOnly = true;
6393 S += 'r';
6394 }
6395 }
6396 if (isReadOnly) {
6397 // Another legacy compatibility encoding. Some ObjC qualifier and type
6398 // combinations need to be rearranged.
6399 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006400 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006401 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006402 }
Mike Stump11289f42009-09-09 15:08:12 +00006403
Anders Carlssond8499822007-10-29 05:01:08 +00006404 if (PointeeTy->isCharType()) {
6405 // char pointer types should be encoded as '*' unless it is a
6406 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006407 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006408 S += '*';
6409 return;
6410 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006411 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006412 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6413 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6414 S += '#';
6415 return;
6416 }
6417 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6418 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6419 S += '@';
6420 return;
6421 }
6422 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006423 }
Anders Carlssond8499822007-10-29 05:01:08 +00006424 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006425 getLegacyIntegralTypeEncoding(PointeeTy);
6426
Mike Stump11289f42009-09-09 15:08:12 +00006427 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006428 nullptr, false, false, false, false, false, false,
6429 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006430 return;
6431 }
John McCall393a78d2012-12-20 02:45:14 +00006432
6433 case Type::ConstantArray:
6434 case Type::IncompleteArray:
6435 case Type::VariableArray: {
6436 const ArrayType *AT = cast<ArrayType>(CT);
6437
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006438 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006439 // Incomplete arrays are encoded as a pointer to the array element.
6440 S += '^';
6441
Mike Stump11289f42009-09-09 15:08:12 +00006442 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006443 false, ExpandStructures, FD);
6444 } else {
6445 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006446
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006447 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6448 S += llvm::utostr(CAT->getSize().getZExtValue());
6449 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006450 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006451 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6452 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006453 S += '0';
6454 }
Mike Stump11289f42009-09-09 15:08:12 +00006455
6456 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006457 false, ExpandStructures, FD,
6458 false, false, false, false, false, false,
6459 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006460 S += ']';
6461 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006462 return;
6463 }
Mike Stump11289f42009-09-09 15:08:12 +00006464
John McCall393a78d2012-12-20 02:45:14 +00006465 case Type::FunctionNoProto:
6466 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006467 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006468 return;
Mike Stump11289f42009-09-09 15:08:12 +00006469
John McCall393a78d2012-12-20 02:45:14 +00006470 case Type::Record: {
6471 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006472 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006473 // Anonymous structures print as '?'
6474 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6475 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006476 if (ClassTemplateSpecializationDecl *Spec
6477 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6478 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006479 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00006480 printTemplateArgumentList(OS, TemplateArgs.asArray(),
6481 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006482 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006483 } else {
6484 S += '?';
6485 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006486 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006487 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006488 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006489 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006490 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006491 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006492 if (FD) {
6493 S += '"';
6494 S += Field->getNameAsString();
6495 S += '"';
6496 }
Mike Stump11289f42009-09-09 15:08:12 +00006497
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006498 // Special case bit-fields.
6499 if (Field->isBitField()) {
6500 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006501 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006502 } else {
6503 QualType qt = Field->getType();
6504 getLegacyIntegralTypeEncoding(qt);
6505 getObjCEncodingForTypeImpl(qt, S, false, true,
6506 FD, /*OutermostType*/false,
6507 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006508 /*StructField*/true,
6509 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006510 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006511 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006512 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006513 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006514 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006515 return;
6516 }
Mike Stump11289f42009-09-09 15:08:12 +00006517
John McCall393a78d2012-12-20 02:45:14 +00006518 case Type::BlockPointer: {
6519 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006520 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006521 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00006522 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006523
6524 S += '<';
6525 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006526 getObjCEncodingForTypeImpl(
6527 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6528 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006529 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6530 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006531 // Block self
6532 S += "@?";
6533 // Block parameters
6534 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006535 for (const auto &I : FPT->param_types())
6536 getObjCEncodingForTypeImpl(
6537 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6538 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006539 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6540 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006541 }
6542 S += '>';
6543 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006544 return;
6545 }
Mike Stump11289f42009-09-09 15:08:12 +00006546
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006547 case Type::ObjCObject: {
6548 // hack to match legacy encoding of *id and *Class
6549 QualType Ty = getObjCObjectPointerType(CT);
6550 if (Ty->isObjCIdType()) {
6551 S += "{objc_object=}";
6552 return;
6553 }
6554 else if (Ty->isObjCClassType()) {
6555 S += "{objc_class=}";
6556 return;
6557 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006558 // TODO: Double check to make sure this intentially falls through.
6559 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006560 }
6561
John McCall393a78d2012-12-20 02:45:14 +00006562 case Type::ObjCInterface: {
6563 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006564 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006565 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006566 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006567 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006568 if (ExpandStructures) {
6569 S += '=';
6570 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6571 DeepCollectObjCIvars(OI, true, Ivars);
6572 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6573 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
6574 if (Field->isBitField())
6575 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6576 else
6577 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6578 false, false, false, false, false,
6579 EncodePointerToObjCTypedef,
6580 NotEncodedT);
6581 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006582 }
6583 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006584 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006585 }
Mike Stump11289f42009-09-09 15:08:12 +00006586
John McCall393a78d2012-12-20 02:45:14 +00006587 case Type::ObjCObjectPointer: {
6588 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006589 if (OPT->isObjCIdType()) {
6590 S += '@';
6591 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006592 }
Mike Stump11289f42009-09-09 15:08:12 +00006593
Steve Narofff0c86112009-10-28 22:03:49 +00006594 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6595 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6596 // Since this is a binary compatibility issue, need to consult with runtime
6597 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006598 S += '#';
6599 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006600 }
Mike Stump11289f42009-09-09 15:08:12 +00006601
Chris Lattnere7cabb92009-07-13 00:10:46 +00006602 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006603 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006604 ExpandPointedToStructures,
6605 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006606 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006607 // Note that we do extended encoding of protocol qualifer list
6608 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006609 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006610 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006611 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006612 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006613 S += '>';
6614 }
6615 S += '"';
6616 }
6617 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006618 }
Mike Stump11289f42009-09-09 15:08:12 +00006619
Chris Lattnere7cabb92009-07-13 00:10:46 +00006620 QualType PointeeTy = OPT->getPointeeType();
6621 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006622 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6623 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006624 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006625 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006626 // {...};
6627 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006628 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006629 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006630 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6631 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6632 DeepCollectObjCIvars(OI, true, Ivars);
6633 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6634 if (cast<FieldDecl>(Ivars[i]) == FD) {
6635 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006636 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006637 S += '}';
6638 return;
6639 }
6640 }
6641 }
Mike Stump11289f42009-09-09 15:08:12 +00006642 getObjCEncodingForTypeImpl(PointeeTy, S,
6643 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006644 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006645 false, false, false, false, false,
6646 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006647 return;
6648 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006649
6650 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006651 if (OPT->getInterfaceDecl() &&
6652 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006653 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006654 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006655 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006656 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006657 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006658 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006659 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006660 S += '"';
6661 }
6662 return;
6663 }
Mike Stump11289f42009-09-09 15:08:12 +00006664
John McCalla9e6e8d2010-05-17 23:56:34 +00006665 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006666 // FIXME: we shoul do better than that. 'M' is available.
6667 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006668 // This matches gcc's encoding, even though technically it is insufficient.
6669 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006670 case Type::Vector:
6671 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006672 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006673 if (NotEncodedT)
6674 *NotEncodedT = T;
6675 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006676
6677 // We could see an undeduced auto type here during error recovery.
6678 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006679 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00006680 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00006681 return;
6682
Xiuli Pan9c14e282016-01-09 12:53:17 +00006683 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006684#define ABSTRACT_TYPE(KIND, BASE)
6685#define TYPE(KIND, BASE)
6686#define DEPENDENT_TYPE(KIND, BASE) \
6687 case Type::KIND:
6688#define NON_CANONICAL_TYPE(KIND, BASE) \
6689 case Type::KIND:
6690#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6691 case Type::KIND:
6692#include "clang/AST/TypeNodes.def"
6693 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006694 }
John McCall393a78d2012-12-20 02:45:14 +00006695 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006696}
6697
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006698void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6699 std::string &S,
6700 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006701 bool includeVBases,
6702 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006703 assert(RDecl && "Expected non-null RecordDecl");
6704 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006705 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006706 return;
6707
6708 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6709 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6710 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6711
6712 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006713 for (const auto &BI : CXXRec->bases()) {
6714 if (!BI.isVirtual()) {
6715 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006716 if (base->isEmpty())
6717 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006718 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006719 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6720 std::make_pair(offs, base));
6721 }
6722 }
6723 }
6724
6725 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006726 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006727 uint64_t offs = layout.getFieldOffset(i);
6728 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006729 std::make_pair(offs, Field));
6730 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006731 }
6732
6733 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006734 for (const auto &BI : CXXRec->vbases()) {
6735 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006736 if (base->isEmpty())
6737 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006738 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006739 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6740 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006741 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6742 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006743 }
6744 }
6745
6746 CharUnits size;
6747 if (CXXRec) {
6748 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6749 } else {
6750 size = layout.getSize();
6751 }
6752
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006753#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006754 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006755#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006756 std::multimap<uint64_t, NamedDecl *>::iterator
6757 CurLayObj = FieldOrBaseOffsets.begin();
6758
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006759 if (CXXRec && CXXRec->isDynamicClass() &&
6760 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006761 if (FD) {
6762 S += "\"_vptr$";
6763 std::string recname = CXXRec->getNameAsString();
6764 if (recname.empty()) recname = "?";
6765 S += recname;
6766 S += '"';
6767 }
6768 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006769#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006770 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006771#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006772 }
6773
6774 if (!RDecl->hasFlexibleArrayMember()) {
6775 // Mark the end of the structure.
6776 uint64_t offs = toBits(size);
6777 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006778 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006779 }
6780
6781 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006782#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006783 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006784 if (CurOffs < CurLayObj->first) {
6785 uint64_t padding = CurLayObj->first - CurOffs;
6786 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6787 // packing/alignment of members is different that normal, in which case
6788 // the encoding will be out-of-sync with the real layout.
6789 // If the runtime switches to just consider the size of types without
6790 // taking into account alignment, we could make padding explicit in the
6791 // encoding (e.g. using arrays of chars). The encoding strings would be
6792 // longer then though.
6793 CurOffs += padding;
6794 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006795#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006796
6797 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006798 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006799 break; // reached end of structure.
6800
6801 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6802 // We expand the bases without their virtual bases since those are going
6803 // in the initial structure. Note that this differs from gcc which
6804 // expands virtual bases each time one is encountered in the hierarchy,
6805 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006806 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6807 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006808 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006809#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006810 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006811#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006812 } else {
6813 FieldDecl *field = cast<FieldDecl>(dcl);
6814 if (FD) {
6815 S += '"';
6816 S += field->getNameAsString();
6817 S += '"';
6818 }
6819
6820 if (field->isBitField()) {
6821 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006822#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006823 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006824#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006825 } else {
6826 QualType qt = field->getType();
6827 getLegacyIntegralTypeEncoding(qt);
6828 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6829 /*OutermostType*/false,
6830 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006831 /*StructField*/true,
6832 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006833#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006834 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006835#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006836 }
6837 }
6838 }
6839}
6840
Mike Stump11289f42009-09-09 15:08:12 +00006841void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006842 std::string& S) const {
6843 if (QT & Decl::OBJC_TQ_In)
6844 S += 'n';
6845 if (QT & Decl::OBJC_TQ_Inout)
6846 S += 'N';
6847 if (QT & Decl::OBJC_TQ_Out)
6848 S += 'o';
6849 if (QT & Decl::OBJC_TQ_Bycopy)
6850 S += 'O';
6851 if (QT & Decl::OBJC_TQ_Byref)
6852 S += 'R';
6853 if (QT & Decl::OBJC_TQ_Oneway)
6854 S += 'V';
6855}
6856
Douglas Gregor3ea72692011-08-12 05:46:01 +00006857TypedefDecl *ASTContext::getObjCIdDecl() const {
6858 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006859 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00006860 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006861 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006862 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006863 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006864}
6865
Douglas Gregor52e02802011-08-12 06:17:30 +00006866TypedefDecl *ASTContext::getObjCSelDecl() const {
6867 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006868 QualType T = getPointerType(ObjCBuiltinSelTy);
6869 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006870 }
6871 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006872}
6873
Douglas Gregor0a586182011-08-12 05:59:41 +00006874TypedefDecl *ASTContext::getObjCClassDecl() const {
6875 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006876 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00006877 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006878 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006879 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006880 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006881}
6882
Douglas Gregord53ae832012-01-17 18:09:05 +00006883ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6884 if (!ObjCProtocolClassDecl) {
6885 ObjCProtocolClassDecl
6886 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6887 SourceLocation(),
6888 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006889 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006890 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006891 SourceLocation(), true);
6892 }
6893
6894 return ObjCProtocolClassDecl;
6895}
6896
Meador Inge5d3fb222012-06-16 03:34:49 +00006897//===----------------------------------------------------------------------===//
6898// __builtin_va_list Construction Functions
6899//===----------------------------------------------------------------------===//
6900
Charles Davisc7d5c942015-09-17 20:55:33 +00006901static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6902 StringRef Name) {
6903 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006904 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006905 return Context->buildImplicitTypedef(T, Name);
6906}
6907
6908static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6909 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6910}
6911
6912static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6913 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006914}
6915
6916static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6917 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006918 QualType T = Context->getPointerType(Context->VoidTy);
6919 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006920}
6921
Tim Northover9bb857a2013-01-31 12:13:10 +00006922static TypedefDecl *
6923CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006924 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006925 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006926 if (Context->getLangOpts().CPlusPlus) {
6927 // namespace std { struct __va_list {
6928 NamespaceDecl *NS;
6929 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6930 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006931 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006932 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006933 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006934 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006935 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006936 }
6937
6938 VaListTagDecl->startDefinition();
6939
6940 const size_t NumFields = 5;
6941 QualType FieldTypes[NumFields];
6942 const char *FieldNames[NumFields];
6943
6944 // void *__stack;
6945 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6946 FieldNames[0] = "__stack";
6947
6948 // void *__gr_top;
6949 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6950 FieldNames[1] = "__gr_top";
6951
6952 // void *__vr_top;
6953 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6954 FieldNames[2] = "__vr_top";
6955
6956 // int __gr_offs;
6957 FieldTypes[3] = Context->IntTy;
6958 FieldNames[3] = "__gr_offs";
6959
6960 // int __vr_offs;
6961 FieldTypes[4] = Context->IntTy;
6962 FieldNames[4] = "__vr_offs";
6963
6964 // Create fields
6965 for (unsigned i = 0; i < NumFields; ++i) {
6966 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6967 VaListTagDecl,
6968 SourceLocation(),
6969 SourceLocation(),
6970 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006971 FieldTypes[i], /*TInfo=*/nullptr,
6972 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006973 /*Mutable=*/false,
6974 ICIS_NoInit);
6975 Field->setAccess(AS_public);
6976 VaListTagDecl->addDecl(Field);
6977 }
6978 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006979 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006980 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006981
6982 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006983 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006984}
6985
Meador Inge5d3fb222012-06-16 03:34:49 +00006986static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6987 // typedef struct __va_list_tag {
6988 RecordDecl *VaListTagDecl;
6989
Alp Toker2dea15b2013-12-17 01:22:38 +00006990 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006991 VaListTagDecl->startDefinition();
6992
6993 const size_t NumFields = 5;
6994 QualType FieldTypes[NumFields];
6995 const char *FieldNames[NumFields];
6996
6997 // unsigned char gpr;
6998 FieldTypes[0] = Context->UnsignedCharTy;
6999 FieldNames[0] = "gpr";
7000
7001 // unsigned char fpr;
7002 FieldTypes[1] = Context->UnsignedCharTy;
7003 FieldNames[1] = "fpr";
7004
7005 // unsigned short reserved;
7006 FieldTypes[2] = Context->UnsignedShortTy;
7007 FieldNames[2] = "reserved";
7008
7009 // void* overflow_arg_area;
7010 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7011 FieldNames[3] = "overflow_arg_area";
7012
7013 // void* reg_save_area;
7014 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7015 FieldNames[4] = "reg_save_area";
7016
7017 // Create fields
7018 for (unsigned i = 0; i < NumFields; ++i) {
7019 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7020 SourceLocation(),
7021 SourceLocation(),
7022 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007023 FieldTypes[i], /*TInfo=*/nullptr,
7024 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007025 /*Mutable=*/false,
7026 ICIS_NoInit);
7027 Field->setAccess(AS_public);
7028 VaListTagDecl->addDecl(Field);
7029 }
7030 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007031 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007032 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7033
7034 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007035 TypedefDecl *VaListTagTypedefDecl =
7036 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7037
Meador Inge5d3fb222012-06-16 03:34:49 +00007038 QualType VaListTagTypedefType =
7039 Context->getTypedefType(VaListTagTypedefDecl);
7040
7041 // typedef __va_list_tag __builtin_va_list[1];
7042 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7043 QualType VaListTagArrayType
7044 = Context->getConstantArrayType(VaListTagTypedefType,
7045 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007046 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007047}
7048
7049static TypedefDecl *
7050CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007051 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007052 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007053 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007054 VaListTagDecl->startDefinition();
7055
7056 const size_t NumFields = 4;
7057 QualType FieldTypes[NumFields];
7058 const char *FieldNames[NumFields];
7059
7060 // unsigned gp_offset;
7061 FieldTypes[0] = Context->UnsignedIntTy;
7062 FieldNames[0] = "gp_offset";
7063
7064 // unsigned fp_offset;
7065 FieldTypes[1] = Context->UnsignedIntTy;
7066 FieldNames[1] = "fp_offset";
7067
7068 // void* overflow_arg_area;
7069 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7070 FieldNames[2] = "overflow_arg_area";
7071
7072 // void* reg_save_area;
7073 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7074 FieldNames[3] = "reg_save_area";
7075
7076 // Create fields
7077 for (unsigned i = 0; i < NumFields; ++i) {
7078 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7079 VaListTagDecl,
7080 SourceLocation(),
7081 SourceLocation(),
7082 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007083 FieldTypes[i], /*TInfo=*/nullptr,
7084 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007085 /*Mutable=*/false,
7086 ICIS_NoInit);
7087 Field->setAccess(AS_public);
7088 VaListTagDecl->addDecl(Field);
7089 }
7090 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007091 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007092 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7093
Richard Smith9b88a4c2015-07-27 05:40:23 +00007094 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007095
Richard Smith9b88a4c2015-07-27 05:40:23 +00007096 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007097 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007098 QualType VaListTagArrayType =
7099 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007100 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007101}
7102
7103static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7104 // typedef int __builtin_va_list[4];
7105 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00007106 QualType IntArrayType =
7107 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007108 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007109}
7110
Logan Chien57086ce2012-10-10 06:56:20 +00007111static TypedefDecl *
7112CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007113 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007114 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007115 if (Context->getLangOpts().CPlusPlus) {
7116 // namespace std { struct __va_list {
7117 NamespaceDecl *NS;
7118 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7119 Context->getTranslationUnitDecl(),
7120 /*Inline*/false, SourceLocation(),
7121 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007122 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007123 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007124 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007125 }
7126
7127 VaListDecl->startDefinition();
7128
7129 // void * __ap;
7130 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7131 VaListDecl,
7132 SourceLocation(),
7133 SourceLocation(),
7134 &Context->Idents.get("__ap"),
7135 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007136 /*TInfo=*/nullptr,
7137 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007138 /*Mutable=*/false,
7139 ICIS_NoInit);
7140 Field->setAccess(AS_public);
7141 VaListDecl->addDecl(Field);
7142
7143 // };
7144 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007145 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007146
7147 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007148 QualType T = Context->getRecordType(VaListDecl);
7149 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007150}
7151
Ulrich Weigand47445072013-05-06 16:26:41 +00007152static TypedefDecl *
7153CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007154 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007155 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007156 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007157 VaListTagDecl->startDefinition();
7158
7159 const size_t NumFields = 4;
7160 QualType FieldTypes[NumFields];
7161 const char *FieldNames[NumFields];
7162
7163 // long __gpr;
7164 FieldTypes[0] = Context->LongTy;
7165 FieldNames[0] = "__gpr";
7166
7167 // long __fpr;
7168 FieldTypes[1] = Context->LongTy;
7169 FieldNames[1] = "__fpr";
7170
7171 // void *__overflow_arg_area;
7172 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7173 FieldNames[2] = "__overflow_arg_area";
7174
7175 // void *__reg_save_area;
7176 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7177 FieldNames[3] = "__reg_save_area";
7178
7179 // Create fields
7180 for (unsigned i = 0; i < NumFields; ++i) {
7181 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7182 VaListTagDecl,
7183 SourceLocation(),
7184 SourceLocation(),
7185 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007186 FieldTypes[i], /*TInfo=*/nullptr,
7187 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007188 /*Mutable=*/false,
7189 ICIS_NoInit);
7190 Field->setAccess(AS_public);
7191 VaListTagDecl->addDecl(Field);
7192 }
7193 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007194 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007195 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007196
Richard Smith9b88a4c2015-07-27 05:40:23 +00007197 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007198
7199 // typedef __va_list_tag __builtin_va_list[1];
7200 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007201 QualType VaListTagArrayType =
7202 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007203
Alp Toker56b5cc92013-12-15 10:36:26 +00007204 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007205}
7206
Meador Inge5d3fb222012-06-16 03:34:49 +00007207static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7208 TargetInfo::BuiltinVaListKind Kind) {
7209 switch (Kind) {
7210 case TargetInfo::CharPtrBuiltinVaList:
7211 return CreateCharPtrBuiltinVaListDecl(Context);
7212 case TargetInfo::VoidPtrBuiltinVaList:
7213 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007214 case TargetInfo::AArch64ABIBuiltinVaList:
7215 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007216 case TargetInfo::PowerABIBuiltinVaList:
7217 return CreatePowerABIBuiltinVaListDecl(Context);
7218 case TargetInfo::X86_64ABIBuiltinVaList:
7219 return CreateX86_64ABIBuiltinVaListDecl(Context);
7220 case TargetInfo::PNaClABIBuiltinVaList:
7221 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007222 case TargetInfo::AAPCSABIBuiltinVaList:
7223 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007224 case TargetInfo::SystemZBuiltinVaList:
7225 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007226 }
7227
7228 llvm_unreachable("Unhandled __builtin_va_list type kind");
7229}
7230
7231TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007232 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007233 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007234 assert(BuiltinVaListDecl->isImplicit());
7235 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007236
7237 return BuiltinVaListDecl;
7238}
7239
Richard Smith9b88a4c2015-07-27 05:40:23 +00007240Decl *ASTContext::getVaListTagDecl() const {
7241 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007242 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007243 if (!VaListTagDecl)
7244 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007245
Richard Smith9b88a4c2015-07-27 05:40:23 +00007246 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007247}
7248
Charles Davisc7d5c942015-09-17 20:55:33 +00007249TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7250 if (!BuiltinMSVaListDecl)
7251 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7252
7253 return BuiltinMSVaListDecl;
7254}
7255
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007256void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007257 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007258 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007259
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007260 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007261}
7262
John McCalld28ae272009-12-02 08:04:21 +00007263/// \brief Retrieve the template name that corresponds to a non-empty
7264/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007265TemplateName
7266ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7267 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007268 unsigned size = End - Begin;
7269 assert(size > 1 && "set is not overloaded!");
7270
7271 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7272 size * sizeof(FunctionTemplateDecl*));
7273 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
7274
7275 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007276 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007277 NamedDecl *D = *I;
7278 assert(isa<FunctionTemplateDecl>(D) ||
7279 (isa<UsingShadowDecl>(D) &&
7280 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7281 *Storage++ = D;
7282 }
7283
7284 return TemplateName(OT);
7285}
7286
Douglas Gregordc572a32009-03-30 22:58:21 +00007287/// \brief Retrieve the template name that represents a qualified
7288/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007289TemplateName
7290ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7291 bool TemplateKeyword,
7292 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007293 assert(NNS && "Missing nested-name-specifier in qualified template name");
7294
Douglas Gregorc42075a2010-02-04 18:10:26 +00007295 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007296 llvm::FoldingSetNodeID ID;
7297 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7298
Craig Topper36250ad2014-05-12 05:36:57 +00007299 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007300 QualifiedTemplateName *QTN =
7301 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7302 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007303 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007304 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007305 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7306 }
7307
7308 return TemplateName(QTN);
7309}
7310
7311/// \brief Retrieve the template name that represents a dependent
7312/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007313TemplateName
7314ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7315 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007316 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007317 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007318
7319 llvm::FoldingSetNodeID ID;
7320 DependentTemplateName::Profile(ID, NNS, Name);
7321
Craig Topper36250ad2014-05-12 05:36:57 +00007322 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007323 DependentTemplateName *QTN =
7324 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7325
7326 if (QTN)
7327 return TemplateName(QTN);
7328
7329 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7330 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007331 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007332 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007333 } else {
7334 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007335 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007336 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007337 DependentTemplateName *CheckQTN =
7338 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7339 assert(!CheckQTN && "Dependent type name canonicalization broken");
7340 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007341 }
7342
7343 DependentTemplateNames.InsertNode(QTN, InsertPos);
7344 return TemplateName(QTN);
7345}
7346
Douglas Gregor71395fa2009-11-04 00:56:37 +00007347/// \brief Retrieve the template name that represents a dependent
7348/// template name such as \c MetaFun::template operator+.
7349TemplateName
7350ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007351 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007352 assert((!NNS || NNS->isDependent()) &&
7353 "Nested name specifier must be dependent");
7354
7355 llvm::FoldingSetNodeID ID;
7356 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007357
7358 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007359 DependentTemplateName *QTN
7360 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007361
7362 if (QTN)
7363 return TemplateName(QTN);
7364
7365 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7366 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007367 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007368 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007369 } else {
7370 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007371 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007372 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007373
Douglas Gregorc42075a2010-02-04 18:10:26 +00007374 DependentTemplateName *CheckQTN
7375 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7376 assert(!CheckQTN && "Dependent template name canonicalization broken");
7377 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007378 }
7379
7380 DependentTemplateNames.InsertNode(QTN, InsertPos);
7381 return TemplateName(QTN);
7382}
7383
Douglas Gregor5590be02011-01-15 06:45:20 +00007384TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007385ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7386 TemplateName replacement) const {
7387 llvm::FoldingSetNodeID ID;
7388 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007389
7390 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007391 SubstTemplateTemplateParmStorage *subst
7392 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7393
7394 if (!subst) {
7395 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7396 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7397 }
7398
7399 return TemplateName(subst);
7400}
7401
7402TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007403ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7404 const TemplateArgument &ArgPack) const {
7405 ASTContext &Self = const_cast<ASTContext &>(*this);
7406 llvm::FoldingSetNodeID ID;
7407 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007408
7409 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007410 SubstTemplateTemplateParmPackStorage *Subst
7411 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7412
7413 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00007414 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007415 ArgPack.pack_size(),
7416 ArgPack.pack_begin());
7417 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7418 }
7419
7420 return TemplateName(Subst);
7421}
7422
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007423/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007424/// TargetInfo, produce the corresponding type. The unsigned @p Type
7425/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007426CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007427 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00007428 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007429 case TargetInfo::SignedChar: return SignedCharTy;
7430 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007431 case TargetInfo::SignedShort: return ShortTy;
7432 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7433 case TargetInfo::SignedInt: return IntTy;
7434 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7435 case TargetInfo::SignedLong: return LongTy;
7436 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7437 case TargetInfo::SignedLongLong: return LongLongTy;
7438 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7439 }
7440
David Blaikie83d382b2011-09-23 05:06:16 +00007441 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007442}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007443
7444//===----------------------------------------------------------------------===//
7445// Type Predicates.
7446//===----------------------------------------------------------------------===//
7447
Fariborz Jahanian96207692009-02-18 21:49:28 +00007448/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7449/// garbage collection attribute.
7450///
John McCall553d45a2011-01-12 00:34:59 +00007451Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007452 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007453 return Qualifiers::GCNone;
7454
David Blaikiebbafb8a2012-03-11 07:00:24 +00007455 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00007456 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7457
7458 // Default behaviour under objective-C's gc is for ObjC pointers
7459 // (or pointers to them) be treated as though they were declared
7460 // as __strong.
7461 if (GCAttrs == Qualifiers::GCNone) {
7462 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7463 return Qualifiers::Strong;
7464 else if (Ty->isPointerType())
7465 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7466 } else {
7467 // It's not valid to set GC attributes on anything that isn't a
7468 // pointer.
7469#ifndef NDEBUG
7470 QualType CT = Ty->getCanonicalTypeInternal();
7471 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
7472 CT = AT->getElementType();
7473 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7474#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007475 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007476 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007477}
7478
Chris Lattner49af6a42008-04-07 06:51:04 +00007479//===----------------------------------------------------------------------===//
7480// Type Compatibility Testing
7481//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007482
Mike Stump11289f42009-09-09 15:08:12 +00007483/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007484/// compatible.
7485static bool areCompatVectorTypes(const VectorType *LHS,
7486 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007487 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007488 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007489 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007490}
7491
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007492bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7493 QualType SecondVec) {
7494 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7495 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7496
7497 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7498 return true;
7499
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007500 // Treat Neon vector types and most AltiVec vector types as if they are the
7501 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007502 const VectorType *First = FirstVec->getAs<VectorType>();
7503 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007504 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007505 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007506 First->getVectorKind() != VectorType::AltiVecPixel &&
7507 First->getVectorKind() != VectorType::AltiVecBool &&
7508 Second->getVectorKind() != VectorType::AltiVecPixel &&
7509 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007510 return true;
7511
7512 return false;
7513}
7514
Steve Naroff8e6aee52009-07-23 01:01:38 +00007515//===----------------------------------------------------------------------===//
7516// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7517//===----------------------------------------------------------------------===//
7518
7519/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7520/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007521bool
7522ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7523 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007524 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007525 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007526 for (auto *PI : rProto->protocols())
7527 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007528 return true;
7529 return false;
7530}
7531
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007532/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7533/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007534bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7535 QualType rhs) {
7536 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7537 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007538 assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007539
Aaron Ballman83731462014-03-17 16:14:00 +00007540 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007541 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007542 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007543 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7544 match = true;
7545 break;
7546 }
7547 }
7548 if (!match)
7549 return false;
7550 }
7551 return true;
7552}
7553
Steve Naroff8e6aee52009-07-23 01:01:38 +00007554/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7555/// ObjCQualifiedIDType.
7556bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7557 bool compare) {
7558 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007559 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007560 lhs->isObjCIdType() || lhs->isObjCClassType())
7561 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007562 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007563 rhs->isObjCIdType() || rhs->isObjCClassType())
7564 return true;
7565
7566 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00007567 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007568
Steve Naroff8e6aee52009-07-23 01:01:38 +00007569 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007570
Steve Naroff8e6aee52009-07-23 01:01:38 +00007571 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007572 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007573 // make sure we check the class hierarchy.
7574 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007575 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007576 // when comparing an id<P> on lhs with a static type on rhs,
7577 // see if static class implements all of id's protocols, directly or
7578 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007579 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007580 return false;
7581 }
7582 }
7583 // If there are no qualifiers and no interface, we have an 'id'.
7584 return true;
7585 }
Mike Stump11289f42009-09-09 15:08:12 +00007586 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007587 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007588 bool match = false;
7589
7590 // when comparing an id<P> on lhs with a static type on rhs,
7591 // see if static class implements all of id's protocols, directly or
7592 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007593 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007594 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7595 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7596 match = true;
7597 break;
7598 }
7599 }
Mike Stump11289f42009-09-09 15:08:12 +00007600 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007601 // make sure we check the class hierarchy.
7602 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007603 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007604 // when comparing an id<P> on lhs with a static type on rhs,
7605 // see if static class implements all of id's protocols, directly or
7606 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007607 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007608 match = true;
7609 break;
7610 }
7611 }
7612 }
7613 if (!match)
7614 return false;
7615 }
Mike Stump11289f42009-09-09 15:08:12 +00007616
Steve Naroff8e6aee52009-07-23 01:01:38 +00007617 return true;
7618 }
Mike Stump11289f42009-09-09 15:08:12 +00007619
Steve Naroff8e6aee52009-07-23 01:01:38 +00007620 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7621 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7622
Mike Stump11289f42009-09-09 15:08:12 +00007623 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007624 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007625 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007626 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007627 bool match = false;
7628
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007629 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007630 // see if static class implements all of id's protocols, directly or
7631 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007632 // First, lhs protocols in the qualifier list must be found, direct
7633 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007634 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007635 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7636 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7637 match = true;
7638 break;
7639 }
7640 }
7641 if (!match)
7642 return false;
7643 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007644
7645 // Static class's protocols, or its super class or category protocols
7646 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7647 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7648 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7649 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7650 // This is rather dubious but matches gcc's behavior. If lhs has
7651 // no type qualifier and its class has no static protocol(s)
7652 // assume that it is mismatch.
7653 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7654 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007655 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007656 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007657 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007658 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7659 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7660 match = true;
7661 break;
7662 }
7663 }
7664 if (!match)
7665 return false;
7666 }
7667 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007668 return true;
7669 }
7670 return false;
7671}
7672
Eli Friedman47f77112008-08-22 00:56:42 +00007673/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007674/// compatible for assignment from RHS to LHS. This handles validation of any
7675/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007676bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7677 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007678 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7679 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7680
Steve Naroff1329fa02009-07-15 18:40:39 +00007681 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007682 if (LHS->isObjCUnqualifiedIdOrClass() ||
7683 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007684 return true;
7685
Douglas Gregorab209d82015-07-07 03:58:42 +00007686 // Function object that propagates a successful result or handles
7687 // __kindof types.
7688 auto finish = [&](bool succeeded) -> bool {
7689 if (succeeded)
7690 return true;
7691
7692 if (!RHS->isKindOfType())
7693 return false;
7694
7695 // Strip off __kindof and protocol qualifiers, then check whether
7696 // we can assign the other way.
7697 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7698 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7699 };
7700
7701 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7702 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7703 QualType(RHSOPT,0),
7704 false));
7705 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007706
Douglas Gregorab209d82015-07-07 03:58:42 +00007707 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7708 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7709 QualType(RHSOPT,0)));
7710 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007711
John McCall8b07ec22010-05-15 11:32:37 +00007712 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007713 if (LHS->getInterface() && RHS->getInterface()) {
7714 return finish(canAssignObjCInterfaces(LHS, RHS));
7715 }
Mike Stump11289f42009-09-09 15:08:12 +00007716
Steve Naroff8e6aee52009-07-23 01:01:38 +00007717 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007718}
7719
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007720/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00007721/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007722/// arguments in block literals. When passed as arguments, passing 'A*' where
7723/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7724/// not OK. For the return type, the opposite is not OK.
7725bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7726 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007727 const ObjCObjectPointerType *RHSOPT,
7728 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007729
7730 // Function object that propagates a successful result or handles
7731 // __kindof types.
7732 auto finish = [&](bool succeeded) -> bool {
7733 if (succeeded)
7734 return true;
7735
7736 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7737 if (!Expected->isKindOfType())
7738 return false;
7739
7740 // Strip off __kindof and protocol qualifiers, then check whether
7741 // we can assign the other way.
7742 return canAssignObjCInterfacesInBlockPointer(
7743 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7744 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7745 BlockReturnType);
7746 };
7747
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007748 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007749 return true;
7750
7751 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007752 return finish(RHSOPT->isObjCBuiltinType() ||
7753 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007754 }
7755
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007756 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007757 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7758 QualType(RHSOPT,0),
7759 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007760
7761 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7762 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7763 if (LHS && RHS) { // We have 2 user-defined types.
7764 if (LHS != RHS) {
7765 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007766 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007767 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007768 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007769 }
7770 else
7771 return true;
7772 }
7773 return false;
7774}
7775
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007776/// Comparison routine for Objective-C protocols to be used with
7777/// llvm::array_pod_sort.
7778static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7779 ObjCProtocolDecl * const *rhs) {
7780 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007781}
7782
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007783/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007784/// of protocols inherited from two distinct objective-c pointer objects with
7785/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007786/// It is used to build composite qualifier list of the composite type of
7787/// the conditional expression involving two objective-c pointer objects.
7788static
7789void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007790 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007791 const ObjCObjectPointerType *LHSOPT,
7792 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007793 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007794
John McCall8b07ec22010-05-15 11:32:37 +00007795 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7796 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7797 assert(LHS->getInterface() && "LHS must have an interface base");
7798 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007799
7800 // Add all of the protocols for the LHS.
7801 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7802
7803 // Start with the protocol qualifiers.
7804 for (auto proto : LHS->quals()) {
7805 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007806 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007807
7808 // Also add the protocols associated with the LHS interface.
7809 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7810
7811 // Add all of the protocls for the RHS.
7812 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7813
7814 // Start with the protocol qualifiers.
7815 for (auto proto : RHS->quals()) {
7816 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007817 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007818
7819 // Also add the protocols associated with the RHS interface.
7820 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7821
7822 // Compute the intersection of the collected protocol sets.
7823 for (auto proto : LHSProtocolSet) {
7824 if (RHSProtocolSet.count(proto))
7825 IntersectionSet.push_back(proto);
7826 }
7827
7828 // Compute the set of protocols that is implied by either the common type or
7829 // the protocols within the intersection.
7830 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7831 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7832
7833 // Remove any implied protocols from the list of inherited protocols.
7834 if (!ImpliedProtocols.empty()) {
7835 IntersectionSet.erase(
7836 std::remove_if(IntersectionSet.begin(),
7837 IntersectionSet.end(),
7838 [&](ObjCProtocolDecl *proto) -> bool {
7839 return ImpliedProtocols.count(proto) > 0;
7840 }),
7841 IntersectionSet.end());
7842 }
7843
7844 // Sort the remaining protocols by name.
7845 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7846 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007847}
7848
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007849/// Determine whether the first type is a subtype of the second.
7850static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7851 QualType rhs) {
7852 // Common case: two object pointers.
7853 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7854 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7855 if (lhsOPT && rhsOPT)
7856 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7857
7858 // Two block pointers.
7859 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7860 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7861 if (lhsBlock && rhsBlock)
7862 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7863
7864 // If either is an unqualified 'id' and the other is a block, it's
7865 // acceptable.
7866 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7867 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7868 return true;
7869
7870 return false;
7871}
7872
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007873// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007874static bool sameObjCTypeArgs(ASTContext &ctx,
7875 const ObjCInterfaceDecl *iface,
7876 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007877 ArrayRef<QualType> rhsArgs,
7878 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007879 if (lhsArgs.size() != rhsArgs.size())
7880 return false;
7881
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007882 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007883 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007884 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7885 continue;
7886
7887 switch (typeParams->begin()[i]->getVariance()) {
7888 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007889 if (!stripKindOf ||
7890 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7891 rhsArgs[i].stripObjCKindOfType(ctx))) {
7892 return false;
7893 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007894 break;
7895
7896 case ObjCTypeParamVariance::Covariant:
7897 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7898 return false;
7899 break;
7900
7901 case ObjCTypeParamVariance::Contravariant:
7902 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7903 return false;
7904 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007905 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007906 }
7907
7908 return true;
7909}
7910
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007911QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007912 const ObjCObjectPointerType *Lptr,
7913 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007914 const ObjCObjectType *LHS = Lptr->getObjectType();
7915 const ObjCObjectType *RHS = Rptr->getObjectType();
7916 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7917 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007918
7919 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007920 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007921
Manman Renc46f7d12016-05-06 19:35:02 +00007922 // When either LHS or RHS is a kindof type, we should return a kindof type.
7923 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7924 // kindof(A).
7925 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7926
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007927 // Follow the left-hand side up the class hierarchy until we either hit a
7928 // root or find the RHS. Record the ancestors in case we don't find it.
7929 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7930 LHSAncestors;
7931 while (true) {
7932 // Record this ancestor. We'll need this if the common type isn't in the
7933 // path from the LHS to the root.
7934 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007935
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007936 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7937 // Get the type arguments.
7938 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7939 bool anyChanges = false;
7940 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7941 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007942 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7943 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007944 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007945 return QualType();
7946 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7947 // If only one has type arguments, the result will not have type
7948 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007949 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007950 anyChanges = true;
7951 }
7952
7953 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007954 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007955 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7956 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007957 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007958 anyChanges = true;
7959
7960 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007961 // If we need to return a kindof type but LHS is not a kindof type, we
7962 // build a new result type.
7963 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007964 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007965 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007966 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007967 return getObjCObjectPointerType(Result);
7968 }
7969
7970 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007971 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007972
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007973 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007974 QualType LHSSuperType = LHS->getSuperClassType();
7975 if (LHSSuperType.isNull())
7976 break;
7977
7978 LHS = LHSSuperType->castAs<ObjCObjectType>();
7979 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007980
7981 // We didn't find anything by following the LHS to its root; now check
7982 // the RHS against the cached set of ancestors.
7983 while (true) {
7984 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7985 if (KnownLHS != LHSAncestors.end()) {
7986 LHS = KnownLHS->second;
7987
7988 // Get the type arguments.
7989 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7990 bool anyChanges = false;
7991 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7992 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007993 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7994 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007995 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007996 return QualType();
7997 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7998 // If only one has type arguments, the result will not have type
7999 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008000 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008001 anyChanges = true;
8002 }
8003
8004 // Compute the intersection of protocols.
8005 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8006 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8007 Protocols);
8008 if (!Protocols.empty())
8009 anyChanges = true;
8010
Manman Renc46f7d12016-05-06 19:35:02 +00008011 // If we need to return a kindof type but RHS is not a kindof type, we
8012 // build a new result type.
8013 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008014 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008015 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008016 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008017 return getObjCObjectPointerType(Result);
8018 }
8019
8020 return getObjCObjectPointerType(QualType(RHS, 0));
8021 }
8022
8023 // Find the superclass of the RHS.
8024 QualType RHSSuperType = RHS->getSuperClassType();
8025 if (RHSSuperType.isNull())
8026 break;
8027
8028 RHS = RHSSuperType->castAs<ObjCObjectType>();
8029 }
8030
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008031 return QualType();
8032}
8033
John McCall8b07ec22010-05-15 11:32:37 +00008034bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8035 const ObjCObjectType *RHS) {
8036 assert(LHS->getInterface() && "LHS is not an interface type");
8037 assert(RHS->getInterface() && "RHS is not an interface type");
8038
Chris Lattner49af6a42008-04-07 06:51:04 +00008039 // Verify that the base decls are compatible: the RHS must be a subclass of
8040 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008041 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8042 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8043 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008044 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008045
Douglas Gregore83b9562015-07-07 03:57:53 +00008046 // If the LHS has protocol qualifiers, determine whether all of them are
8047 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8048 // LHS).
8049 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008050 // OK if conversion of LHS to SuperClass results in narrowing of types
8051 // ; i.e., SuperClass may implement at least one of the protocols
8052 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8053 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8054 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8055 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8056 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8057 // qualifiers.
8058 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008059 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008060 // If there is no protocols associated with RHS, it is not a match.
8061 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008062 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008063
8064 for (const auto *LHSProto : LHS->quals()) {
8065 bool SuperImplementsProtocol = false;
8066 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8067 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8068 SuperImplementsProtocol = true;
8069 break;
8070 }
8071 if (!SuperImplementsProtocol)
8072 return false;
8073 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008074 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008075
8076 // If the LHS is specialized, we may need to check type arguments.
8077 if (LHS->isSpecialized()) {
8078 // Follow the superclass chain until we've matched the LHS class in the
8079 // hierarchy. This substitutes type arguments through.
8080 const ObjCObjectType *RHSSuper = RHS;
8081 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8082 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8083
8084 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008085 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008086 !sameObjCTypeArgs(*this, LHS->getInterface(),
8087 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008088 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008089 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008090 }
8091 }
8092
8093 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008094}
8095
Steve Naroffb7605152009-02-12 17:52:19 +00008096bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8097 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00008098 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8099 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008100
Steve Naroff7cae42b2009-07-10 23:34:53 +00008101 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008102 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008103
8104 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8105 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008106}
8107
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008108bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8109 return canAssignObjCInterfaces(
8110 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8111 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8112}
8113
Mike Stump11289f42009-09-09 15:08:12 +00008114/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008115/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008116/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008117/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008118bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8119 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008120 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008121 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008122
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008123 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008124}
8125
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008126bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008127 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008128}
8129
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008130bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8131 return !mergeTypes(LHS, RHS, true).isNull();
8132}
8133
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008134/// mergeTransparentUnionType - if T is a transparent union type and a member
8135/// of T is compatible with SubType, return the merged type, else return
8136/// QualType()
8137QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8138 bool OfBlockPointer,
8139 bool Unqualified) {
8140 if (const RecordType *UT = T->getAsUnionType()) {
8141 RecordDecl *UD = UT->getDecl();
8142 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008143 for (const auto *I : UD->fields()) {
8144 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008145 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8146 if (!MT.isNull())
8147 return MT;
8148 }
8149 }
8150 }
8151
8152 return QualType();
8153}
8154
Alp Toker9cacbab2014-01-20 20:26:09 +00008155/// mergeFunctionParameterTypes - merge two types which appear as function
8156/// parameter types
8157QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8158 bool OfBlockPointer,
8159 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008160 // GNU extension: two types are compatible if they appear as a function
8161 // argument, one of the types is a transparent union type and the other
8162 // type is compatible with a union member
8163 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8164 Unqualified);
8165 if (!lmerge.isNull())
8166 return lmerge;
8167
8168 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8169 Unqualified);
8170 if (!rmerge.isNull())
8171 return rmerge;
8172
8173 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8174}
8175
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008176QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008177 bool OfBlockPointer,
8178 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00008179 const FunctionType *lbase = lhs->getAs<FunctionType>();
8180 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008181 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
8182 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008183 bool allLTypes = true;
8184 bool allRTypes = true;
8185
8186 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008187 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008188 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008189 QualType RHS = rbase->getReturnType();
8190 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008191 bool UnqualifiedResult = Unqualified;
8192 if (!UnqualifiedResult)
8193 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008194 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008195 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008196 else
Alp Toker314cc812014-01-25 16:55:45 +00008197 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008198 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008199 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008200
8201 if (Unqualified)
8202 retType = retType.getUnqualifiedType();
8203
Alp Toker314cc812014-01-25 16:55:45 +00008204 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8205 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008206 if (Unqualified) {
8207 LRetType = LRetType.getUnqualifiedType();
8208 RRetType = RRetType.getUnqualifiedType();
8209 }
8210
8211 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008212 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008213 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008214 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008215
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008216 // FIXME: double check this
8217 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8218 // rbase->getRegParmAttr() != 0 &&
8219 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008220 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8221 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008222
Douglas Gregor8c940862010-01-18 17:14:39 +00008223 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008224 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00008225 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00008226
John McCall8c6b56f2010-12-15 01:06:38 +00008227 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008228 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
8229 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00008230 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
8231 return QualType();
8232
John McCall31168b02011-06-15 23:02:42 +00008233 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
8234 return QualType();
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008235 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
8236 return QualType();
John McCall31168b02011-06-15 23:02:42 +00008237
John McCall8c6b56f2010-12-15 01:06:38 +00008238 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8239 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008240
Rafael Espindola8778c282012-11-29 16:09:03 +00008241 if (lbaseInfo.getNoReturn() != NoReturn)
8242 allLTypes = false;
8243 if (rbaseInfo.getNoReturn() != NoReturn)
8244 allRTypes = false;
8245
John McCall31168b02011-06-15 23:02:42 +00008246 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008247
Eli Friedman47f77112008-08-22 00:56:42 +00008248 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008249 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8250 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008251 // Compatible functions must have the same number of parameters
8252 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00008253 return QualType();
8254
8255 // Variadic and non-variadic functions aren't compatible
8256 if (lproto->isVariadic() != rproto->isVariadic())
8257 return QualType();
8258
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008259 if (lproto->getTypeQuals() != rproto->getTypeQuals())
8260 return QualType();
8261
Akira Hatanaka98a49332017-09-22 00:41:05 +00008262 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8263 bool canUseLeft, canUseRight;
8264 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8265 newParamInfos))
Fariborz Jahanian97676972011-09-28 21:52:05 +00008266 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00008267
Akira Hatanaka98a49332017-09-22 00:41:05 +00008268 if (!canUseLeft)
8269 allLTypes = false;
8270 if (!canUseRight)
8271 allRTypes = false;
8272
Alp Toker601b22c2014-01-21 23:35:24 +00008273 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008274 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008275 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8276 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8277 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8278 QualType paramType = mergeFunctionParameterTypes(
8279 lParamType, rParamType, OfBlockPointer, Unqualified);
8280 if (paramType.isNull())
8281 return QualType();
8282
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008283 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008284 paramType = paramType.getUnqualifiedType();
8285
8286 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008287 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008288 lParamType = lParamType.getUnqualifiedType();
8289 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008290 }
Alp Toker601b22c2014-01-21 23:35:24 +00008291
8292 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008293 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008294 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008295 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008296 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00008297
Eli Friedman47f77112008-08-22 00:56:42 +00008298 if (allLTypes) return lhs;
8299 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008300
8301 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8302 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008303 EPI.ExtParameterInfos =
8304 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008305 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008306 }
8307
8308 if (lproto) allRTypes = false;
8309 if (rproto) allLTypes = false;
8310
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008311 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008312 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008313 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00008314 if (proto->isVariadic()) return QualType();
8315 // Check that the types are compatible with the types that
8316 // would result from default argument promotions (C99 6.7.5.3p15).
8317 // The only types actually affected are promotable integer
8318 // types and floats, which would be passed as a different
8319 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008320 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8321 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008322
Eli Friedman448ce402012-08-30 00:44:15 +00008323 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008324 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00008325 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
8326 paramTy = Enum->getDecl()->getIntegerType();
8327 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00008328 return QualType();
8329 }
Alp Toker601b22c2014-01-21 23:35:24 +00008330
8331 if (paramTy->isPromotableIntegerType() ||
8332 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00008333 return QualType();
8334 }
8335
8336 if (allLTypes) return lhs;
8337 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008338
8339 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8340 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008341 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008342 }
8343
8344 if (allLTypes) return lhs;
8345 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008346 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008347}
8348
John McCall433c2e62013-03-21 00:10:07 +00008349/// Given that we have an enum type and a non-enum type, try to merge them.
8350static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8351 QualType other, bool isBlockReturnType) {
8352 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8353 // a signed integer type, or an unsigned integer type.
8354 // Compatibility is based on the underlying type, not the promotion
8355 // type.
8356 QualType underlyingType = ET->getDecl()->getIntegerType();
8357 if (underlyingType.isNull()) return QualType();
8358 if (Context.hasSameType(underlyingType, other))
8359 return other;
8360
8361 // In block return types, we're more permissive and accept any
8362 // integral type of the same size.
8363 if (isBlockReturnType && other->isIntegerType() &&
8364 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8365 return other;
8366
8367 return QualType();
8368}
8369
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008370QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008371 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008372 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008373 // C++ [expr]: If an expression initially has the type "reference to T", the
8374 // type is adjusted to "T" prior to any further analysis, the expression
8375 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008376 // expression is an lvalue unless the reference is an rvalue reference and
8377 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008378 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8379 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008380
8381 if (Unqualified) {
8382 LHS = LHS.getUnqualifiedType();
8383 RHS = RHS.getUnqualifiedType();
8384 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00008385
Eli Friedman47f77112008-08-22 00:56:42 +00008386 QualType LHSCan = getCanonicalType(LHS),
8387 RHSCan = getCanonicalType(RHS);
8388
8389 // If two types are identical, they are compatible.
8390 if (LHSCan == RHSCan)
8391 return LHS;
8392
John McCall8ccfcb52009-09-24 19:53:00 +00008393 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008394 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8395 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008396 if (LQuals != RQuals) {
8397 // If any of these qualifiers are different, we have a type
8398 // mismatch.
8399 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008400 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008401 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8402 LQuals.hasUnaligned() != RQuals.hasUnaligned())
John McCall8ccfcb52009-09-24 19:53:00 +00008403 return QualType();
8404
8405 // Exactly one GC qualifier difference is allowed: __strong is
8406 // okay if the other type has no GC qualifier but is an Objective
8407 // C object pointer (i.e. implicitly strong by default). We fix
8408 // this by pretending that the unqualified type was actually
8409 // qualified __strong.
8410 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8411 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8412 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8413
8414 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8415 return QualType();
8416
8417 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8418 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8419 }
8420 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8421 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8422 }
Eli Friedman47f77112008-08-22 00:56:42 +00008423 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00008424 }
8425
8426 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008427
Eli Friedmandcca6332009-06-01 01:22:52 +00008428 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8429 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008430
Chris Lattnerfd652912008-01-14 05:45:46 +00008431 // We want to consider the two function types to be the same for these
8432 // comparisons, just force one to the other.
8433 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8434 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008435
8436 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008437 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8438 LHSClass = Type::ConstantArray;
8439 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8440 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008441
John McCall8b07ec22010-05-15 11:32:37 +00008442 // ObjCInterfaces are just specialized ObjCObjects.
8443 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8444 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8445
Nate Begemance4d7fc2008-04-18 23:10:10 +00008446 // Canonicalize ExtVector -> Vector.
8447 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8448 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008449
Chris Lattner95554662008-04-07 05:43:21 +00008450 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008451 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008452 // Note that we only have special rules for turning block enum
8453 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00008454 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008455 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008456 }
John McCall9dd450b2009-09-21 23:43:11 +00008457 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008458 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008459 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008460 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008461 if (OfBlockPointer && !BlockReturnType) {
8462 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8463 return LHS;
8464 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8465 return RHS;
8466 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008467
Eli Friedman47f77112008-08-22 00:56:42 +00008468 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00008469 }
Eli Friedman47f77112008-08-22 00:56:42 +00008470
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008471 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008472 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008473#define TYPE(Class, Base)
8474#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008475#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008476#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8477#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8478#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008479 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008480
Richard Smith27d807c2013-04-30 13:56:41 +00008481 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008482 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008483 case Type::LValueReference:
8484 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008485 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008486 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008487
John McCall8b07ec22010-05-15 11:32:37 +00008488 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008489 case Type::IncompleteArray:
8490 case Type::VariableArray:
8491 case Type::FunctionProto:
8492 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008493 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008494
Chris Lattnerfd652912008-01-14 05:45:46 +00008495 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008496 {
8497 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008498 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8499 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008500 if (Unqualified) {
8501 LHSPointee = LHSPointee.getUnqualifiedType();
8502 RHSPointee = RHSPointee.getUnqualifiedType();
8503 }
8504 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8505 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008506 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00008507 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008508 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008509 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008510 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008511 return getPointerType(ResultType);
8512 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008513 case Type::BlockPointer:
8514 {
8515 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008516 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8517 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008518 if (Unqualified) {
8519 LHSPointee = LHSPointee.getUnqualifiedType();
8520 RHSPointee = RHSPointee.getUnqualifiedType();
8521 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008522 if (getLangOpts().OpenCL) {
8523 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8524 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8525 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8526 // 6.12.5) thus the following check is asymmetric.
8527 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
8528 return QualType();
8529 LHSPteeQual.removeAddressSpace();
8530 RHSPteeQual.removeAddressSpace();
8531 LHSPointee =
8532 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8533 RHSPointee =
8534 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8535 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008536 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8537 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00008538 if (ResultType.isNull()) return QualType();
8539 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8540 return LHS;
8541 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8542 return RHS;
8543 return getBlockPointerType(ResultType);
8544 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008545 case Type::Atomic:
8546 {
8547 // Merge two pointer types, while trying to preserve typedef info
8548 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8549 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8550 if (Unqualified) {
8551 LHSValue = LHSValue.getUnqualifiedType();
8552 RHSValue = RHSValue.getUnqualifiedType();
8553 }
8554 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8555 Unqualified);
8556 if (ResultType.isNull()) return QualType();
8557 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8558 return LHS;
8559 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8560 return RHS;
8561 return getAtomicType(ResultType);
8562 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008563 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008564 {
8565 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8566 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8567 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8568 return QualType();
8569
8570 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8571 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008572 if (Unqualified) {
8573 LHSElem = LHSElem.getUnqualifiedType();
8574 RHSElem = RHSElem.getUnqualifiedType();
8575 }
8576
8577 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008578 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00008579 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8580 return LHS;
8581 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8582 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008583 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8584 ArrayType::ArraySizeModifier(), 0);
8585 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8586 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008587 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8588 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00008589 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8590 return LHS;
8591 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8592 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008593 if (LVAT) {
8594 // FIXME: This isn't correct! But tricky to implement because
8595 // the array's size has to be the size of LHS, but the type
8596 // has to be different.
8597 return LHS;
8598 }
8599 if (RVAT) {
8600 // FIXME: This isn't correct! But tricky to implement because
8601 // the array's size has to be the size of RHS, but the type
8602 // has to be different.
8603 return RHS;
8604 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008605 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8606 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008607 return getIncompleteArrayType(ResultType,
8608 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008609 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008610 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008611 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008612 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008613 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00008614 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00008615 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008616 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00008617 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00008618 case Type::Complex:
8619 // Distinct complex types are incompatible.
8620 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008621 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008622 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008623 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8624 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008625 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00008626 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00008627 case Type::ObjCObject: {
8628 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008629 // FIXME: This should be type compatibility, e.g. whether
8630 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00008631 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
8632 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
8633 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008634 return LHS;
8635
Eli Friedman47f77112008-08-22 00:56:42 +00008636 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00008637 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008638 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008639 if (OfBlockPointer) {
8640 if (canAssignObjCInterfacesInBlockPointer(
8641 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008642 RHS->getAs<ObjCObjectPointerType>(),
8643 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00008644 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008645 return QualType();
8646 }
John McCall9dd450b2009-09-21 23:43:11 +00008647 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8648 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00008649 return LHS;
8650
Steve Naroffc68cfcf2008-12-10 22:14:21 +00008651 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00008652 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00008653 assert(LHS != RHS &&
8654 "Equivalent pipe types should have already been handled!");
8655 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00008656 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008657
David Blaikie8a40f702012-01-17 06:56:22 +00008658 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00008659}
Ted Kremenekfc581a92007-10-31 17:10:13 +00008660
Akira Hatanaka98a49332017-09-22 00:41:05 +00008661bool ASTContext::mergeExtParameterInfo(
8662 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
8663 bool &CanUseFirst, bool &CanUseSecond,
8664 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
8665 assert(NewParamInfos.empty() && "param info list not empty");
8666 CanUseFirst = CanUseSecond = true;
8667 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
8668 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
8669
John McCall18afab72016-03-01 00:49:02 +00008670 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00008671 // we match if and only if the second type also doesn't have them.
8672 if (!FirstHasInfo && !SecondHasInfo)
8673 return true;
John McCall18afab72016-03-01 00:49:02 +00008674
Akira Hatanaka98a49332017-09-22 00:41:05 +00008675 bool NeedParamInfo = false;
8676 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
8677 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00008678
Akira Hatanaka98a49332017-09-22 00:41:05 +00008679 for (size_t I = 0; I < E; ++I) {
8680 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
8681 if (FirstHasInfo)
8682 FirstParam = FirstFnType->getExtParameterInfo(I);
8683 if (SecondHasInfo)
8684 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00008685
Akira Hatanaka98a49332017-09-22 00:41:05 +00008686 // Cannot merge unless everything except the noescape flag matches.
8687 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00008688 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008689
8690 bool FirstNoEscape = FirstParam.isNoEscape();
8691 bool SecondNoEscape = SecondParam.isNoEscape();
8692 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
8693 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
8694 if (NewParamInfos.back().getOpaqueValue())
8695 NeedParamInfo = true;
8696 if (FirstNoEscape != IsNoEscape)
8697 CanUseFirst = false;
8698 if (SecondNoEscape != IsNoEscape)
8699 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00008700 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00008701
8702 if (!NeedParamInfo)
8703 NewParamInfos.clear();
8704
Fariborz Jahanian97676972011-09-28 21:52:05 +00008705 return true;
8706}
8707
Chandler Carruth21c90602015-12-30 03:24:14 +00008708void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8709 ObjCLayouts[CD] = nullptr;
8710}
8711
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008712/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8713/// 'RHS' attributes and returns the merged version; including for function
8714/// return types.
8715QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8716 QualType LHSCan = getCanonicalType(LHS),
8717 RHSCan = getCanonicalType(RHS);
8718 // If two types are identical, they are compatible.
8719 if (LHSCan == RHSCan)
8720 return LHS;
8721 if (RHSCan->isFunctionType()) {
8722 if (!LHSCan->isFunctionType())
8723 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00008724 QualType OldReturnType =
8725 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008726 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008727 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008728 QualType ResReturnType =
8729 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8730 if (ResReturnType.isNull())
8731 return QualType();
8732 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8733 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8734 // In either case, use OldReturnType to build the new function type.
8735 const FunctionType *F = LHS->getAs<FunctionType>();
8736 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008737 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8738 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00008739 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00008740 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008741 return ResultType;
8742 }
8743 }
8744 return QualType();
8745 }
8746
8747 // If the qualifiers are different, the types can still be merged.
8748 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8749 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8750 if (LQuals != RQuals) {
8751 // If any of these qualifiers are different, we have a type mismatch.
8752 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8753 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8754 return QualType();
8755
8756 // Exactly one GC qualifier difference is allowed: __strong is
8757 // okay if the other type has no GC qualifier but is an Objective
8758 // C object pointer (i.e. implicitly strong by default). We fix
8759 // this by pretending that the unqualified type was actually
8760 // qualified __strong.
8761 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8762 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8763 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8764
8765 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8766 return QualType();
8767
8768 if (GC_L == Qualifiers::Strong)
8769 return LHS;
8770 if (GC_R == Qualifiers::Strong)
8771 return RHS;
8772 return QualType();
8773 }
8774
8775 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8776 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8777 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8778 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8779 if (ResQT == LHSBaseQT)
8780 return LHS;
8781 if (ResQT == RHSBaseQT)
8782 return RHS;
8783 }
8784 return QualType();
8785}
8786
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008787//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008788// Integer Predicates
8789//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008790
Jay Foad39c79802011-01-12 09:06:06 +00008791unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00008792 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008793 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008794 if (T->isBooleanType())
8795 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008796 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008797 return (unsigned)getTypeSize(T);
8798}
8799
Abramo Bagnara13640492012-09-09 10:21:24 +00008800QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008801 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008802
8803 // Turn <4 x signed int> -> <4 x unsigned int>
8804 if (const VectorType *VTy = T->getAs<VectorType>())
8805 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008806 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008807
8808 // For enums, we return the unsigned version of the base type.
8809 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008810 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008811
8812 const BuiltinType *BTy = T->getAs<BuiltinType>();
8813 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008814 switch (BTy->getKind()) {
8815 case BuiltinType::Char_S:
8816 case BuiltinType::SChar:
8817 return UnsignedCharTy;
8818 case BuiltinType::Short:
8819 return UnsignedShortTy;
8820 case BuiltinType::Int:
8821 return UnsignedIntTy;
8822 case BuiltinType::Long:
8823 return UnsignedLongTy;
8824 case BuiltinType::LongLong:
8825 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008826 case BuiltinType::Int128:
8827 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008828 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008829 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008830 }
8831}
8832
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008833ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008834
Richard Smith1fa5d642013-05-11 05:45:24 +00008835void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8836 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008837
8838//===----------------------------------------------------------------------===//
8839// Builtin Type Computation
8840//===----------------------------------------------------------------------===//
8841
8842/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008843/// pointer over the consumed characters. This returns the resultant type. If
8844/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8845/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8846/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008847///
8848/// RequiresICE is filled in on return to indicate whether the value is required
8849/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008850static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008851 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00008852 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008853 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008854 // Modifiers.
8855 int HowLong = 0;
8856 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008857 RequiresICE = false;
Chandler Carruth45bbe012017-03-24 09:11:57 +00008858
Chris Lattnerdc226c22010-10-01 22:42:38 +00008859 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00008860 bool Done = false;
8861 #ifndef NDEBUG
8862 bool IsSpecialLong = false;
8863 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00008864 while (!Done) {
8865 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008866 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008867 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008868 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008869 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008870 case 'S':
8871 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8872 assert(!Signed && "Can't use 'S' modifier multiple times!");
8873 Signed = true;
8874 break;
8875 case 'U':
8876 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008877 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008878 Unsigned = true;
8879 break;
8880 case 'L':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008881 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008882 assert(HowLong <= 2 && "Can't have LLLL modifier");
8883 ++HowLong;
8884 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008885 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008886 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
8887 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
8888 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00008889 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008890 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00008891 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008892 if (Context.getTargetInfo().getLongWidth() == 32)
8893 ++HowLong;
8894 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00008895 case 'W':
8896 // This modifier represents int64 type.
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008897 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00008898 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00008899 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008900 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00008901 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00008902 switch (Context.getTargetInfo().getInt64Type()) {
8903 default:
8904 llvm_unreachable("Unexpected integer type");
8905 case TargetInfo::SignedLong:
8906 HowLong = 1;
8907 break;
8908 case TargetInfo::SignedLongLong:
8909 HowLong = 2;
8910 break;
8911 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00008912 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008913 }
8914 }
8915
8916 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008917
Chris Lattnerecd79c62009-06-14 00:45:47 +00008918 // Read the base type.
8919 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008920 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008921 case 'v':
8922 assert(HowLong == 0 && !Signed && !Unsigned &&
8923 "Bad modifiers used with 'v'!");
8924 Type = Context.VoidTy;
8925 break;
Jack Carter24bef982013-08-15 15:16:57 +00008926 case 'h':
8927 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008928 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008929 Type = Context.HalfTy;
8930 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008931 case 'f':
8932 assert(HowLong == 0 && !Signed && !Unsigned &&
8933 "Bad modifiers used with 'f'!");
8934 Type = Context.FloatTy;
8935 break;
8936 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00008937 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00008938 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00008939 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00008940 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00008941 else if (HowLong == 2)
8942 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008943 else
8944 Type = Context.DoubleTy;
8945 break;
8946 case 's':
8947 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8948 if (Unsigned)
8949 Type = Context.UnsignedShortTy;
8950 else
8951 Type = Context.ShortTy;
8952 break;
8953 case 'i':
8954 if (HowLong == 3)
8955 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8956 else if (HowLong == 2)
8957 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8958 else if (HowLong == 1)
8959 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8960 else
8961 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8962 break;
8963 case 'c':
8964 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8965 if (Signed)
8966 Type = Context.SignedCharTy;
8967 else if (Unsigned)
8968 Type = Context.UnsignedCharTy;
8969 else
8970 Type = Context.CharTy;
8971 break;
8972 case 'b': // boolean
8973 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8974 Type = Context.BoolTy;
8975 break;
8976 case 'z': // size_t.
8977 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8978 Type = Context.getSizeType();
8979 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00008980 case 'w': // wchar_t.
8981 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
8982 Type = Context.getWideCharType();
8983 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008984 case 'F':
8985 Type = Context.getCFConstantStringType();
8986 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008987 case 'G':
8988 Type = Context.getObjCIdType();
8989 break;
8990 case 'H':
8991 Type = Context.getObjCSelType();
8992 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008993 case 'M':
8994 Type = Context.getObjCSuperType();
8995 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008996 case 'a':
8997 Type = Context.getBuiltinVaListType();
8998 assert(!Type.isNull() && "builtin va list type not initialized!");
8999 break;
9000 case 'A':
9001 // This is a "reference" to a va_list; however, what exactly
9002 // this means depends on how va_list is defined. There are two
9003 // different kinds of va_list: ones passed by value, and ones
9004 // passed by reference. An example of a by-value va_list is
9005 // x86, where va_list is a char*. An example of by-ref va_list
9006 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9007 // we want this argument to be a char*&; for x86-64, we want
9008 // it to be a __va_list_tag*.
9009 Type = Context.getBuiltinVaListType();
9010 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009011 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009012 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009013 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009014 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009015 break;
9016 case 'V': {
9017 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009018 unsigned NumElements = strtoul(Str, &End, 10);
9019 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009020 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009021
Chandler Carruth45bbe012017-03-24 09:11:57 +00009022 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
9023 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009024 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00009025
9026 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009027 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009028 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009029 break;
9030 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009031 case 'E': {
9032 char *End;
9033
9034 unsigned NumElements = strtoul(Str, &End, 10);
9035 assert(End != Str && "Missing vector size");
9036
9037 Str = End;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009038
Douglas Gregorfed66992012-06-07 18:08:25 +00009039 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009040 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009041 Type = Context.getExtVectorType(ElementType, NumElements);
9042 break;
9043 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009044 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009045 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009046 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009047 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009048 Type = Context.getComplexType(ElementType);
9049 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009050 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009051 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009052 Type = Context.getPointerDiffType();
9053 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009054 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009055 Type = Context.getFILEType();
9056 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009057 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009058 return QualType();
9059 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009060 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009061 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009062 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009063 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009064 else
9065 Type = Context.getjmp_bufType();
9066
Mike Stump2adb4da2009-07-28 23:47:15 +00009067 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009068 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00009069 return QualType();
9070 }
9071 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009072 case 'K':
9073 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9074 Type = Context.getucontext_tType();
9075
9076 if (Type.isNull()) {
9077 Error = ASTContext::GE_Missing_ucontext;
9078 return QualType();
9079 }
9080 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009081 case 'p':
9082 Type = Context.getProcessIDType();
9083 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009084 }
Mike Stump11289f42009-09-09 15:08:12 +00009085
Chris Lattnerdc226c22010-10-01 22:42:38 +00009086 // If there are modifiers and if we're allowed to parse them, go for it.
9087 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009088 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009089 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009090 default: Done = true; --Str; break;
9091 case '*':
9092 case '&': {
9093 // Both pointers and references can have their pointee types
9094 // qualified with an address space.
9095 char *End;
9096 unsigned AddrSpace = strtoul(Str, &End, 10);
9097 if (End != Str && AddrSpace != 0) {
Alexander Richardson6d989432017-10-15 18:48:14 +00009098 Type = Context.getAddrSpaceQualType(Type,
9099 getLangASFromTargetAS(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009100 Str = End;
9101 }
9102 if (c == '*')
9103 Type = Context.getPointerType(Type);
9104 else
9105 Type = Context.getLValueReferenceType(Type);
9106 break;
9107 }
9108 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9109 case 'C':
9110 Type = Type.withConst();
9111 break;
9112 case 'D':
9113 Type = Context.getVolatileType(Type);
9114 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009115 case 'R':
9116 Type = Type.withRestrict();
9117 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009118 }
9119 }
Chris Lattner84733392010-10-01 07:13:18 +00009120
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009121 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00009122 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009123
Chris Lattnerecd79c62009-06-14 00:45:47 +00009124 return Type;
9125}
9126
9127/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009128QualType ASTContext::GetBuiltinType(unsigned Id,
9129 GetBuiltinTypeError &Error,
9130 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009131 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00009132
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009133 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009134
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009135 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009136 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009137 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9138 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009139 if (Error != GE_None)
9140 return QualType();
Chandler Carruth45bbe012017-03-24 09:11:57 +00009141
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009142 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Chandler Carruth45bbe012017-03-24 09:11:57 +00009143
Chris Lattnerecd79c62009-06-14 00:45:47 +00009144 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009145 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009146 if (Error != GE_None)
9147 return QualType();
9148
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009149 // If this argument is required to be an IntegerConstantExpression and the
9150 // caller cares, fill in the bitmask we return.
9151 if (RequiresICE && IntegerConstantArgs)
9152 *IntegerConstantArgs |= 1 << ArgTypes.size();
9153
Chris Lattnerecd79c62009-06-14 00:45:47 +00009154 // Do array -> pointer decay. The builtin should use the decayed type.
9155 if (Ty->isArrayType())
9156 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009157
Chris Lattnerecd79c62009-06-14 00:45:47 +00009158 ArgTypes.push_back(Ty);
9159 }
9160
David Majnemerba3e5ec2015-03-13 18:26:17 +00009161 if (Id == Builtin::BI__GetExceptionInfo)
9162 return QualType();
9163
Chris Lattnerecd79c62009-06-14 00:45:47 +00009164 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9165 "'.' should only occur at end of builtin type list!");
9166
Reid Kleckner78af0702013-08-27 23:08:25 +00009167 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00009168 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9169
9170 bool Variadic = (TypeStr[0] == '.');
9171
Richard Smith836de6b2016-12-19 23:59:34 +00009172 // We really shouldn't be making a no-proto type here.
9173 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00009174 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00009175
John McCalldb40c7f2010-12-14 08:05:40 +00009176 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00009177 EPI.ExtInfo = EI;
9178 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00009179 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9180 EPI.ExceptionSpec.Type =
9181 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00009182
Jordan Rose5c382722013-03-08 21:51:21 +00009183 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009184}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00009185
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009186static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9187 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009188 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009189 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009190
Richard Smithe2467b72017-11-16 23:54:56 +00009191 // Non-user-provided functions get emitted as weak definitions with every
9192 // use, no matter whether they've been explicitly instantiated etc.
9193 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
9194 if (!MD->isUserProvided())
9195 return GVA_DiscardableODR;
9196
Yaron Keren4cd211b2017-02-22 14:32:39 +00009197 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009198 switch (FD->getTemplateSpecializationKind()) {
9199 case TSK_Undeclared:
9200 case TSK_ExplicitSpecialization:
9201 External = GVA_StrongExternal;
9202 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009203
Rafael Espindola3ae00052013-05-13 00:12:11 +00009204 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009205 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009206
David Majnemerc3d07332014-05-15 06:25:57 +00009207 // C++11 [temp.explicit]p10:
9208 // [ Note: The intent is that an inline function that is the subject of
9209 // an explicit instantiation declaration will still be implicitly
9210 // instantiated when used so that the body can be considered for
9211 // inlining, but that no out-of-line copy of the inline function would be
9212 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00009213 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00009214 return GVA_AvailableExternally;
9215
Rafael Espindola3ae00052013-05-13 00:12:11 +00009216 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009217 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009218 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009219 }
9220
9221 if (!FD->isInlined())
9222 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00009223
David Majnemer3f021502015-10-08 04:53:31 +00009224 if ((!Context.getLangOpts().CPlusPlus &&
9225 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009226 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00009227 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009228 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9229
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009230 // GNU or C99 inline semantics. Determine whether this symbol should be
9231 // externally visible.
9232 if (FD->isInlineDefinitionExternallyVisible())
9233 return External;
9234
9235 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00009236 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009237 }
9238
David Majnemer54e3ba52014-04-02 23:17:29 +00009239 // Functions specified with extern and inline in -fms-compatibility mode
9240 // forcibly get emitted. While the body of the function cannot be later
9241 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00009242 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00009243 return GVA_StrongODR;
9244
David Majnemer27d69db2014-04-28 22:17:59 +00009245 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009246}
9247
Artem Belevichca2b9512016-05-02 20:30:03 +00009248static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00009249 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009250 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9251 // dllexport/dllimport on inline functions.
9252 if (D->hasAttr<DLLImportAttr>()) {
9253 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9254 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00009255 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009256 if (L == GVA_DiscardableODR)
9257 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00009258 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9259 D->hasAttr<CUDAGlobalAttr>()) {
9260 // Device-side functions with __global__ attribute must always be
9261 // visible externally so they can be launched from host.
9262 if (L == GVA_DiscardableODR || L == GVA_Internal)
9263 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009264 }
9265 return L;
9266}
9267
Richard Smitha4653622017-09-06 20:01:14 +00009268/// Adjust the GVALinkage for a declaration based on what an external AST source
9269/// knows about whether there can be other definitions of this declaration.
9270static GVALinkage
9271adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9272 GVALinkage L) {
9273 ExternalASTSource *Source = Ctx.getExternalSource();
9274 if (!Source)
9275 return L;
9276
9277 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00009278 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00009279 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009280 if (L == GVA_DiscardableODR)
9281 return GVA_StrongODR;
9282 break;
Richard Smitha4653622017-09-06 20:01:14 +00009283
David Blaikie9ffe5a32017-01-30 05:00:26 +00009284 case ExternalASTSource::EK_Always:
9285 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00009286
David Blaikie9ffe5a32017-01-30 05:00:26 +00009287 case ExternalASTSource::EK_ReplyHazy:
9288 break;
9289 }
9290 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009291}
9292
Richard Smitha4653622017-09-06 20:01:14 +00009293GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9294 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9295 adjustGVALinkageForAttributes(*this, FD,
9296 basicGVALinkageForFunction(*this, FD)));
9297}
9298
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009299static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9300 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009301 if (!VD->isExternallyVisible())
9302 return GVA_Internal;
9303
David Majnemer27d69db2014-04-28 22:17:59 +00009304 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00009305 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9306 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9307 LexicalContext = LexicalContext->getLexicalParent();
9308
David Blaikieeb210012017-01-27 23:11:10 +00009309 // ObjC Blocks can create local variables that don't have a FunctionDecl
9310 // LexicalContext.
9311 if (!LexicalContext)
9312 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00009313
David Blaikieeb210012017-01-27 23:11:10 +00009314 // Otherwise, let the static local variable inherit its linkage from the
9315 // nearest enclosing function.
9316 auto StaticLocalLinkage =
9317 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9318
9319 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9320 // be emitted in any object with references to the symbol for the object it
9321 // contains, whether inline or out-of-line."
9322 // Similar behavior is observed with MSVC. An alternative ABI could use
9323 // StrongODR/AvailableExternally to match the function, but none are
9324 // known/supported currently.
9325 if (StaticLocalLinkage == GVA_StrongODR ||
9326 StaticLocalLinkage == GVA_AvailableExternally)
9327 return GVA_DiscardableODR;
9328 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009329 }
9330
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009331 // MSVC treats in-class initialized static data members as definitions.
9332 // By giving them non-strong linkage, out-of-line definitions won't
9333 // cause link errors.
9334 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9335 return GVA_DiscardableODR;
9336
Richard Smithd9b90092016-07-02 01:32:16 +00009337 // Most non-template variables have strong linkage; inline variables are
9338 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9339 GVALinkage StrongLinkage;
9340 switch (Context.getInlineVariableDefinitionKind(VD)) {
9341 case ASTContext::InlineVariableDefinitionKind::None:
9342 StrongLinkage = GVA_StrongExternal;
9343 break;
9344 case ASTContext::InlineVariableDefinitionKind::Weak:
9345 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009346 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009347 break;
9348 case ASTContext::InlineVariableDefinitionKind::Strong:
9349 StrongLinkage = GVA_StrongODR;
9350 break;
9351 }
Richard Smith62f19e72016-06-25 00:15:56 +00009352
Richard Smith8809a0c2013-09-27 20:14:12 +00009353 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009354 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009355 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009356
David Majnemer6d1780c2015-07-17 23:36:49 +00009357 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00009358 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9359 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00009360 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00009361 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009362
Rafael Espindola3ae00052013-05-13 00:12:11 +00009363 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009364 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009365
David Majnemer27d69db2014-04-28 22:17:59 +00009366 case TSK_ExplicitInstantiationDeclaration:
9367 return GVA_AvailableExternally;
9368
Rafael Espindola3ae00052013-05-13 00:12:11 +00009369 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009370 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009371 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009372
9373 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009374}
9375
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009376GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009377 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9378 adjustGVALinkageForAttributes(*this, VD,
9379 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009380}
9381
David Blaikiee6b7c282017-04-11 20:46:34 +00009382bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009383 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
9384 if (!VD->isFileVarDecl())
9385 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009386 // Global named register variables (GNU extension) are never emitted.
9387 if (VD->getStorageClass() == SC_Register)
9388 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009389 if (VD->getDescribedVarTemplate() ||
9390 isa<VarTemplatePartialSpecializationDecl>(VD))
9391 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00009392 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9393 // We never need to emit an uninstantiated function template.
9394 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9395 return false;
Nico Weber66220292016-03-02 17:28:48 +00009396 } else if (isa<PragmaCommentDecl>(D))
9397 return true;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00009398 else if (isa<OMPThreadPrivateDecl>(D) ||
9399 D->hasAttr<OMPDeclareTargetDeclAttr>())
9400 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009401 else if (isa<PragmaDetectMismatchDecl>(D))
9402 return true;
Nico Weber66220292016-03-02 17:28:48 +00009403 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009404 return !D->getDeclContext()->isDependentContext();
9405 else if (isa<OMPDeclareReductionDecl>(D))
9406 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009407 else if (isa<ImportDecl>(D))
9408 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009409 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009410 return false;
9411
9412 // If this is a member of a class template, we do not need to emit it.
9413 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009414 return false;
9415
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009416 // Weak references don't produce any output by themselves.
9417 if (D->hasAttr<WeakRefAttr>())
9418 return false;
9419
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009420 // Aliases and used decls are required.
9421 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9422 return true;
9423
9424 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9425 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009426 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009427 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009428
9429 // Constructors and destructors are required.
9430 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9431 return true;
9432
John McCall6bd2a892013-01-25 22:31:03 +00009433 // The key function for a class is required. This rule only comes
9434 // into play when inline functions can be key functions, though.
9435 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
9436 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9437 const CXXRecordDecl *RD = MD->getParent();
9438 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9439 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9440 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9441 return true;
9442 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009443 }
9444 }
9445
David Blaikie9ffe5a32017-01-30 05:00:26 +00009446 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9447
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009448 // static, static inline, always_inline, and extern inline functions can
9449 // always be deferred. Normal inline functions can be deferred in C99/C++.
9450 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009451 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009452 }
Douglas Gregor87d81242011-09-10 00:22:34 +00009453
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009454 const VarDecl *VD = cast<VarDecl>(D);
9455 assert(VD->isFileVarDecl() && "Expected file scoped var");
9456
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009457 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9458 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009459 return false;
9460
Richard Smitha0e5e542012-11-12 21:38:00 +00009461 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +00009462 auto Linkage = GetGVALinkageForVariable(VD);
9463 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +00009464 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009465
Richard Smitha4653622017-09-06 20:01:14 +00009466 // We never need to emit a variable that is available in another TU.
9467 if (Linkage == GVA_AvailableExternally)
9468 return false;
9469
Richard Smitha0e5e542012-11-12 21:38:00 +00009470 // Variables that have destruction with side-effects are required.
9471 if (VD->getType().isDestructedType())
9472 return true;
9473
9474 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009475 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009476 // We can get a value-dependent initializer during error recovery.
9477 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009478 return true;
9479
Richard Smithda383632016-08-15 01:33:41 +00009480 // Likewise, variables with tuple-like bindings are required if their
9481 // bindings have side-effects.
9482 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
9483 for (auto *BD : DD->bindings())
9484 if (auto *BindingVD = BD->getHoldingVar())
9485 if (DeclMustBeEmitted(BindingVD))
9486 return true;
9487
Richard Smitha0e5e542012-11-12 21:38:00 +00009488 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009489}
Charles Davis53c59df2010-08-16 03:33:14 +00009490
Erich Keane281d20b2018-01-08 21:34:17 +00009491void ASTContext::forEachMultiversionedFunctionVersion(
9492 const FunctionDecl *FD,
9493 llvm::function_ref<void(const FunctionDecl *)> Pred) const {
9494 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
9495 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
9496 FD = FD->getCanonicalDecl();
9497 for (auto *CurDecl :
9498 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
9499 FunctionDecl *CurFD = CurDecl->getAsFunction()->getCanonicalDecl();
9500 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
9501 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
9502 SeenDecls.insert(CurFD);
9503 Pred(CurFD);
9504 }
9505 }
9506}
9507
Reid Kleckner78af0702013-08-27 23:08:25 +00009508CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9509 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00009510 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00009511 if (IsCXXMethod)
9512 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00009513
Alexey Bataeva7547182016-05-18 09:06:38 +00009514 switch (LangOpts.getDefaultCallingConv()) {
9515 case LangOptions::DCC_None:
9516 break;
9517 case LangOptions::DCC_CDecl:
9518 return CC_C;
9519 case LangOptions::DCC_FastCall:
Erich Keane5759fa72017-10-24 23:12:01 +00009520 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
Alexey Bataeva7547182016-05-18 09:06:38 +00009521 return CC_X86FastCall;
9522 break;
9523 case LangOptions::DCC_StdCall:
9524 if (!IsVariadic)
9525 return CC_X86StdCall;
9526 break;
9527 case LangOptions::DCC_VectorCall:
9528 // __vectorcall cannot be applied to variadic functions.
9529 if (!IsVariadic)
9530 return CC_X86VectorCall;
9531 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00009532 case LangOptions::DCC_RegCall:
9533 // __regcall cannot be applied to variadic functions.
9534 if (!IsVariadic)
9535 return CC_X86RegCall;
9536 break;
Alexey Bataeva7547182016-05-18 09:06:38 +00009537 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00009538 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00009539}
9540
Jay Foad39c79802011-01-12 09:06:06 +00009541bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00009542 // Pass through to the C++ ABI object
9543 return ABI->isNearlyEmpty(RD);
9544}
9545
Reid Kleckner96f8f932014-02-05 17:27:08 +00009546VTableContextBase *ASTContext::getVTableContext() {
9547 if (!VTContext.get()) {
9548 if (Target->getCXXABI().isMicrosoft())
9549 VTContext.reset(new MicrosoftVTableContext(*this));
9550 else
9551 VTContext.reset(new ItaniumVTableContext(*this));
9552 }
9553 return VTContext.get();
9554}
9555
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009556MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00009557 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009558 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009559 case TargetCXXABI::GenericItanium:
9560 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009561 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009562 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009563 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009564 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009565 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009566 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009567 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009568 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009569 }
David Blaikie83d382b2011-09-23 05:06:16 +00009570 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009571}
9572
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009573CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009574
9575size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00009576 return ASTRecordLayouts.getMemorySize() +
9577 llvm::capacity_in_bytes(ObjCLayouts) +
9578 llvm::capacity_in_bytes(KeyFunctions) +
9579 llvm::capacity_in_bytes(ObjCImpls) +
9580 llvm::capacity_in_bytes(BlockVarCopyInits) +
9581 llvm::capacity_in_bytes(DeclAttrs) +
9582 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9583 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9584 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9585 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9586 llvm::capacity_in_bytes(OverriddenMethods) +
9587 llvm::capacity_in_bytes(Types) +
9588 llvm::capacity_in_bytes(VariableArrayTypes) +
9589 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009590}
Ted Kremenek540017e2011-10-06 05:00:56 +00009591
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009592/// getIntTypeForBitwidth -
9593/// sets integer QualTy according to specified details:
9594/// bitwidth, signed/unsigned.
9595/// Returns empty type if there is no appropriate target types.
9596QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9597 unsigned Signed) const {
9598 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9599 CanQualType QualTy = getFromTargetType(Ty);
9600 if (!QualTy && DestWidth == 128)
9601 return Signed ? Int128Ty : UnsignedInt128Ty;
9602 return QualTy;
9603}
9604
9605/// getRealTypeForBitwidth -
9606/// sets floating point QualTy according to specified bitwidth.
9607/// Returns empty type if there is no appropriate target types.
9608QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9609 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9610 switch (Ty) {
9611 case TargetInfo::Float:
9612 return FloatTy;
9613 case TargetInfo::Double:
9614 return DoubleTy;
9615 case TargetInfo::LongDouble:
9616 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00009617 case TargetInfo::Float128:
9618 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009619 case TargetInfo::NoFloat:
9620 return QualType();
9621 }
9622
9623 llvm_unreachable("Unhandled TargetInfo::RealType value");
9624}
9625
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009626void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9627 if (Number > 1)
9628 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00009629}
9630
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009631unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009632 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009633 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00009634}
9635
David Majnemer2206bf52014-03-05 08:57:59 +00009636void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9637 if (Number > 1)
9638 StaticLocalNumbers[VD] = Number;
9639}
9640
9641unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009642 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00009643 return I != StaticLocalNumbers.end() ? I->second : 1;
9644}
9645
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009646MangleNumberingContext &
9647ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009648 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +00009649 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +00009650 if (!MCtx)
9651 MCtx = createMangleNumberingContext();
9652 return *MCtx;
9653}
9654
Justin Lebar20ebffc2016-10-10 16:26:19 +00009655std::unique_ptr<MangleNumberingContext>
9656ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009657 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00009658}
9659
David Majnemere7a818f2015-03-06 18:53:55 +00009660const CXXConstructorDecl *
9661ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9662 return ABI->getCopyConstructorForExceptionObject(
9663 cast<CXXRecordDecl>(RD->getFirstDecl()));
9664}
9665
9666void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9667 CXXConstructorDecl *CD) {
9668 return ABI->addCopyConstructorForExceptionObject(
9669 cast<CXXRecordDecl>(RD->getFirstDecl()),
9670 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9671}
9672
David Majnemer00350522015-08-31 18:48:39 +00009673void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9674 TypedefNameDecl *DD) {
9675 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9676}
9677
9678TypedefNameDecl *
9679ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9680 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9681}
9682
9683void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9684 DeclaratorDecl *DD) {
9685 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9686}
9687
9688DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9689 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9690}
9691
Ted Kremenek540017e2011-10-06 05:00:56 +00009692void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9693 ParamIndices[D] = index;
9694}
9695
9696unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9697 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9698 assert(I != ParamIndices.end() &&
9699 "ParmIndices lacks entry set by ParmVarDecl");
9700 return I->second;
9701}
Fariborz Jahanian615de762013-05-28 17:37:39 +00009702
Richard Smithe6c01442013-06-05 00:46:14 +00009703APValue *
9704ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9705 bool MayCreate) {
9706 assert(E && E->getStorageDuration() == SD_Static &&
9707 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00009708 if (MayCreate) {
9709 APValue *&MTVI = MaterializedTemporaryValues[E];
9710 if (!MTVI)
9711 MTVI = new (*this) APValue;
9712 return MTVI;
9713 }
Richard Smithe6c01442013-06-05 00:46:14 +00009714
David Majnemer2dcef9e2015-08-13 23:50:15 +00009715 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00009716}
9717
Fariborz Jahanian615de762013-05-28 17:37:39 +00009718bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9719 const llvm::Triple &T = getTargetInfo().getTriple();
9720 if (!T.isOSDarwin())
9721 return false;
9722
Bob Wilson2c82c3d2013-11-02 23:27:49 +00009723 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9724 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9725 return false;
9726
Fariborz Jahanian615de762013-05-28 17:37:39 +00009727 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9728 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9729 uint64_t Size = sizeChars.getQuantity();
9730 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9731 unsigned Align = alignChars.getQuantity();
9732 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9733 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9734}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009735
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009736static ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009737 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009738 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009739 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009740 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009741 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009742 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009743}
9744
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009745namespace {
9746
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009747/// Template specializations to abstract away from pointers and TypeLocs.
9748/// @{
9749template <typename T>
9750ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9751 return ast_type_traits::DynTypedNode::create(*Node);
9752}
9753template <>
9754ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9755 return ast_type_traits::DynTypedNode::create(Node);
9756}
9757template <>
9758ast_type_traits::DynTypedNode
9759createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9760 return ast_type_traits::DynTypedNode::create(Node);
9761}
9762/// @}
9763
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009764 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
9765 /// parents as defined by the \c RecursiveASTVisitor.
9766 ///
9767 /// Note that the relationship described here is purely in terms of AST
9768 /// traversal - there are other relationships (for example declaration context)
9769 /// in the AST that are better modeled by special matchers.
9770 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009771 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009772 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009773 public:
9774 /// \brief Builds and returns the translation unit's parent map.
9775 ///
9776 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009777 static std::pair<ASTContext::ParentMapPointers *,
9778 ASTContext::ParentMapOtherNodes *>
9779 buildMap(TranslationUnitDecl &TU) {
9780 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9781 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009782 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009783 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009784 }
9785
9786 private:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009787 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9788
9789 using VisitorBase = RecursiveASTVisitor<ParentMapASTVisitor>;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009790
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009791 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9792 ASTContext::ParentMapOtherNodes *OtherParents)
9793 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009794
9795 bool shouldVisitTemplateInstantiations() const {
9796 return true;
9797 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009798
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009799 bool shouldVisitImplicitCode() const {
9800 return true;
9801 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009802
Richard Smith85838722015-11-24 03:09:01 +00009803 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9804 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009805 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00009806 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00009807 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009808 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00009809 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009810 // FIXME: Currently we add the same parent multiple times, but only
9811 // when no memoization data is available for the type.
9812 // For example when we visit all subexpressions of template
9813 // instantiations; this is suboptimal, but benign: the only way to
9814 // visit those is with hasAncestor / hasParent, and those do not create
9815 // new matches.
9816 // The plan is to enable DynTypedNode to be storable in a map or hash
9817 // map. The main problem there is to implement hash functions /
9818 // comparison operators for all types that DynTypedNode supports that
9819 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009820 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00009821 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009822 if (const auto *D = ParentStack.back().get<Decl>())
9823 NodeOrVector = D;
9824 else if (const auto *S = ParentStack.back().get<Stmt>())
9825 NodeOrVector = S;
9826 else
9827 NodeOrVector =
9828 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009829 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009830 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9831 auto *Vector = new ASTContext::ParentVector(
9832 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Gabor Horvath10a837a2017-04-19 15:11:10 +00009833 delete NodeOrVector
9834 .template dyn_cast<ast_type_traits::DynTypedNode *>();
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00009835 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009836 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009837
9838 auto *Vector =
9839 NodeOrVector.template get<ASTContext::ParentVector *>();
9840 // Skip duplicates for types that have memoization data.
9841 // We must check that the type has memoization data before calling
9842 // std::find() because DynTypedNode::operator== can't compare all
9843 // types.
9844 bool Found = ParentStack.back().getMemoizationData() &&
9845 std::find(Vector->begin(), Vector->end(),
9846 ParentStack.back()) != Vector->end();
9847 if (!Found)
9848 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009849 }
9850 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009851 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009852 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009853 ParentStack.pop_back();
9854 return Result;
9855 }
9856
9857 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009858 return TraverseNode(DeclNode, DeclNode,
9859 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009860 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009861 }
9862
9863 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009864 return TraverseNode(StmtNode, StmtNode,
9865 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009866 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009867 }
9868
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009869 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009870 return TraverseNode(
9871 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9872 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9873 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009874 }
9875
9876 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9877 return TraverseNode(
9878 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009879 [&] {
9880 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9881 },
9882 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009883 }
9884
9885 ASTContext::ParentMapPointers *Parents;
9886 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009887 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009888 };
9889
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009890} // namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009891
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009892template <typename NodeTy, typename MapTy>
9893static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9894 const MapTy &Map) {
9895 auto I = Map.find(Node);
9896 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009897 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009898 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009899 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009900 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009901 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009902 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009903}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009904
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009905ASTContext::DynTypedNodeList
9906ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9907 if (!PointerParents) {
9908 // We always need to run over the whole translation unit, as
9909 // hasAncestor can escape any subtree.
9910 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9911 PointerParents.reset(Maps.first);
9912 OtherParents.reset(Maps.second);
9913 }
9914 if (Node.getNodeKind().hasPointerIdentity())
9915 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9916 return getDynNodeFromMap(Node, *OtherParents);
9917}
9918
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009919bool
9920ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9921 const ObjCMethodDecl *MethodImpl) {
9922 // No point trying to match an unavailable/deprecated mothod.
9923 if (MethodDecl->hasAttr<UnavailableAttr>()
9924 || MethodDecl->hasAttr<DeprecatedAttr>())
9925 return false;
9926 if (MethodDecl->getObjCDeclQualifier() !=
9927 MethodImpl->getObjCDeclQualifier())
9928 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009929 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009930 return false;
9931
9932 if (MethodDecl->param_size() != MethodImpl->param_size())
9933 return false;
9934
9935 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9936 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9937 EF = MethodDecl->param_end();
9938 IM != EM && IF != EF; ++IM, ++IF) {
9939 const ParmVarDecl *DeclVar = (*IF);
9940 const ParmVarDecl *ImplVar = (*IM);
9941 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9942 return false;
9943 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9944 return false;
9945 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009946
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009947 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009948}
Richard Smith053f6c62014-05-16 23:01:30 +00009949
Yaxun Liu402804b2016-12-15 08:09:08 +00009950uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +00009951 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +00009952 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +00009953 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +00009954 else
9955 AS = QT->getPointeeType().getAddressSpace();
9956
9957 return getTargetInfo().getNullPointerValue(AS);
9958}
9959
Alexander Richardson6d989432017-10-15 18:48:14 +00009960unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
9961 if (isTargetAddressSpace(AS))
9962 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +00009963 else
Alexander Richardson6d989432017-10-15 18:48:14 +00009964 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +00009965}
9966
Richard Smith053f6c62014-05-16 23:01:30 +00009967// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9968// doesn't include ASTContext.h
9969template
9970clang::LazyGenerationalUpdatePtr<
9971 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9972clang::LazyGenerationalUpdatePtr<
9973 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9974 const clang::ASTContext &Ctx, Decl *Value);