blob: eb02a61b234f15c0ffe37d034984b962591ba9c9 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerddc135e2006-11-10 06:34:16 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the ASTContext interface.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "CXXABI.h"
Nandor Licker950b70d2019-09-13 09:46:16 +000015#include "Interp/Context.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"
Eugene Zelenko7855e772018-04-03 00:11:50 +000050#include "clang/Basic/ExceptionSpecificationType.h"
Leonard Chana6779422018-08-06 16:42:37 +000051#include "clang/Basic/FixedPoint.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000052#include "clang/Basic/IdentifierTable.h"
53#include "clang/Basic/LLVM.h"
54#include "clang/Basic/LangOptions.h"
55#include "clang/Basic/Linkage.h"
56#include "clang/Basic/ObjCRuntime.h"
57#include "clang/Basic/SanitizerBlacklist.h"
58#include "clang/Basic/SourceLocation.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000059#include "clang/Basic/SourceManager.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000060#include "clang/Basic/Specifiers.h"
61#include "clang/Basic/TargetCXXABI.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000062#include "clang/Basic/TargetInfo.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000063#include "clang/Basic/XRayLists.h"
64#include "llvm/ADT/APInt.h"
65#include "llvm/ADT/APSInt.h"
66#include "llvm/ADT/ArrayRef.h"
67#include "llvm/ADT/DenseMap.h"
68#include "llvm/ADT/DenseSet.h"
69#include "llvm/ADT/FoldingSet.h"
70#include "llvm/ADT/None.h"
71#include "llvm/ADT/Optional.h"
72#include "llvm/ADT/PointerUnion.h"
73#include "llvm/ADT/STLExtras.h"
74#include "llvm/ADT/SmallPtrSet.h"
75#include "llvm/ADT/SmallVector.h"
Anders Carlssond8499822007-10-29 05:01:08 +000076#include "llvm/ADT/StringExtras.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000077#include "llvm/ADT/StringRef.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000078#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000079#include "llvm/Support/Capacity.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000080#include "llvm/Support/Casting.h"
81#include "llvm/Support/Compiler.h"
82#include "llvm/Support/ErrorHandling.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000083#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000084#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000085#include <algorithm>
86#include <cassert>
87#include <cstddef>
88#include <cstdint>
89#include <cstdlib>
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000090#include <map>
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000091#include <memory>
92#include <string>
93#include <tuple>
94#include <utility>
Anders Carlssona4267a62009-07-18 21:19:52 +000095
Chris Lattnerddc135e2006-11-10 06:34:16 +000096using namespace clang;
97
Steve Naroff0af91202007-04-27 21:51:21 +000098enum FloatingRank {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +000099 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +0000100};
101
Jan Korousf31d8df2019-08-13 18:11:44 +0000102/// \returns location that is relevant when searching for Doc comments related
103/// to \p D.
104static SourceLocation getDeclLocForCommentSearch(const Decl *D,
105 SourceManager &SourceMgr) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000106 assert(D);
107
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000108 // User can not attach documentation to implicit declarations.
109 if (D->isImplicit())
Jan Korousf31d8df2019-08-13 18:11:44 +0000110 return {};
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000111
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000112 // User can not attach documentation to implicit instantiations.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000113 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000114 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Jan Korousf31d8df2019-08-13 18:11:44 +0000115 return {};
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000116 }
117
Eugene Zelenko7855e772018-04-03 00:11:50 +0000118 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000119 if (VD->isStaticDataMember() &&
120 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Jan Korousf31d8df2019-08-13 18:11:44 +0000121 return {};
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000122 }
123
Eugene Zelenko7855e772018-04-03 00:11:50 +0000124 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000125 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Jan Korousf31d8df2019-08-13 18:11:44 +0000126 return {};
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000127 }
128
Eugene Zelenko7855e772018-04-03 00:11:50 +0000129 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000130 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
131 if (TSK == TSK_ImplicitInstantiation ||
132 TSK == TSK_Undeclared)
Jan Korousf31d8df2019-08-13 18:11:44 +0000133 return {};
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000134 }
135
Eugene Zelenko7855e772018-04-03 00:11:50 +0000136 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000137 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Jan Korousf31d8df2019-08-13 18:11:44 +0000138 return {};
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000139 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000140 if (const auto *TD = dyn_cast<TagDecl>(D)) {
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000141 // When tag declaration (but not definition!) is part of the
142 // decl-specifier-seq of some other declaration, it doesn't get comment
143 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Jan Korousf31d8df2019-08-13 18:11:44 +0000144 return {};
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000145 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000146 // TODO: handle comments for function parameters properly.
147 if (isa<ParmVarDecl>(D))
Jan Korousf31d8df2019-08-13 18:11:44 +0000148 return {};
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000149
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000150 // TODO: we could look up template parameter documentation in the template
151 // documentation.
152 if (isa<TemplateTypeParmDecl>(D) ||
153 isa<NonTypeTemplateParmDecl>(D) ||
154 isa<TemplateTemplateParmDecl>(D))
Jan Korousf31d8df2019-08-13 18:11:44 +0000155 return {};
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000156
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000157 // Find declaration location.
158 // For Objective-C declarations we generally don't expect to have multiple
159 // declarators, thus use declaration starting location as the "declaration
160 // location".
161 // For all other declarations multiple declarators are used quite frequently,
162 // so we use the location of the identifier as the "declaration location".
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000163 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000164 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000165 isa<RedeclarableTemplateDecl>(D) ||
Sam McCalla433e712019-11-13 21:30:31 +0100166 isa<ClassTemplateSpecializationDecl>(D) ||
167 // Allow association with Y across {} in `typedef struct X {} Y`.
168 isa<TypedefDecl>(D))
Jan Korousf31d8df2019-08-13 18:11:44 +0000169 return D->getBeginLoc();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000170 else {
Jan Korousf31d8df2019-08-13 18:11:44 +0000171 const SourceLocation DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000172 if (DeclLoc.isMacroID()) {
173 if (isa<TypedefDecl>(D)) {
174 // If location of the typedef name is in a macro, it is because being
175 // declared via a macro. Try using declaration's starting location as
176 // the "declaration location".
Jan Korousf31d8df2019-08-13 18:11:44 +0000177 return D->getBeginLoc();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000178 } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000179 // If location of the tag decl is inside a macro, but the spelling of
180 // the tag name comes from a macro argument, it looks like a special
181 // macro like NS_ENUM is being used to define the tag decl. In that
182 // case, adjust the source location to the expansion loc so that we can
183 // attach the comment to the tag decl.
184 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
185 TD->isCompleteDefinition())
Jan Korousf31d8df2019-08-13 18:11:44 +0000186 return SourceMgr.getExpansionLoc(DeclLoc);
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000187 }
188 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000189 return DeclLoc;
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000190 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000191
Jan Korousf31d8df2019-08-13 18:11:44 +0000192 return {};
193}
194
195RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
196 const Decl *D, const SourceLocation RepresentativeLocForDecl,
197 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000198 // If the declaration doesn't map directly to a location in a file, we
199 // can't find the comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000200 if (RepresentativeLocForDecl.isInvalid() ||
201 !RepresentativeLocForDecl.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000202 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000203
Jan Korous6644d012019-04-10 20:23:33 +0000204 // If there are no comments anywhere, we won't find anything.
Jan Korousf31d8df2019-08-13 18:11:44 +0000205 if (CommentsInTheFile.empty())
Jan Korous6644d012019-04-10 20:23:33 +0000206 return nullptr;
207
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000208 // Decompose the location for the declaration and find the beginning of the
209 // file buffer.
Jan Korousf31d8df2019-08-13 18:11:44 +0000210 const std::pair<FileID, unsigned> DeclLocDecomp =
211 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
212
213 // Slow path.
214 auto OffsetCommentBehindDecl =
215 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000216
217 // First check whether we have a trailing comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000218 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
219 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
220 if ((CommentBehindDecl->isDocumentation() ||
221 LangOpts.CommentOpts.ParseAllComments) &&
222 CommentBehindDecl->isTrailingComment() &&
223 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
224 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
225
226 // Check that Doxygen trailing comment comes after the declaration, starts
227 // on the same line and in the same file as the declaration.
228 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
229 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
230 OffsetCommentBehindDecl->first)) {
231 return CommentBehindDecl;
232 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000233 }
234 }
235
236 // The comment just after the declaration was not a trailing comment.
237 // Let's look at the previous comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000238 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000239 return nullptr;
Jan Korousf31d8df2019-08-13 18:11:44 +0000240
241 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
242 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000243
244 // Check that we actually have a non-member Doxygen comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000245 if (!(CommentBeforeDecl->isDocumentation() ||
David L. Jones13d5a872018-03-02 00:07:45 +0000246 LangOpts.CommentOpts.ParseAllComments) ||
Jan Korousf31d8df2019-08-13 18:11:44 +0000247 CommentBeforeDecl->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000248 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000249
250 // Decompose the end of the comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000251 const unsigned CommentEndOffset =
252 Comments.getCommentEndOffset(CommentBeforeDecl);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000253
254 // Get the corresponding buffer.
255 bool Invalid = false;
256 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
257 &Invalid).data();
258 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000259 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000260
261 // Extract text between the comment and declaration.
Jan Korousf31d8df2019-08-13 18:11:44 +0000262 StringRef Text(Buffer + CommentEndOffset,
263 DeclLocDecomp.second - CommentEndOffset);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000264
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000265 // There should be no other declarations or preprocessor directives between
266 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000267 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000268 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000269
Jan Korousf31d8df2019-08-13 18:11:44 +0000270 return CommentBeforeDecl;
271}
272
273RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
274 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
275
276 // If the declaration doesn't map directly to a location in a file, we
277 // can't find the comment.
278 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
279 return nullptr;
280
281 if (ExternalSource && !CommentsLoaded) {
282 ExternalSource->ReadComments();
283 CommentsLoaded = true;
284 }
285
286 if (Comments.empty())
287 return nullptr;
288
289 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
290 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
291 if (!CommentsInThisFile || CommentsInThisFile->empty())
292 return nullptr;
293
294 return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000295}
296
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000297/// If we have a 'templated' declaration for a template, adjust 'D' to
298/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000299/// If we have an implicit instantiation, adjust 'D' to refer to template.
Jan Korousf31d8df2019-08-13 18:11:44 +0000300static const Decl &adjustDeclToTemplate(const Decl &D) {
301 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000302 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000303 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Jan Korousf31d8df2019-08-13 18:11:44 +0000304 return *FTD;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000305
306 // Nothing to do if function is not an implicit instantiation.
307 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
308 return D;
309
310 // Function is an implicit instantiation of a function template?
311 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
Jan Korousf31d8df2019-08-13 18:11:44 +0000312 return *FTD;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000313
314 // Function is instantiated from a member definition of a class template?
315 if (const FunctionDecl *MemberDecl =
316 FD->getInstantiatedFromMemberFunction())
Jan Korousf31d8df2019-08-13 18:11:44 +0000317 return *MemberDecl;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000318
319 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000320 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000321 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000322 // Static data member is instantiated from a member definition of a class
323 // template?
324 if (VD->isStaticDataMember())
325 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
Jan Korousf31d8df2019-08-13 18:11:44 +0000326 return *MemberDecl;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000327
328 return D;
329 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000330 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000331 // Is this class declaration part of a class template?
332 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
Jan Korousf31d8df2019-08-13 18:11:44 +0000333 return *CTD;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000334
335 // Class is an implicit instantiation of a class template or partial
336 // specialization?
Eugene Zelenko7855e772018-04-03 00:11:50 +0000337 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000338 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
339 return D;
340 llvm::PointerUnion<ClassTemplateDecl *,
341 ClassTemplatePartialSpecializationDecl *>
342 PU = CTSD->getSpecializedTemplateOrPartial();
Jan Korousf31d8df2019-08-13 18:11:44 +0000343 return PU.is<ClassTemplateDecl *>()
344 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
345 : *static_cast<const Decl *>(
346 PU.get<ClassTemplatePartialSpecializationDecl *>());
Dmitri Gribenko90631802012-08-22 17:44:32 +0000347 }
348
349 // Class is instantiated from a member definition of a class template?
350 if (const MemberSpecializationInfo *Info =
Jan Korousf31d8df2019-08-13 18:11:44 +0000351 CRD->getMemberSpecializationInfo())
352 return *Info->getInstantiatedFrom();
Dmitri Gribenko90631802012-08-22 17:44:32 +0000353
354 return D;
355 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000356 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000357 // Enum is instantiated from a member definition of a class template?
358 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
Jan Korousf31d8df2019-08-13 18:11:44 +0000359 return *MemberDecl;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000360
361 return D;
362 }
363 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000364 return D;
365}
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000366
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000367const RawComment *ASTContext::getRawCommentForAnyRedecl(
368 const Decl *D,
369 const Decl **OriginalDecl) const {
Jan Korousf31d8df2019-08-13 18:11:44 +0000370 if (!D) {
371 if (OriginalDecl)
372 OriginalDecl = nullptr;
373 return nullptr;
374 }
Douglas Gregor35ceb272012-08-13 16:37:30 +0000375
Jan Korousf31d8df2019-08-13 18:11:44 +0000376 D = &adjustDeclToTemplate(*D);
377
378 // Any comment directly attached to D?
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000379 {
Jan Korousf31d8df2019-08-13 18:11:44 +0000380 auto DeclComment = DeclRawComments.find(D);
381 if (DeclComment != DeclRawComments.end()) {
382 if (OriginalDecl)
383 *OriginalDecl = D;
384 return DeclComment->second;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000385 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000386 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000387
Jan Korousf31d8df2019-08-13 18:11:44 +0000388 // Any comment attached to any redeclaration of D?
389 const Decl *CanonicalD = D->getCanonicalDecl();
390 if (!CanonicalD)
391 return nullptr;
392
393 {
394 auto RedeclComment = RedeclChainComments.find(CanonicalD);
395 if (RedeclComment != RedeclChainComments.end()) {
396 if (OriginalDecl)
397 *OriginalDecl = RedeclComment->second;
398 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
399 assert(CommentAtRedecl != DeclRawComments.end() &&
400 "This decl is supposed to have comment attached.");
401 return CommentAtRedecl->second;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000402 }
403 }
404
Jan Korousf31d8df2019-08-13 18:11:44 +0000405 // Any redeclarations of D that we haven't checked for comments yet?
406 // We can't use DenseMap::iterator directly since it'd get invalid.
407 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
408 auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
409 if (LookupRes != CommentlessRedeclChains.end())
410 return LookupRes->second;
411 return nullptr;
412 }();
413
414 for (const auto Redecl : D->redecls()) {
415 assert(Redecl);
416 // Skip all redeclarations that have been checked previously.
417 if (LastCheckedRedecl) {
418 if (LastCheckedRedecl == Redecl) {
419 LastCheckedRedecl = nullptr;
420 }
421 continue;
422 }
423 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
424 if (RedeclComment) {
425 cacheRawCommentForDecl(*Redecl, *RedeclComment);
426 if (OriginalDecl)
427 *OriginalDecl = Redecl;
428 return RedeclComment;
429 }
430 CommentlessRedeclChains[CanonicalD] = Redecl;
431 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000432
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000433 if (OriginalDecl)
Jan Korousf31d8df2019-08-13 18:11:44 +0000434 *OriginalDecl = nullptr;
435 return nullptr;
436}
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000437
Jan Korousf31d8df2019-08-13 18:11:44 +0000438void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
439 const RawComment &Comment) const {
440 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
441 DeclRawComments.try_emplace(&OriginalD, &Comment);
442 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
443 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
444 CommentlessRedeclChains.erase(CanonicalDecl);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000445}
446
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000447static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
448 SmallVectorImpl<const NamedDecl *> &Redeclared) {
449 const DeclContext *DC = ObjCMethod->getDeclContext();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000450 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000451 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
452 if (!ID)
453 return;
454 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000455 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000456 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000457 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000458 ObjCMethod->isInstanceMethod()))
459 Redeclared.push_back(RedeclaredMethod);
460 }
461 }
462}
463
Jan Korousf31d8df2019-08-13 18:11:44 +0000464void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
465 const Preprocessor *PP) {
466 if (Comments.empty() || Decls.empty())
467 return;
468
469 // See if there are any new comments that are not attached to a decl.
470 // The location doesn't have to be precise - we care only about the file.
471 const FileID File =
472 SourceMgr.getDecomposedLoc((*Decls.begin())->getLocation()).first;
473 auto CommentsInThisFile = Comments.getCommentsInFile(File);
474 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
475 CommentsInThisFile->rbegin()->second->isAttached())
476 return;
477
478 // There is at least one comment not attached to a decl.
479 // Maybe it should be attached to one of Decls?
480 //
481 // Note that this way we pick up not only comments that precede the
482 // declaration, but also comments that *follow* the declaration -- thanks to
483 // the lookahead in the lexer: we've consumed the semicolon and looked
484 // ahead through comments.
485
486 for (const Decl *D : Decls) {
487 assert(D);
488 if (D->isInvalidDecl())
489 continue;
490
491 D = &adjustDeclToTemplate(*D);
492
493 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
494
495 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
496 continue;
497
498 if (DeclRawComments.count(D) > 0)
499 continue;
500
501 if (RawComment *const DocComment =
502 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
503 cacheRawCommentForDecl(*D, *DocComment);
504 comments::FullComment *FC = DocComment->parse(*this, PP, D);
505 ParsedComments[D->getCanonicalDecl()] = FC;
506 }
507 }
508}
509
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000510comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
511 const Decl *D) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000512 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000513 ThisDeclInfo->CommentDecl = D;
514 ThisDeclInfo->IsFilled = false;
515 ThisDeclInfo->fill();
516 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000517 if (!ThisDeclInfo->TemplateParameters)
518 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000519 comments::FullComment *CFC =
520 new (*this) comments::FullComment(FC->getBlocks(),
521 ThisDeclInfo);
522 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000523}
524
Richard Smithb39b9d52013-05-21 05:24:00 +0000525comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
526 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000527 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000528}
529
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000530comments::FullComment *ASTContext::getCommentForDecl(
531 const Decl *D,
532 const Preprocessor *PP) const {
Jan Korousf31d8df2019-08-13 18:11:44 +0000533 if (!D || D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000534 return nullptr;
Jan Korousf31d8df2019-08-13 18:11:44 +0000535 D = &adjustDeclToTemplate(*D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000536
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000537 const Decl *Canonical = D->getCanonicalDecl();
538 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
539 ParsedComments.find(Canonical);
Fangrui Song6907ce22018-07-30 19:24:48 +0000540
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000541 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000542 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000543 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000544 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000545 return CFC;
546 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000547 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000548 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000549
Jan Korousf31d8df2019-08-13 18:11:44 +0000550 const Decl *OriginalDecl = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +0000551
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000552 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000553 if (!RC) {
554 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000555 SmallVector<const NamedDecl*, 8> Overridden;
Eugene Zelenko7855e772018-04-03 00:11:50 +0000556 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000557 if (OMD && OMD->isPropertyAccessor())
558 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
559 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
560 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000561 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000562 addRedeclaredMethods(OMD, Overridden);
563 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000564 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
565 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
566 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000567 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000568 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000569 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000570 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000571 QualType QT = TD->getUnderlyingType();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000572 if (const auto *TT = QT->getAs<TagType>())
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000573 if (const Decl *TD = TT->getDecl())
574 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000575 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000576 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000577 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000578 while (IC->getSuperClass()) {
579 IC = IC->getSuperClass();
580 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
581 return cloneFullComment(FC, D);
582 }
583 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000584 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000585 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
586 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
587 return cloneFullComment(FC, D);
588 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000589 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000590 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000591 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000592 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000593 for (const auto &I : RD->bases()) {
594 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000595 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000596 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000597 if (Ty.isNull())
598 continue;
599 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
600 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
601 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000602
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000603 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
604 return cloneFullComment(FC, D);
605 }
606 }
607 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000608 for (const auto &I : RD->vbases()) {
609 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000610 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000611 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000612 if (Ty.isNull())
613 continue;
614 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
615 if (!(VirtualBase= VirtualBase->getDefinition()))
616 continue;
617 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
618 return cloneFullComment(FC, D);
619 }
620 }
621 }
Craig Topper36250ad2014-05-12 05:36:57 +0000622 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000623 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000624
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000625 // If the RawComment was attached to other redeclaration of this Decl, we
626 // should parse the comment in context of that other Decl. This is important
627 // because comments can contain references to parameter names which can be
628 // different across redeclarations.
Jan Korousf31d8df2019-08-13 18:11:44 +0000629 if (D != OriginalDecl && OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000630 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000631
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000632 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000633 ParsedComments[Canonical] = FC;
634 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000635}
636
Fangrui Song6907ce22018-07-30 19:24:48 +0000637void
638ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000639 TemplateTemplateParmDecl *Parm) {
640 ID.AddInteger(Parm->getDepth());
641 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000642 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000643
644 TemplateParameterList *Params = Parm->getTemplateParameters();
645 ID.AddInteger(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000646 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000647 PEnd = Params->end();
648 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000649 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000650 ID.AddInteger(0);
651 ID.AddBoolean(TTP->isParameterPack());
652 continue;
653 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000654
Eugene Zelenko7855e772018-04-03 00:11:50 +0000655 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000656 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000657 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000658 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000659 if (NTTP->isExpandedParameterPack()) {
660 ID.AddBoolean(true);
661 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000662 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
663 QualType T = NTTP->getExpansionType(I);
664 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
665 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000666 } else
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000667 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000668 continue;
669 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000670
Eugene Zelenko7855e772018-04-03 00:11:50 +0000671 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000672 ID.AddInteger(2);
673 Profile(ID, TTP);
674 }
675}
676
677TemplateTemplateParmDecl *
678ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000679 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000680 // Check if we already have a canonical template template parameter.
681 llvm::FoldingSetNodeID ID;
682 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000683 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000684 CanonicalTemplateTemplateParm *Canonical
685 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
686 if (Canonical)
687 return Canonical->getParam();
Fangrui Song6907ce22018-07-30 19:24:48 +0000688
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000689 // Build a canonical template parameter list.
690 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000691 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000692 CanonParams.reserve(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000693 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000694 PEnd = Params->end();
695 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000696 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000697 CanonParams.push_back(
Fangrui Song6907ce22018-07-30 19:24:48 +0000698 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000699 SourceLocation(),
700 SourceLocation(),
701 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000702 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000703 TTP->isParameterPack()));
Eugene Zelenko7855e772018-04-03 00:11:50 +0000704 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000705 QualType T = getCanonicalType(NTTP->getType());
706 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
707 NonTypeTemplateParmDecl *Param;
708 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000709 SmallVector<QualType, 2> ExpandedTypes;
710 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000711 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
712 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
713 ExpandedTInfos.push_back(
714 getTrivialTypeSourceInfo(ExpandedTypes.back()));
715 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000716
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000717 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000718 SourceLocation(),
719 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000720 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000721 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000722 T,
723 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000724 ExpandedTypes,
725 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000726 } else {
727 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000728 SourceLocation(),
729 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000730 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000731 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000732 T,
733 NTTP->isParameterPack(),
734 TInfo);
735 }
736 CanonParams.push_back(Param);
737
738 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000739 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
740 cast<TemplateTemplateParmDecl>(*P)));
741 }
742
Saar Raz0330fba2019-10-15 18:44:06 +0000743 assert(!TTP->getTemplateParameters()->getRequiresClause() &&
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000744 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000745 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000746
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000747 TemplateTemplateParmDecl *CanonTTP
Fangrui Song6907ce22018-07-30 19:24:48 +0000748 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000749 SourceLocation(), TTP->getDepth(),
Fangrui Song6907ce22018-07-30 19:24:48 +0000750 TTP->getPosition(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000751 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000752 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000753 TemplateParameterList::Create(*this, SourceLocation(),
754 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000755 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000756 SourceLocation(),
757 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000758
759 // Get the new insert position for the node we care about.
760 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000761 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000762 (void)Canonical;
763
764 // Create the canonical template template parameter entry.
765 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
766 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
767 return CanonTTP;
768}
769
Charles Davis53c59df2010-08-16 03:33:14 +0000770CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000771 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000772
John McCall359b8852013-01-25 22:30:49 +0000773 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000774 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000775 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000776 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000777 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000778 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000779 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000780 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000781 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000782 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000783 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000784 return CreateMicrosoftCXXABI(*this);
785 }
David Blaikie8a40f702012-01-17 06:56:22 +0000786 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000787}
788
Nandor Licker950b70d2019-09-13 09:46:16 +0000789interp::Context &ASTContext::getInterpContext() {
790 if (!InterpContext) {
791 InterpContext.reset(new interp::Context(*this));
792 }
793 return *InterpContext.get();
794}
795
Alexander Richardson6d989432017-10-15 18:48:14 +0000796static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
797 const LangOptions &LOpts) {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000798 if (LOpts.FakeAddressSpaceMap) {
799 // The fake address space map must have a distinct entry for each
800 // language-specific address space.
801 static const unsigned FakeAddrSpaceMap[] = {
Yaxun Liub34ec822017-04-11 17:24:23 +0000802 0, // Default
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000803 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000804 3, // opencl_local
805 2, // opencl_constant
Yaxun Liub7318e02017-10-13 03:37:48 +0000806 0, // opencl_private
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000807 4, // opencl_generic
808 5, // cuda_device
809 6, // cuda_constant
810 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000811 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000812 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000813 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000814 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000815 }
816}
817
David Tweed31d09b02013-09-13 12:04:22 +0000818static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
819 const LangOptions &LangOpts) {
820 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000821 case LangOptions::ASMM_Target:
822 return TI.useAddressSpaceMapMangling();
823 case LangOptions::ASMM_On:
824 return true;
825 case LangOptions::ASMM_Off:
826 return false;
827 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000828 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000829}
830
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000831ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000832 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000833 Builtin::Context &builtins)
Richard Smith772e2662019-10-04 01:25:59 +0000834 : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()),
835 TemplateSpecializationTypes(this_()),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000836 DependentTemplateSpecializationTypes(this_()),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000837 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
Ilya Biryukovdf7ea712019-10-09 09:40:22 +0000838 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000839 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +0000840 LangOpts.XRayNeverInstrumentFiles,
841 LangOpts.XRayAttrListFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000842 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000843 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000844 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
845 CompCategories(this_()), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000846 TUDecl = TranslationUnitDecl::Create(*this);
Sam McCall814e7972018-11-14 10:33:30 +0000847 TraversalScope = {TUDecl};
Daniel Dunbar221fa942008-08-11 04:54:23 +0000848}
849
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000850ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000851 // Release the DenseMaps associated with DeclContext objects.
852 // FIXME: Is this the ideal solution?
853 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000854
Manuel Klimeka7328992013-06-03 13:51:33 +0000855 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000856 for (auto &Pair : Deallocations)
857 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000858
Ted Kremenek076baeb2010-06-08 23:00:58 +0000859 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000860 // because they can contain DenseMaps.
861 for (llvm::DenseMap<const ObjCContainerDecl*,
862 const ASTRecordLayout*>::iterator
863 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
864 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000865 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Douglas Gregor5b11d492010-07-25 17:53:33 +0000866 R->Destroy(*this);
867
Ted Kremenek076baeb2010-06-08 23:00:58 +0000868 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
869 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
870 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000871 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Ted Kremenek076baeb2010-06-08 23:00:58 +0000872 R->Destroy(*this);
873 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000874
Douglas Gregor561eceb2010-08-30 16:49:28 +0000875 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
876 AEnd = DeclAttrs.end();
877 A != AEnd; ++A)
878 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000879
Richard Smith423f46f2016-07-20 21:38:26 +0000880 for (const auto &Value : ModuleInitializers)
881 Value.second->~PerModuleInitializers();
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000882
883 for (APValue *Value : APValueCleanups)
884 Value->~APValue();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000885}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000886
Sam McCall814e7972018-11-14 10:33:30 +0000887class ASTContext::ParentMap {
888 /// Contains parents of a node.
889 using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
890
891 /// Maps from a node to its parents. This is used for nodes that have
892 /// pointer identity only, which are more common and we can save space by
893 /// only storing a unique pointer to them.
894 using ParentMapPointers = llvm::DenseMap<
895 const void *,
896 llvm::PointerUnion4<const Decl *, const Stmt *,
897 ast_type_traits::DynTypedNode *, ParentVector *>>;
898
899 /// Parent map for nodes without pointer identity. We store a full
900 /// DynTypedNode for all keys.
901 using ParentMapOtherNodes = llvm::DenseMap<
902 ast_type_traits::DynTypedNode,
903 llvm::PointerUnion4<const Decl *, const Stmt *,
904 ast_type_traits::DynTypedNode *, ParentVector *>>;
905
906 ParentMapPointers PointerParents;
907 ParentMapOtherNodes OtherParents;
908 class ASTVisitor;
909
910 static ast_type_traits::DynTypedNode
911 getSingleDynTypedNodeFromParentMap(ParentMapPointers::mapped_type U) {
912 if (const auto *D = U.dyn_cast<const Decl *>())
913 return ast_type_traits::DynTypedNode::create(*D);
914 if (const auto *S = U.dyn_cast<const Stmt *>())
915 return ast_type_traits::DynTypedNode::create(*S);
916 return *U.get<ast_type_traits::DynTypedNode *>();
917 }
918
919 template <typename NodeTy, typename MapTy>
920 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
921 const MapTy &Map) {
922 auto I = Map.find(Node);
923 if (I == Map.end()) {
924 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
925 }
926 if (const auto *V = I->second.template dyn_cast<ParentVector *>()) {
927 return llvm::makeArrayRef(*V);
928 }
929 return getSingleDynTypedNodeFromParentMap(I->second);
930 }
931
932public:
933 ParentMap(ASTContext &Ctx);
934 ~ParentMap() {
935 for (const auto &Entry : PointerParents) {
936 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
937 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
938 } else if (Entry.second.is<ParentVector *>()) {
939 delete Entry.second.get<ParentVector *>();
940 }
941 }
942 for (const auto &Entry : OtherParents) {
943 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
944 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
945 } else if (Entry.second.is<ParentVector *>()) {
946 delete Entry.second.get<ParentVector *>();
947 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000948 }
949 }
Sam McCall814e7972018-11-14 10:33:30 +0000950
951 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node) {
952 if (Node.getNodeKind().hasPointerIdentity())
953 return getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
954 return getDynNodeFromMap(Node, OtherParents);
Manuel Klimek95403e62014-05-21 13:28:59 +0000955 }
Sam McCall814e7972018-11-14 10:33:30 +0000956};
957
958void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
959 TraversalScope = TopLevelDecls;
960 Parents.reset();
Manuel Klimek95403e62014-05-21 13:28:59 +0000961}
962
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000963void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000964 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000965}
966
Mike Stump11289f42009-09-09 15:08:12 +0000967void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000968ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000969 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000970}
971
Chris Lattner4eb445d2007-01-26 01:27:23 +0000972void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000973 llvm::errs() << "\n*** AST Context Stats:\n";
974 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000975
Douglas Gregora30d0462009-05-26 14:40:08 +0000976 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000977#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000978#define ABSTRACT_TYPE(Name, Parent)
John McCall36b12a82019-10-02 06:35:23 +0000979#include "clang/AST/TypeNodes.inc"
Douglas Gregora30d0462009-05-26 14:40:08 +0000980 0 // Extra
981 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000982
Chris Lattner4eb445d2007-01-26 01:27:23 +0000983 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
984 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000985 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000986 }
987
Douglas Gregora30d0462009-05-26 14:40:08 +0000988 unsigned Idx = 0;
989 unsigned TotalBytes = 0;
990#define TYPE(Name, Parent) \
991 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000992 llvm::errs() << " " << counts[Idx] << " " << #Name \
Bruno Ricci58e03222018-08-06 15:17:32 +0000993 << " types, " << sizeof(Name##Type) << " each " \
994 << "(" << counts[Idx] * sizeof(Name##Type) \
995 << " bytes)\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000996 TotalBytes += counts[Idx] * sizeof(Name##Type); \
997 ++Idx;
998#define ABSTRACT_TYPE(Name, Parent)
John McCall36b12a82019-10-02 06:35:23 +0000999#include "clang/AST/TypeNodes.inc"
Mike Stump11289f42009-09-09 15:08:12 +00001000
Chandler Carruth3c147a72011-07-04 05:32:14 +00001001 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1002
Douglas Gregor7454c562010-07-02 20:37:36 +00001003 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +00001004 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1005 << NumImplicitDefaultConstructors
1006 << " implicit default constructors created\n";
1007 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1008 << NumImplicitCopyConstructors
1009 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +00001010 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +00001011 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1012 << NumImplicitMoveConstructors
1013 << " implicit move constructors created\n";
1014 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1015 << NumImplicitCopyAssignmentOperators
1016 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +00001017 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +00001018 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1019 << NumImplicitMoveAssignmentOperators
1020 << " implicit move assignment operators created\n";
1021 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1022 << NumImplicitDestructors
1023 << " implicit destructors created\n";
1024
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +00001025 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +00001026 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001027 ExternalSource->PrintStats();
1028 }
Chandler Carruth3c147a72011-07-04 05:32:14 +00001029
Douglas Gregor5b11d492010-07-25 17:53:33 +00001030 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +00001031}
1032
Richard Smith42413142015-05-15 20:05:43 +00001033void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1034 bool NotifyListeners) {
1035 if (NotifyListeners)
1036 if (auto *Listener = getASTMutationListener())
1037 Listener->RedefinedHiddenDefinition(ND, M);
1038
Richard Smith13897eb2018-09-12 23:37:00 +00001039 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
Richard Smith42413142015-05-15 20:05:43 +00001040}
1041
1042void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
Richard Smith20fbdb32018-09-12 02:13:46 +00001043 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
Richard Smith42413142015-05-15 20:05:43 +00001044 if (It == MergedDefModules.end())
1045 return;
1046
Benjamin Kramera72a70a2016-10-17 13:00:44 +00001047 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +00001048 llvm::DenseSet<Module*> Found;
1049 for (Module *&M : Merged)
1050 if (!Found.insert(M).second)
1051 M = nullptr;
1052 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1053}
1054
Richard Smithdc1f0422016-07-20 19:10:16 +00001055void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1056 if (LazyInitializers.empty())
1057 return;
1058
1059 auto *Source = Ctx.getExternalSource();
1060 assert(Source && "lazy initializers but no external source");
1061
1062 auto LazyInits = std::move(LazyInitializers);
1063 LazyInitializers.clear();
1064
1065 for (auto ID : LazyInits)
1066 Initializers.push_back(Source->GetExternalDecl(ID));
1067
1068 assert(LazyInitializers.empty() &&
1069 "GetExternalDecl for lazy module initializer added more inits");
1070}
1071
1072void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1073 // One special case: if we add a module initializer that imports another
1074 // module, and that module's only initializer is an ImportDecl, simplify.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001075 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001076 auto It = ModuleInitializers.find(ID->getImportedModule());
1077
1078 // Maybe the ImportDecl does nothing at all. (Common case.)
1079 if (It == ModuleInitializers.end())
1080 return;
1081
1082 // Maybe the ImportDecl only imports another ImportDecl.
1083 auto &Imported = *It->second;
1084 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1085 Imported.resolve(*this);
1086 auto *OnlyDecl = Imported.Initializers.front();
1087 if (isa<ImportDecl>(OnlyDecl))
1088 D = OnlyDecl;
1089 }
1090 }
1091
1092 auto *&Inits = ModuleInitializers[M];
1093 if (!Inits)
1094 Inits = new (*this) PerModuleInitializers;
1095 Inits->Initializers.push_back(D);
1096}
1097
1098void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1099 auto *&Inits = ModuleInitializers[M];
1100 if (!Inits)
1101 Inits = new (*this) PerModuleInitializers;
1102 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1103 IDs.begin(), IDs.end());
1104}
1105
Eugene Zelenko7855e772018-04-03 00:11:50 +00001106ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001107 auto It = ModuleInitializers.find(M);
Fangrui Song6907ce22018-07-30 19:24:48 +00001108 if (It == ModuleInitializers.end())
Richard Smithdc1f0422016-07-20 19:10:16 +00001109 return None;
1110
1111 auto *Inits = It->second;
1112 Inits->resolve(*this);
1113 return Inits->Initializers;
1114}
1115
Richard Smithf19e1272015-03-07 00:04:49 +00001116ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1117 if (!ExternCContext)
1118 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1119
1120 return ExternCContext;
1121}
1122
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001123BuiltinTemplateDecl *
1124ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1125 const IdentifierInfo *II) const {
1126 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1127 BuiltinTemplate->setImplicit();
1128 TUDecl->addDecl(BuiltinTemplate);
1129
1130 return BuiltinTemplate;
1131}
1132
1133BuiltinTemplateDecl *
1134ASTContext::getMakeIntegerSeqDecl() const {
1135 if (!MakeIntegerSeqDecl)
1136 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1137 getMakeIntegerSeqName());
1138 return MakeIntegerSeqDecl;
1139}
1140
Eric Fiselier6ad68552016-07-01 01:24:09 +00001141BuiltinTemplateDecl *
1142ASTContext::getTypePackElementDecl() const {
1143 if (!TypePackElementDecl)
1144 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1145 getTypePackElementName());
1146 return TypePackElementDecl;
1147}
1148
Alp Toker2dea15b2013-12-17 01:22:38 +00001149RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1150 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001151 SourceLocation Loc;
1152 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001153 if (getLangOpts().CPlusPlus)
1154 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1155 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001156 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001157 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1158 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001159 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001160 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1161 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001162 return NewDecl;
1163}
1164
1165TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1166 StringRef Name) const {
1167 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1168 TypedefDecl *NewDecl = TypedefDecl::Create(
1169 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1170 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1171 NewDecl->setImplicit();
1172 return NewDecl;
1173}
1174
Douglas Gregor801c99d2011-08-12 06:49:56 +00001175TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001176 if (!Int128Decl)
1177 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001178 return Int128Decl;
1179}
1180
1181TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001182 if (!UInt128Decl)
1183 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001184 return UInt128Decl;
1185}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001186
John McCall48f2d582009-10-23 23:03:21 +00001187void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001188 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001189 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001190 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001191}
1192
Artem Belevichb5bc9232015-09-22 17:23:22 +00001193void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1194 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001195 assert((!this->Target || this->Target == &Target) &&
1196 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001197 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001198
Douglas Gregore8bbc122011-09-02 00:18:52 +00001199 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001200 this->AuxTarget = AuxTarget;
1201
Douglas Gregore8bbc122011-09-02 00:18:52 +00001202 ABI.reset(createCXXABI(Target));
1203 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001204 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Fangrui Song6907ce22018-07-30 19:24:48 +00001205
Chris Lattner970e54e2006-11-12 00:37:36 +00001206 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001207 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001208
Chris Lattner970e54e2006-11-12 00:37:36 +00001209 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001210 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001211 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001212 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001213 InitBuiltinType(CharTy, BuiltinType::Char_S);
1214 else
1215 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001216 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001217 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1218 InitBuiltinType(ShortTy, BuiltinType::Short);
1219 InitBuiltinType(IntTy, BuiltinType::Int);
1220 InitBuiltinType(LongTy, BuiltinType::Long);
1221 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001222
Chris Lattner970e54e2006-11-12 00:37:36 +00001223 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001224 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1225 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1226 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1227 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1228 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001229
Chris Lattner970e54e2006-11-12 00:37:36 +00001230 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001231 InitBuiltinType(FloatTy, BuiltinType::Float);
1232 InitBuiltinType(DoubleTy, BuiltinType::Double);
1233 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001234
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001235 // GNU extension, __float128 for IEEE quadruple precision
1236 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1237
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001238 // C11 extension ISO/IEC TS 18661-3
1239 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1240
Leonard Chanf921d852018-06-04 16:07:52 +00001241 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
Leonard Chanab80f3c2018-06-14 14:53:51 +00001242 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1243 InitBuiltinType(AccumTy, BuiltinType::Accum);
1244 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1245 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1246 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1247 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1248 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1249 InitBuiltinType(FractTy, BuiltinType::Fract);
1250 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1251 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1252 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1253 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1254 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1255 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1256 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1257 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1258 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1259 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1260 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1261 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1262 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1263 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1264 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1265 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
Leonard Chanf921d852018-06-04 16:07:52 +00001266
Chris Lattnerf122cef2009-04-30 02:43:43 +00001267 // GNU extension, 128-bit integers.
1268 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1269 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1270
Hans Wennborg0d81e012013-05-10 10:08:40 +00001271 // C++ 3.9.1p5
1272 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1273 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1274 else // -fshort-wchar makes wchar_t be unsigned.
1275 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1276 if (LangOpts.CPlusPlus && LangOpts.WChar)
1277 WideCharTy = WCharTy;
1278 else {
1279 // C99 (or C++ using -fno-wchar).
1280 WideCharTy = getFromTargetType(Target.getWCharType());
1281 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001282
James Molloy36365542012-05-04 10:55:22 +00001283 WIntTy = getFromTargetType(Target.getWIntType());
1284
Richard Smith3a8244d2018-05-01 05:02:45 +00001285 // C++20 (proposed)
1286 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1287
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001288 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1289 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1290 else // C99
1291 Char16Ty = getFromTargetType(Target.getChar16Type());
1292
1293 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1294 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1295 else // C99
1296 Char32Ty = getFromTargetType(Target.getChar32Type());
1297
Douglas Gregor4619e432008-12-05 23:32:09 +00001298 // Placeholder type for type-dependent expressions whose type is
1299 // completely unknown. No code should ever check a type against
1300 // DependentTy and users should never see it; however, it is here to
1301 // help diagnose failures to properly check for type-dependent
1302 // expressions.
1303 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001304
John McCall36e7fe32010-10-12 00:20:44 +00001305 // Placeholder type for functions.
1306 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1307
John McCall0009fcc2011-04-26 20:42:42 +00001308 // Placeholder type for bound members.
1309 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1310
John McCall526ab472011-10-25 17:37:35 +00001311 // Placeholder type for pseudo-objects.
1312 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1313
John McCall31996342011-04-07 08:22:57 +00001314 // "any" type; useful for debugger-like clients.
1315 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1316
John McCall8a6b59a2011-10-17 18:09:15 +00001317 // Placeholder type for unbridged ARC casts.
1318 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1319
Eli Friedman34866c72012-08-31 00:14:07 +00001320 // Placeholder type for builtin functions.
1321 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1322
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001323 // Placeholder type for OMP array sections.
1324 if (LangOpts.OpenMP)
1325 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1326
Chris Lattner970e54e2006-11-12 00:37:36 +00001327 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001328 FloatComplexTy = getComplexType(FloatTy);
1329 DoubleComplexTy = getComplexType(DoubleTy);
1330 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001331 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001332
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001333 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001334 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1335 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001336 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001337
Alexey Bader954ba212016-04-08 13:40:33 +00001338 if (LangOpts.OpenCL) {
1339#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1340 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001341#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001342
Guy Benyei61054192013-02-07 10:55:47 +00001343 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001344 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001345 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1346 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001347 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001348
1349#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1350 InitBuiltinType(Id##Ty, BuiltinType::Id);
1351#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001352 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001353
Richard Sandifordeb485fb2019-08-09 08:52:54 +00001354 if (Target.hasAArch64SVETypes()) {
1355#define SVE_TYPE(Name, Id, SingletonId) \
1356 InitBuiltinType(SingletonId, BuiltinType::Id);
1357#include "clang/Basic/AArch64SVEACLETypes.def"
1358 }
1359
Ted Kremeneke65b0862012-03-06 20:05:56 +00001360 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001361 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1362 SignedCharTy : BoolTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001363
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001364 ObjCConstantStringType = QualType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001365
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001366 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001367
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001368 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001369 if (LangOpts.OpenCLVersion >= 200) {
1370 auto Q = VoidTy.getQualifiers();
1371 Q.setAddressSpace(LangAS::opencl_generic);
1372 VoidPtrTy = getPointerType(getCanonicalType(
1373 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1374 } else {
1375 VoidPtrTy = getPointerType(VoidTy);
1376 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001377
1378 // nullptr type (C++0x 2.14.7)
1379 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001380
1381 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1382 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001383
1384 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001385 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001386}
1387
David Blaikie9c902b52011-09-25 23:23:43 +00001388DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001389 return SourceMgr.getDiagnostics();
1390}
1391
Douglas Gregor561eceb2010-08-30 16:49:28 +00001392AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1393 AttrVec *&Result = DeclAttrs[D];
1394 if (!Result) {
1395 void *Mem = Allocate(sizeof(AttrVec));
1396 Result = new (Mem) AttrVec;
1397 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001398
Douglas Gregor561eceb2010-08-30 16:49:28 +00001399 return *Result;
1400}
1401
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001402/// Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001403void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001404 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1405 if (Pos != DeclAttrs.end()) {
1406 Pos->second->~AttrVec();
1407 DeclAttrs.erase(Pos);
1408 }
1409}
1410
Larisse Voufo39a1e502013-08-06 01:03:05 +00001411// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001412MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001413ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001414 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001415 return getTemplateOrSpecializationInfo(Var)
1416 .dyn_cast<MemberSpecializationInfo *>();
1417}
1418
1419ASTContext::TemplateOrSpecializationInfo
1420ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1421 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1422 TemplateOrInstantiation.find(Var);
1423 if (Pos == TemplateOrInstantiation.end())
Eugene Zelenko7855e772018-04-03 00:11:50 +00001424 return {};
Mike Stump11289f42009-09-09 15:08:12 +00001425
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001426 return Pos->second;
1427}
1428
Mike Stump11289f42009-09-09 15:08:12 +00001429void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001430ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001431 TemplateSpecializationKind TSK,
1432 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001433 assert(Inst->isStaticDataMember() && "Not a static data member");
1434 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001435 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1436 Tmpl, TSK, PointOfInstantiation));
1437}
1438
1439void
1440ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1441 TemplateOrSpecializationInfo TSI) {
1442 assert(!TemplateOrInstantiation[Inst] &&
1443 "Already noted what the variable was instantiated from");
1444 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001445}
1446
John McCalle61f2ba2009-11-18 02:36:19 +00001447NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001448ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1449 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001450 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001451 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001452
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001453 return Pos->second;
1454}
1455
1456void
Richard Smithd8a9e372016-12-18 21:39:37 +00001457ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001458 assert((isa<UsingDecl>(Pattern) ||
1459 isa<UnresolvedUsingValueDecl>(Pattern) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001460 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
John McCallb96ec562009-12-04 22:46:56 +00001461 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001462 assert((isa<UsingDecl>(Inst) ||
1463 isa<UnresolvedUsingValueDecl>(Inst) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001464 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
Richard Smithd8a9e372016-12-18 21:39:37 +00001465 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001466 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1467 InstantiatedFromUsingDecl[Inst] = Pattern;
1468}
1469
1470UsingShadowDecl *
1471ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1472 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1473 = InstantiatedFromUsingShadowDecl.find(Inst);
1474 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001475 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001476
1477 return Pos->second;
1478}
1479
1480void
1481ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1482 UsingShadowDecl *Pattern) {
1483 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1484 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001485}
1486
Anders Carlsson5da84842009-09-01 04:26:58 +00001487FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1488 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1489 = InstantiatedFromUnnamedFieldDecl.find(Field);
1490 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001491 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001492
Anders Carlsson5da84842009-09-01 04:26:58 +00001493 return Pos->second;
1494}
1495
1496void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1497 FieldDecl *Tmpl) {
1498 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1499 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1500 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1501 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001502
Anders Carlsson5da84842009-09-01 04:26:58 +00001503 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1504}
1505
Douglas Gregor832940b2010-03-02 23:58:15 +00001506ASTContext::overridden_cxx_method_iterator
1507ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001508 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001509}
1510
1511ASTContext::overridden_cxx_method_iterator
1512ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001513 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001514}
1515
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001516unsigned
1517ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001518 auto Range = overridden_methods(Method);
1519 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001520}
1521
Clement Courbet6ecaec82016-07-05 07:49:31 +00001522ASTContext::overridden_method_range
1523ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001524 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1525 OverriddenMethods.find(Method->getCanonicalDecl());
1526 if (Pos == OverriddenMethods.end())
1527 return overridden_method_range(nullptr, nullptr);
1528 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001529}
1530
Fangrui Song6907ce22018-07-30 19:24:48 +00001531void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
Douglas Gregor832940b2010-03-02 23:58:15 +00001532 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001533 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001534 OverriddenMethods[Method].push_back(Overridden);
1535}
1536
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001537void ASTContext::getOverriddenMethods(
1538 const NamedDecl *D,
1539 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001540 assert(D);
1541
Eugene Zelenko7855e772018-04-03 00:11:50 +00001542 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001543 Overridden.append(overridden_methods_begin(CXXMethod),
1544 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001545 return;
1546 }
1547
Eugene Zelenko7855e772018-04-03 00:11:50 +00001548 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001549 if (!Method)
1550 return;
1551
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001552 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1553 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001554 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001555}
1556
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001557void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1558 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1559 assert(!Import->isFromASTFile() && "Non-local import declaration");
1560 if (!FirstLocalImport) {
1561 FirstLocalImport = Import;
1562 LastLocalImport = Import;
1563 return;
1564 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001565
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001566 LastLocalImport->NextLocalImport = Import;
1567 LastLocalImport = Import;
1568}
1569
Chris Lattner53cfe802007-07-18 17:52:12 +00001570//===----------------------------------------------------------------------===//
1571// Type Sizing and Analysis
1572//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001573
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001574/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1575/// scalar floating point type.
1576const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
Simon Pilgrim9588ae72019-10-03 21:47:42 +00001577 switch (T->castAs<BuiltinType>()->getKind()) {
1578 default:
1579 llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001580 case BuiltinType::Float16:
1581 case BuiltinType::Half:
1582 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001583 case BuiltinType::Float: return Target->getFloatFormat();
1584 case BuiltinType::Double: return Target->getDoubleFormat();
Alexey Bataeve509af32019-07-09 14:09:53 +00001585 case BuiltinType::LongDouble:
Fangrui Song3fbd8fd2019-07-09 19:36:22 +00001586 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
Alexey Bataeve509af32019-07-09 14:09:53 +00001587 return AuxTarget->getLongDoubleFormat();
1588 return Target->getLongDoubleFormat();
1589 case BuiltinType::Float128:
Fangrui Song3fbd8fd2019-07-09 19:36:22 +00001590 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
Alexey Bataeve509af32019-07-09 14:09:53 +00001591 return AuxTarget->getFloat128Format();
1592 return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001593 }
1594}
1595
Rafael Espindola71eccb32013-08-08 19:53:46 +00001596CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001597 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001598
John McCall94268702010-10-08 18:24:19 +00001599 bool UseAlignAttrOnly = false;
1600 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1601 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001602
John McCall94268702010-10-08 18:24:19 +00001603 // __attribute__((aligned)) can increase or decrease alignment
1604 // *except* on a struct or struct member, where it only increases
1605 // alignment unless 'packed' is also specified.
1606 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001607 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001608 // ignore that possibility; Sema should diagnose it.
1609 if (isa<FieldDecl>(D)) {
1610 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1611 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1612 } else {
1613 UseAlignAttrOnly = true;
1614 }
1615 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001616 else if (isa<FieldDecl>(D))
Fangrui Song6907ce22018-07-30 19:24:48 +00001617 UseAlignAttrOnly =
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001618 D->hasAttr<PackedAttr>() ||
1619 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001620
John McCall4e819612011-01-20 07:57:12 +00001621 // If we're using the align attribute only, just ignore everything
1622 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001623 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001624 // do nothing
Eugene Zelenko7855e772018-04-03 00:11:50 +00001625 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001626 QualType T = VD->getType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001627 if (const auto *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001628 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001629 T = RT->getPointeeType();
1630 else
1631 T = getPointerType(RT->getPointeeType());
1632 }
Richard Smithf6d70302014-06-10 23:34:28 +00001633 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001634 if (T->isFunctionType())
1635 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1636 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001637 // Adjust alignments of declarations with array type by the
1638 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001639 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001640 unsigned MinWidth = Target->getLargeArrayMinWidth();
1641 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001642 if (isa<VariableArrayType>(arrayType))
1643 Align = std::max(Align, Target->getLargeArrayAlign());
1644 else if (isa<ConstantArrayType>(arrayType) &&
1645 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1646 Align = std::max(Align, Target->getLargeArrayAlign());
1647 }
John McCall33ddac02011-01-19 10:06:00 +00001648 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001649 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001650 if (BaseT.getQualifiers().hasUnaligned())
1651 Align = Target->getCharWidth();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001652 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Tom Tanb7c6d952019-05-02 00:38:14 +00001653 if (VD->hasGlobalStorage() && !ForAlignof) {
1654 uint64_t TypeSize = getTypeSize(T.getTypePtr());
1655 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1656 }
Ulrich Weigandfa806422013-05-06 16:23:57 +00001657 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001658 }
John McCall4e819612011-01-20 07:57:12 +00001659
1660 // Fields can be subject to extra alignment constraints, like if
1661 // the field is packed, the struct is packed, or the struct has a
1662 // a max-field-alignment constraint (#pragma pack). So calculate
1663 // the actual alignment of the field within the struct, and then
1664 // (as we're expected to) constrain that by the alignment of the type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001665 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001666 const RecordDecl *Parent = Field->getParent();
1667 // We can only produce a sensible answer if the record is valid.
1668 if (!Parent->isInvalidDecl()) {
1669 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001670
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001671 // Start with the record's overall alignment.
1672 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001673
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001674 // Use the GCD of that and the offset within the record.
1675 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1676 if (Offset > 0) {
1677 // Alignment is always a power of 2, so the GCD will be a power of 2,
1678 // which means we get to do this crazy thing instead of Euclid's.
1679 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1680 if (LowBitOfOffset < FieldAlign)
1681 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1682 }
1683
1684 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001685 }
Charles Davis3fc51072010-02-23 04:52:00 +00001686 }
Chris Lattner68061312009-01-24 21:53:27 +00001687 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001688
Ken Dyckcc56c542011-01-15 18:38:59 +00001689 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001690}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001691
John McCallf1249922012-08-21 04:10:00 +00001692// getTypeInfoDataSizeInChars - Return the size of a type, in
1693// chars. If the type is a record, its data size is returned. This is
1694// the size of the memcpy that's performed when assigning this type
1695// using a trivial copy/move assignment operator.
1696std::pair<CharUnits, CharUnits>
1697ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1698 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1699
1700 // In C++, objects can sometimes be allocated into the tail padding
1701 // of a base-class subobject. We decide whether that's possible
1702 // during class layout, so here we can just trust the layout results.
1703 if (getLangOpts().CPlusPlus) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001704 if (const auto *RT = T->getAs<RecordType>()) {
John McCallf1249922012-08-21 04:10:00 +00001705 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1706 sizeAndAlign.first = layout.getDataSize();
1707 }
1708 }
1709
1710 return sizeAndAlign;
1711}
1712
Richard Trieu04d2d942013-05-14 21:59:17 +00001713/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1714/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1715std::pair<CharUnits, CharUnits>
1716static getConstantArrayInfoInChars(const ASTContext &Context,
1717 const ConstantArrayType *CAT) {
1718 std::pair<CharUnits, CharUnits> EltInfo =
1719 Context.getTypeInfoInChars(CAT->getElementType());
1720 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001721 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1722 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001723 "Overflow in array type char size evaluation");
1724 uint64_t Width = EltInfo.first.getQuantity() * Size;
1725 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001726 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1727 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001728 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001729 return std::make_pair(CharUnits::fromQuantity(Width),
1730 CharUnits::fromQuantity(Align));
1731}
1732
John McCall87fe5d52010-05-20 01:18:31 +00001733std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001734ASTContext::getTypeInfoInChars(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001735 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
Richard Trieu04d2d942013-05-14 21:59:17 +00001736 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001737 TypeInfo Info = getTypeInfo(T);
1738 return std::make_pair(toCharUnitsFromBits(Info.Width),
1739 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001740}
1741
1742std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001743ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001744 return getTypeInfoInChars(T.getTypePtr());
1745}
1746
David Majnemer34b57492014-07-30 01:30:47 +00001747bool ASTContext::isAlignmentRequired(const Type *T) const {
1748 return getTypeInfo(T).AlignIsRequired;
1749}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001750
David Majnemer34b57492014-07-30 01:30:47 +00001751bool ASTContext::isAlignmentRequired(QualType T) const {
1752 return isAlignmentRequired(T.getTypePtr());
1753}
1754
Richard Smithb2f0f052016-10-10 18:54:32 +00001755unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1756 // An alignment on a typedef overrides anything else.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001757 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001758 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1759 return Align;
1760
1761 // If we have an (array of) complete type, we're done.
1762 T = getBaseElementType(T);
1763 if (!T->isIncompleteType())
1764 return getTypeAlign(T);
1765
1766 // If we had an array type, its element type might be a typedef
1767 // type with an alignment attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001768 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001769 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1770 return Align;
1771
1772 // Otherwise, see if the declaration of the type had an attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001773 if (const auto *TT = T->getAs<TagType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001774 return TT->getDecl()->getMaxAlignment();
1775
1776 return 0;
1777}
1778
David Majnemer34b57492014-07-30 01:30:47 +00001779TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001780 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1781 if (I != MemoizedTypeInfo.end())
1782 return I->second;
1783
1784 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1785 TypeInfo TI = getTypeInfoImpl(T);
1786 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001787 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001788}
1789
1790/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1791/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001792///
1793/// FIXME: Pointers into different addr spaces could have different sizes and
1794/// alignment requirements: getPointerInfo should take an AddrSpace, this
1795/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001796TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1797 uint64_t Width = 0;
1798 unsigned Align = 8;
1799 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001800 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001801 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001802#define TYPE(Class, Base)
1803#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001804#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001805#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001806#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1807 case Type::Class: \
1808 assert(!T->isDependentType() && "should not see dependent types here"); \
1809 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
John McCall36b12a82019-10-02 06:35:23 +00001810#include "clang/AST/TypeNodes.inc"
John McCall15547bb2011-06-28 16:49:23 +00001811 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001812
Chris Lattner355332d2007-07-13 22:27:08 +00001813 case Type::FunctionNoProto:
1814 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001815 // GCC extension: alignof(function) = 32 bits
1816 Width = 0;
1817 Align = 32;
1818 break;
1819
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001820 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001821 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001822 Width = 0;
1823 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1824 break;
1825
Steve Naroff5c131802007-08-30 01:06:46 +00001826 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001827 const auto *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001828
David Majnemer34b57492014-07-30 01:30:47 +00001829 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001830 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001831 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001832 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001833 Width = EltInfo.Width * Size;
1834 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001835 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1836 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001837 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001838 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001839 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001840 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001841 case Type::Vector: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001842 const auto *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001843 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1844 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001845 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001846 // If the alignment is not a power of 2, round up to the next power of 2.
1847 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001848 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001849 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001850 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001851 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001852 // Adjust the alignment based on the target max.
1853 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1854 if (TargetVectorAlign && TargetVectorAlign < Align)
1855 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001856 break;
1857 }
Chris Lattner647fb222007-07-18 18:26:58 +00001858
Chris Lattner7570e9c2008-03-08 08:52:55 +00001859 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001860 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001861 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001862 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001863 // GCC extension: alignof(void) = 8 bits.
1864 Width = 0;
1865 Align = 8;
1866 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001867 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001868 Width = Target->getBoolWidth();
1869 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001870 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001871 case BuiltinType::Char_S:
1872 case BuiltinType::Char_U:
1873 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001874 case BuiltinType::SChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00001875 case BuiltinType::Char8:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001876 Width = Target->getCharWidth();
1877 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001878 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001879 case BuiltinType::WChar_S:
1880 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001881 Width = Target->getWCharWidth();
1882 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001883 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001884 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001885 Width = Target->getChar16Width();
1886 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001887 break;
1888 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001889 Width = Target->getChar32Width();
1890 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001891 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001892 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001893 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001894 Width = Target->getShortWidth();
1895 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001896 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001897 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001898 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001899 Width = Target->getIntWidth();
1900 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001901 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001902 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001903 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001904 Width = Target->getLongWidth();
1905 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001906 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001907 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001908 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001909 Width = Target->getLongLongWidth();
1910 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001911 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001912 case BuiltinType::Int128:
1913 case BuiltinType::UInt128:
1914 Width = 128;
1915 Align = 128; // int128_t is 128-bit aligned on all targets.
1916 break;
Leonard Chanf921d852018-06-04 16:07:52 +00001917 case BuiltinType::ShortAccum:
1918 case BuiltinType::UShortAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001919 case BuiltinType::SatShortAccum:
1920 case BuiltinType::SatUShortAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001921 Width = Target->getShortAccumWidth();
1922 Align = Target->getShortAccumAlign();
1923 break;
1924 case BuiltinType::Accum:
1925 case BuiltinType::UAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001926 case BuiltinType::SatAccum:
1927 case BuiltinType::SatUAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001928 Width = Target->getAccumWidth();
1929 Align = Target->getAccumAlign();
1930 break;
1931 case BuiltinType::LongAccum:
1932 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001933 case BuiltinType::SatLongAccum:
1934 case BuiltinType::SatULongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001935 Width = Target->getLongAccumWidth();
1936 Align = Target->getLongAccumAlign();
1937 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00001938 case BuiltinType::ShortFract:
1939 case BuiltinType::UShortFract:
1940 case BuiltinType::SatShortFract:
1941 case BuiltinType::SatUShortFract:
1942 Width = Target->getShortFractWidth();
1943 Align = Target->getShortFractAlign();
1944 break;
1945 case BuiltinType::Fract:
1946 case BuiltinType::UFract:
1947 case BuiltinType::SatFract:
1948 case BuiltinType::SatUFract:
1949 Width = Target->getFractWidth();
1950 Align = Target->getFractAlign();
1951 break;
1952 case BuiltinType::LongFract:
1953 case BuiltinType::ULongFract:
1954 case BuiltinType::SatLongFract:
1955 case BuiltinType::SatULongFract:
1956 Width = Target->getLongFractWidth();
1957 Align = Target->getLongFractAlign();
1958 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001959 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001960 case BuiltinType::Half:
Alexey Bataev123ad192019-02-27 20:29:45 +00001961 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
1962 !getLangOpts().OpenMPIsDevice) {
1963 Width = Target->getHalfWidth();
1964 Align = Target->getHalfAlign();
1965 } else {
1966 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1967 "Expected OpenMP device compilation.");
1968 Width = AuxTarget->getHalfWidth();
1969 Align = AuxTarget->getHalfAlign();
1970 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001971 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001972 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001973 Width = Target->getFloatWidth();
1974 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001975 break;
1976 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001977 Width = Target->getDoubleWidth();
1978 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001979 break;
1980 case BuiltinType::LongDouble:
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001981 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1982 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
1983 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
1984 Width = AuxTarget->getLongDoubleWidth();
1985 Align = AuxTarget->getLongDoubleAlign();
1986 } else {
1987 Width = Target->getLongDoubleWidth();
1988 Align = Target->getLongDoubleAlign();
1989 }
Chris Lattner6a4f7452007-12-19 19:23:28 +00001990 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001991 case BuiltinType::Float128:
Alexey Bataev123ad192019-02-27 20:29:45 +00001992 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
1993 !getLangOpts().OpenMPIsDevice) {
1994 Width = Target->getFloat128Width();
1995 Align = Target->getFloat128Align();
1996 } else {
1997 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1998 "Expected OpenMP device compilation.");
1999 Width = AuxTarget->getFloat128Width();
2000 Align = AuxTarget->getFloat128Align();
2001 }
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002002 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002003 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00002004 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
2005 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00002006 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00002007 case BuiltinType::ObjCId:
2008 case BuiltinType::ObjCClass:
2009 case BuiltinType::ObjCSel:
Fangrui Song6907ce22018-07-30 19:24:48 +00002010 Width = Target->getPointerWidth(0);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002011 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00002012 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002013 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002014 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002015 case BuiltinType::OCLClkEvent:
2016 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002017 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00002018#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2019 case BuiltinType::Id:
2020#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00002021#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2022 case BuiltinType::Id:
2023#include "clang/Basic/OpenCLExtensionTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00002024 AS = getTargetAddressSpace(
2025 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002026 Width = Target->getPointerWidth(AS);
2027 Align = Target->getPointerAlign(AS);
2028 break;
Richard Sandifordeb485fb2019-08-09 08:52:54 +00002029 // The SVE types are effectively target-specific. The length of an
2030 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2031 // of 128 bits. There is one predicate bit for each vector byte, so the
2032 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2033 //
2034 // Because the length is only known at runtime, we use a dummy value
2035 // of 0 for the static length. The alignment values are those defined
2036 // by the Procedure Call Standard for the Arm Architecture.
2037#define SVE_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, IsSigned, IsFP)\
2038 case BuiltinType::Id: \
2039 Width = 0; \
2040 Align = 128; \
2041 break;
2042#define SVE_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2043 case BuiltinType::Id: \
2044 Width = 0; \
2045 Align = 16; \
2046 break;
2047#include "clang/Basic/AArch64SVEACLETypes.def"
Chris Lattner983a8bb2007-07-13 22:13:22 +00002048 }
Chris Lattner48f84b82007-07-15 23:46:53 +00002049 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00002050 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00002051 Width = Target->getPointerWidth(0);
2052 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00002053 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002054 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002055 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00002056 Width = Target->getPointerWidth(AS);
2057 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00002058 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002059 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002060 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002061 // alignof and sizeof should never enter this code path here, so we go
2062 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002063 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00002064 Width = Target->getPointerWidth(AS);
2065 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002066 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002067 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002068 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00002069 Width = Target->getPointerWidth(AS);
2070 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00002071 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002072 case Type::MemberPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002073 const auto *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00002074 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2075 Width = MPI.Width;
2076 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00002077 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002078 }
Chris Lattner647fb222007-07-18 18:26:58 +00002079 case Type::Complex: {
2080 // Complex types have the same alignment as their elements, but twice the
2081 // size.
David Majnemer34b57492014-07-30 01:30:47 +00002082 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2083 Width = EltInfo.Width * 2;
2084 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00002085 break;
2086 }
John McCall8b07ec22010-05-15 11:32:37 +00002087 case Type::ObjCObject:
2088 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00002089 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002090 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002091 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00002092 case Type::ObjCInterface: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002093 const auto *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00002094 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00002095 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002096 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00002097 break;
2098 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002099 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002100 case Type::Enum: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002101 const auto *TT = cast<TagType>(T);
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00002102
2103 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00002104 Width = 8;
2105 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00002106 break;
2107 }
Mike Stump11289f42009-09-09 15:08:12 +00002108
Eugene Zelenko7855e772018-04-03 00:11:50 +00002109 if (const auto *ET = dyn_cast<EnumType>(TT)) {
David Majnemer475b25e2015-01-21 10:54:38 +00002110 const EnumDecl *ED = ET->getDecl();
2111 TypeInfo Info =
2112 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2113 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2114 Info.Align = AttrAlign;
2115 Info.AlignIsRequired = true;
2116 }
2117 return Info;
2118 }
Chris Lattner8b23c252008-04-06 22:05:18 +00002119
Eugene Zelenko7855e772018-04-03 00:11:50 +00002120 const auto *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00002121 const RecordDecl *RD = RT->getDecl();
2122 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00002123 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002124 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00002125 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00002126 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00002127 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002128
Chris Lattner63d2b362009-10-22 05:17:15 +00002129 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00002130 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2131 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00002132
Richard Smith600b5262017-01-26 20:40:47 +00002133 case Type::Auto:
2134 case Type::DeducedTemplateSpecialization: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002135 const auto *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00002136 assert(!A->getDeducedType().isNull() &&
2137 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00002138 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00002139 }
2140
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002141 case Type::Paren:
2142 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2143
Leonard Chanc72aaf62019-05-07 03:20:17 +00002144 case Type::MacroQualified:
2145 return getTypeInfo(
2146 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2147
Manman Rene6be26c2016-09-13 17:25:08 +00002148 case Type::ObjCTypeParam:
2149 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2150
Douglas Gregoref462e62009-04-30 17:32:17 +00002151 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00002152 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00002153 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00002154 // If the typedef has an aligned attribute on it, it overrides any computed
2155 // alignment we have. This violates the GCC documentation (which says that
2156 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00002157 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00002158 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00002159 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00002160 } else {
David Majnemer34b57492014-07-30 01:30:47 +00002161 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00002162 AlignIsRequired = Info.AlignIsRequired;
2163 }
David Majnemer34b57492014-07-30 01:30:47 +00002164 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00002165 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00002166 }
Douglas Gregoref462e62009-04-30 17:32:17 +00002167
Abramo Bagnara6150c882010-05-11 21:36:43 +00002168 case Type::Elaborated:
2169 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00002170
John McCall81904512011-01-06 01:58:22 +00002171 case Type::Attributed:
2172 return getTypeInfo(
2173 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2174
Eli Friedman0dfb8892011-10-06 23:00:33 +00002175 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00002176 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00002177 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2178 Width = Info.Width;
2179 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00002180
JF Bastien801fca22018-05-09 03:51:12 +00002181 if (!Width) {
2182 // An otherwise zero-sized type should still generate an
2183 // atomic operation.
2184 Width = Target->getCharWidth();
2185 assert(Align);
2186 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2187 // If the size of the type doesn't exceed the platform's max
2188 // atomic promotion width, make the size and alignment more
2189 // favorable to atomic operations:
2190
John McCalla8ec7eb2013-03-07 21:37:17 +00002191 // Round the size up to a power of 2.
2192 if (!llvm::isPowerOf2_64(Width))
2193 Width = llvm::NextPowerOf2(Width);
2194
2195 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002196 Align = static_cast<unsigned>(Width);
2197 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00002198 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00002199 break;
2200
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002201 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00002202 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2203 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002204 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00002205 }
Mike Stump11289f42009-09-09 15:08:12 +00002206
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002207 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00002208 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00002209}
2210
Momchil Velikov20208cc2018-07-30 17:48:23 +00002211unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2212 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2213 if (I != MemoizedUnadjustedAlign.end())
2214 return I->second;
2215
2216 unsigned UnadjustedAlign;
2217 if (const auto *RT = T->getAs<RecordType>()) {
2218 const RecordDecl *RD = RT->getDecl();
2219 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2220 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2221 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2222 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2223 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2224 } else {
John Brawn6c49f582019-05-22 11:42:54 +00002225 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
Momchil Velikov20208cc2018-07-30 17:48:23 +00002226 }
2227
2228 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2229 return UnadjustedAlign;
2230}
2231
Alexey Bataev00396512015-07-02 03:40:19 +00002232unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2233 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2234 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2235 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2236 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2237 getTargetInfo().getABI() == "elfv1-qpx" &&
2238 T->isSpecificBuiltinType(BuiltinType::Double))
2239 SimdAlign = 256;
2240 return SimdAlign;
2241}
2242
Ken Dyckcc56c542011-01-15 18:38:59 +00002243/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2244CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2245 return CharUnits::fromQuantity(BitSize / getCharWidth());
2246}
2247
Ken Dyckb0fcc592011-02-11 01:54:29 +00002248/// toBits - Convert a size in characters to a size in characters.
2249int64_t ASTContext::toBits(CharUnits CharSize) const {
2250 return CharSize.getQuantity() * getCharWidth();
2251}
2252
Ken Dyck8c89d592009-12-22 14:23:30 +00002253/// getTypeSizeInChars - Return the size of the specified type, in characters.
2254/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002255CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002256 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002257}
Jay Foad39c79802011-01-12 09:06:06 +00002258CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002259 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002260}
2261
Fangrui Song6907ce22018-07-30 19:24:48 +00002262/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002263/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002264CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002265 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002266}
Jay Foad39c79802011-01-12 09:06:06 +00002267CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002268 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002269}
2270
Momchil Velikov20208cc2018-07-30 17:48:23 +00002271/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2272/// type, in characters, before alignment adustments. This method does
2273/// not work on incomplete types.
2274CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2275 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2276}
2277CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2278 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2279}
2280
Chris Lattnera3402cd2009-01-27 18:08:34 +00002281/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2282/// type for the current target in bits. This can be different than the ABI
2283/// alignment in cases where it is beneficial for performance to overalign
2284/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002285unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002286 TypeInfo TI = getTypeInfo(T);
2287 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002288
David Majnemere1544562015-04-24 01:25:05 +00002289 T = T->getBaseElementTypeUnsafe();
2290
2291 // The preferred alignment of member pointers is that of a pointer.
2292 if (T->isMemberPointerType())
2293 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2294
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002295 if (!Target->allowsLargerPreferedTypeAlignment())
2296 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002297
Eli Friedman7ab09572009-05-25 21:27:19 +00002298 // Double and long long should be naturally aligned if possible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002299 if (const auto *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002300 T = CT->getElementType().getTypePtr();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002301 if (const auto *ET = T->getAs<EnumType>())
David Majnemer475b25e2015-01-21 10:54:38 +00002302 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002303 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002304 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2305 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002306 // Don't increase the alignment if an alignment attribute was specified on a
2307 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002308 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002309 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002310
Chris Lattnera3402cd2009-01-27 18:08:34 +00002311 return ABIAlign;
2312}
2313
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002314/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2315/// for __attribute__((aligned)) on this target, to be used if no alignment
2316/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002317unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002318 return getTargetInfo().getDefaultAlignForAttributeAligned();
2319}
2320
Ulrich Weigandfa806422013-05-06 16:23:57 +00002321/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2322/// to a global variable of the specified type.
2323unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
Tom Tanb7c6d952019-05-02 00:38:14 +00002324 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2325 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
Ulrich Weigandfa806422013-05-06 16:23:57 +00002326}
2327
2328/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2329/// should be given to a global variable of the specified type.
2330CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2331 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2332}
2333
David Majnemer08ef2ba2015-06-23 20:34:18 +00002334CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2335 CharUnits Offset = CharUnits::Zero();
2336 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2337 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2338 Offset += Layout->getBaseClassOffset(Base);
2339 Layout = &getASTRecordLayout(Base);
2340 }
2341 return Offset;
2342}
2343
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002344/// DeepCollectObjCIvars -
2345/// This routine first collects all declared, but not synthesized, ivars in
2346/// super class and then collects all ivars, including those synthesized for
2347/// current class. This routine is used for implementation of current class
2348/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002349void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2350 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002351 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002352 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2353 DeepCollectObjCIvars(SuperClass, false, Ivars);
2354 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002355 for (const auto *I : OI->ivars())
2356 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002357 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002358 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Fangrui Song6907ce22018-07-30 19:24:48 +00002359 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002360 Iv= Iv->getNextIvar())
2361 Ivars.push_back(Iv);
2362 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002363}
2364
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002365/// CollectInheritedProtocols - Collect all protocols in current class and
2366/// those inherited by it.
2367void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002368 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002369 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002370 // We can use protocol_iterator here instead of
Fangrui Song6907ce22018-07-30 19:24:48 +00002371 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002372 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002373 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002374 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002375
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002376 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002377 for (const auto *Cat : OI->visible_categories())
2378 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002379
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002380 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2381 while (SD) {
2382 CollectInheritedProtocols(SD, Protocols);
2383 SD = SD->getSuperClass();
2384 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002385 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002386 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002387 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002388 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002389 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002390 // Insert the protocol.
2391 if (!Protocols.insert(
2392 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2393 return;
2394
2395 for (auto *Proto : OP->protocols())
2396 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002397 }
2398}
2399
Erich Keane8a6b7402017-11-30 16:37:02 +00002400static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2401 const RecordDecl *RD) {
2402 assert(RD->isUnion() && "Must be union type");
2403 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2404
2405 for (const auto *Field : RD->fields()) {
2406 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2407 return false;
2408 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2409 if (FieldSize != UnionSize)
2410 return false;
2411 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002412 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002413}
2414
Benjamin Kramer802e6252017-12-24 12:46:22 +00002415static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002416 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2417
2418 if (!RD->field_empty())
2419 return false;
2420
2421 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2422 return ClassDecl->isEmpty();
2423
2424 return true;
2425}
2426
2427static llvm::Optional<int64_t>
2428structHasUniqueObjectRepresentations(const ASTContext &Context,
2429 const RecordDecl *RD) {
2430 assert(!RD->isUnion() && "Must be struct/class type");
2431 const auto &Layout = Context.getASTRecordLayout(RD);
2432
2433 int64_t CurOffsetInBits = 0;
2434 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2435 if (ClassDecl->isDynamicClass())
2436 return llvm::None;
2437
2438 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2439 for (const auto Base : ClassDecl->bases()) {
2440 // Empty types can be inherited from, and non-empty types can potentially
2441 // have tail padding, so just make sure there isn't an error.
2442 if (!isStructEmpty(Base.getType())) {
2443 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
Simon Pilgrimeed4b122019-10-02 11:48:06 +00002444 Context, Base.getType()->castAs<RecordType>()->getDecl());
Erich Keane8a6b7402017-11-30 16:37:02 +00002445 if (!Size)
2446 return llvm::None;
2447 Bases.emplace_back(Base.getType(), Size.getValue());
2448 }
2449 }
2450
Fangrui Song1d38c132018-09-30 21:41:11 +00002451 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2452 const std::pair<QualType, int64_t> &R) {
2453 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2454 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2455 });
Erich Keane8a6b7402017-11-30 16:37:02 +00002456
2457 for (const auto Base : Bases) {
2458 int64_t BaseOffset = Context.toBits(
2459 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2460 int64_t BaseSize = Base.second;
2461 if (BaseOffset != CurOffsetInBits)
2462 return llvm::None;
2463 CurOffsetInBits = BaseOffset + BaseSize;
2464 }
2465 }
2466
2467 for (const auto *Field : RD->fields()) {
2468 if (!Field->getType()->isReferenceType() &&
2469 !Context.hasUniqueObjectRepresentations(Field->getType()))
2470 return llvm::None;
2471
2472 int64_t FieldSizeInBits =
2473 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2474 if (Field->isBitField()) {
2475 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2476
2477 if (BitfieldSize > FieldSizeInBits)
2478 return llvm::None;
2479 FieldSizeInBits = BitfieldSize;
2480 }
2481
2482 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2483
2484 if (FieldOffsetInBits != CurOffsetInBits)
2485 return llvm::None;
2486
2487 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2488 }
2489
2490 return CurOffsetInBits;
2491}
2492
2493bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2494 // C++17 [meta.unary.prop]:
2495 // The predicate condition for a template specialization
2496 // has_unique_object_representations<T> shall be
2497 // satisfied if and only if:
2498 // (9.1) - T is trivially copyable, and
2499 // (9.2) - any two objects of type T with the same value have the same
2500 // object representation, where two objects
2501 // of array or non-union class type are considered to have the same value
2502 // if their respective sequences of
2503 // direct subobjects have the same values, and two objects of union type
2504 // are considered to have the same
2505 // value if they have the same active member and the corresponding members
2506 // have the same value.
2507 // The set of scalar types for which this condition holds is
2508 // implementation-defined. [ Note: If a type has padding
2509 // bits, the condition does not hold; otherwise, the condition holds true
2510 // for unsigned integral types. -- end note ]
2511 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2512
2513 // Arrays are unique only if their element type is unique.
2514 if (Ty->isArrayType())
2515 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2516
2517 // (9.1) - T is trivially copyable...
2518 if (!Ty.isTriviallyCopyableType(*this))
2519 return false;
2520
2521 // All integrals and enums are unique.
2522 if (Ty->isIntegralOrEnumerationType())
2523 return true;
2524
2525 // All other pointers are unique.
2526 if (Ty->isPointerType())
2527 return true;
2528
2529 if (Ty->isMemberPointerType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002530 const auto *MPT = Ty->getAs<MemberPointerType>();
Erich Keane8a6b7402017-11-30 16:37:02 +00002531 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2532 }
2533
2534 if (Ty->isRecordType()) {
Simon Pilgrimeed4b122019-10-02 11:48:06 +00002535 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
Erich Keane8a6b7402017-11-30 16:37:02 +00002536
Erich Keanebd2197c2017-12-12 16:02:06 +00002537 if (Record->isInvalidDecl())
2538 return false;
2539
Erich Keane8a6b7402017-11-30 16:37:02 +00002540 if (Record->isUnion())
2541 return unionHasUniqueObjectRepresentations(*this, Record);
2542
2543 Optional<int64_t> StructSize =
2544 structHasUniqueObjectRepresentations(*this, Record);
2545
2546 return StructSize &&
2547 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2548 }
2549
2550 // FIXME: More cases to handle here (list by rsmith):
2551 // vectors (careful about, eg, vector of 3 foo)
2552 // _Complex int and friends
2553 // _Atomic T
2554 // Obj-C block pointers
2555 // Obj-C object pointers
2556 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2557 // clk_event_t, queue_t, reserve_id_t)
2558 // There're also Obj-C class types and the Obj-C selector type, but I think it
2559 // makes sense for those to return false here.
2560
2561 return false;
2562}
2563
Jay Foad39c79802011-01-12 09:06:06 +00002564unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002565 unsigned count = 0;
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002566 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002567 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002568 count += Ext->ivar_size();
Fangrui Song6907ce22018-07-30 19:24:48 +00002569
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002570 // Count ivar defined in this class's implementation. This
2571 // includes synthesized ivars.
2572 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002573 count += ImplDecl->ivar_size();
2574
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002575 return count;
2576}
2577
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002578bool ASTContext::isSentinelNullExpr(const Expr *E) {
2579 if (!E)
2580 return false;
2581
2582 // nullptr_t is always treated as null.
2583 if (E->getType()->isNullPtrType()) return true;
2584
2585 if (E->getType()->isAnyPointerType() &&
2586 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2587 Expr::NPC_ValueDependentIsNull))
2588 return true;
2589
2590 // Unfortunately, __null has type 'int'.
2591 if (isa<GNUNullExpr>(E)) return true;
2592
2593 return false;
2594}
2595
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002596/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002597/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002598ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2599 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2600 I = ObjCImpls.find(D);
2601 if (I != ObjCImpls.end())
2602 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002603 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002604}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002605
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002606/// Get the implementation of ObjCCategoryDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002607/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002608ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2609 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2610 I = ObjCImpls.find(D);
2611 if (I != ObjCImpls.end())
2612 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002613 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002614}
2615
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002616/// Set the implementation of ObjCInterfaceDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002617void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2618 ObjCImplementationDecl *ImplD) {
2619 assert(IFaceD && ImplD && "Passed null params");
2620 ObjCImpls[IFaceD] = ImplD;
2621}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002622
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002623/// Set the implementation of ObjCCategoryDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002624void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2625 ObjCCategoryImplDecl *ImplD) {
2626 assert(CatD && ImplD && "Passed null params");
2627 ObjCImpls[CatD] = ImplD;
2628}
2629
Chandler Carruth21c90602015-12-30 03:24:14 +00002630const ObjCMethodDecl *
2631ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2632 return ObjCMethodRedecls.lookup(MD);
2633}
2634
2635void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2636 const ObjCMethodDecl *Redecl) {
2637 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2638 ObjCMethodRedecls[MD] = Redecl;
2639}
2640
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002641const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2642 const NamedDecl *ND) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002643 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002644 return ID;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002645 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002646 return CD->getClassInterface();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002647 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002648 return IMD->getClassInterface();
2649
Craig Topper36250ad2014-05-12 05:36:57 +00002650 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002651}
2652
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002653/// Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002654/// none exists.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002655ASTContext::BlockVarCopyInit
2656ASTContext::getBlockVarCopyInit(const VarDecl*VD) const {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002657 assert(VD && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002658 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002659 "getBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002660 auto I = BlockVarCopyInits.find(VD);
2661 if (I != BlockVarCopyInits.end())
2662 return I->second;
2663 return {nullptr, false};
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002664}
2665
JF Bastien0d702a72019-04-30 00:11:53 +00002666/// Set the copy initialization expression of a block var decl.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002667void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2668 bool CanThrow) {
2669 assert(VD && CopyExpr && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002670 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002671 "setBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002672 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002673}
2674
John McCallbcd03502009-12-07 02:54:59 +00002675TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002676 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002677 if (!DataSize)
2678 DataSize = TypeLoc::getFullDataSizeForType(T);
2679 else
2680 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002681 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002682
Eugene Zelenko7855e772018-04-03 00:11:50 +00002683 auto *TInfo =
John McCallbcd03502009-12-07 02:54:59 +00002684 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2685 new (TInfo) TypeSourceInfo(T);
2686 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002687}
2688
John McCallbcd03502009-12-07 02:54:59 +00002689TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002690 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002691 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002692 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002693 return DI;
2694}
2695
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002696const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002697ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002698 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002699}
2700
2701const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002702ASTContext::getASTObjCImplementationLayout(
2703 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002704 return getObjCLayout(D->getClassInterface(), D);
2705}
2706
Chris Lattner983a8bb2007-07-13 22:13:22 +00002707//===----------------------------------------------------------------------===//
2708// Type creation/memoization methods
2709//===----------------------------------------------------------------------===//
2710
Jay Foad39c79802011-01-12 09:06:06 +00002711QualType
John McCall33ddac02011-01-19 10:06:00 +00002712ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2713 unsigned fastQuals = quals.getFastQualifiers();
2714 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002715
2716 // Check if we've already instantiated this type.
2717 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002718 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002719 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002720 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2721 assert(eq->getQualifiers() == quals);
2722 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002723 }
2724
John McCall33ddac02011-01-19 10:06:00 +00002725 // If the base type is not canonical, make the appropriate canonical type.
2726 QualType canon;
2727 if (!baseType->isCanonicalUnqualified()) {
2728 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002729 canonSplit.Quals.addConsistentQualifiers(quals);
2730 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002731
2732 // Re-find the insert position.
2733 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2734 }
2735
Eugene Zelenko7855e772018-04-03 00:11:50 +00002736 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
John McCall33ddac02011-01-19 10:06:00 +00002737 ExtQualNodes.InsertNode(eq, insertPos);
2738 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002739}
2740
Alexander Richardson6d989432017-10-15 18:48:14 +00002741QualType ASTContext::getAddrSpaceQualType(QualType T,
2742 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002743 QualType CanT = getCanonicalType(T);
2744 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002745 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002746
John McCall8ccfcb52009-09-24 19:53:00 +00002747 // If we are composing extended qualifiers together, merge together
2748 // into one ExtQuals node.
2749 QualifierCollector Quals;
2750 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002751
John McCall8ccfcb52009-09-24 19:53:00 +00002752 // If this type already has an address space specified, it cannot get
2753 // another one.
2754 assert(!Quals.hasAddressSpace() &&
2755 "Type cannot be in multiple addr spaces!");
2756 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002757
John McCall8ccfcb52009-09-24 19:53:00 +00002758 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002759}
2760
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002761QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2762 // If we are composing extended qualifiers together, merge together
2763 // into one ExtQuals node.
2764 QualifierCollector Quals;
2765 const Type *TypeNode = Quals.strip(T);
2766
2767 // If the qualifier doesn't have an address space just return it.
2768 if (!Quals.hasAddressSpace())
2769 return T;
2770
2771 Quals.removeAddressSpace();
2772
2773 // Removal of the address space can mean there are no longer any
2774 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2775 // or required.
2776 if (Quals.hasNonFastQualifiers())
2777 return getExtQualType(TypeNode, Quals);
2778 else
2779 return QualType(TypeNode, Quals.getFastQualifiers());
2780}
2781
Chris Lattnerd60183d2009-02-18 22:53:11 +00002782QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002783 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002784 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002785 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002786 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002787
Eugene Zelenko7855e772018-04-03 00:11:50 +00002788 if (const auto *ptr = T->getAs<PointerType>()) {
John McCall53fa7142010-12-24 02:08:15 +00002789 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002790 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002791 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2792 return getPointerType(ResultType);
2793 }
2794 }
Mike Stump11289f42009-09-09 15:08:12 +00002795
John McCall8ccfcb52009-09-24 19:53:00 +00002796 // If we are composing extended qualifiers together, merge together
2797 // into one ExtQuals node.
2798 QualifierCollector Quals;
2799 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002800
John McCall8ccfcb52009-09-24 19:53:00 +00002801 // If this type already has an ObjCGC specified, it cannot get
2802 // another one.
2803 assert(!Quals.hasObjCGCAttr() &&
2804 "Type cannot have multiple ObjCGCs!");
2805 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002806
John McCall8ccfcb52009-09-24 19:53:00 +00002807 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002808}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002809
John McCall4f5019e2010-12-19 02:44:49 +00002810const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2811 FunctionType::ExtInfo Info) {
2812 if (T->getExtInfo() == Info)
2813 return T;
2814
2815 QualType Result;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002816 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002817 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002818 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002819 const auto *FPT = cast<FunctionProtoType>(T);
John McCall4f5019e2010-12-19 02:44:49 +00002820 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2821 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002822 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002823 }
2824
2825 return cast<FunctionType>(Result.getTypePtr());
2826}
2827
Richard Smith2a7d4812013-05-04 07:00:32 +00002828void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2829 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002830 FD = FD->getMostRecentDecl();
2831 while (true) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002832 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smith2a7d4812013-05-04 07:00:32 +00002833 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002834 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002835 if (FunctionDecl *Next = FD->getPreviousDecl())
2836 FD = Next;
2837 else
2838 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002839 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002840 if (ASTMutationListener *L = getASTMutationListener())
2841 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002842}
2843
Richard Smith0b3a4622014-11-13 20:01:57 +00002844/// Get a function type and produce the equivalent function type with the
2845/// specified exception specification. Type sugar that can be present on a
2846/// declaration of a function with an exception specification is permitted
2847/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002848QualType ASTContext::getFunctionTypeWithExceptionSpec(
2849 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002850 // Might have some parens.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002851 if (const auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002852 return getParenType(
2853 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002854
Leonard Chandc5d9752019-05-10 18:05:15 +00002855 // Might be wrapped in a macro qualified type.
2856 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
2857 return getMacroQualifiedType(
2858 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
2859 MQT->getMacroIdentifier());
2860
Richard Smith0b3a4622014-11-13 20:01:57 +00002861 // Might have a calling-convention attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002862 if (const auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002863 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002864 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002865 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2866 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002867
2868 // Anything else must be a function type. Rebuild it with the new exception
2869 // specification.
Simon Pilgrim9588ae72019-10-03 21:47:42 +00002870 const auto *Proto = Orig->castAs<FunctionProtoType>();
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002871 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002872 Proto->getReturnType(), Proto->getParamTypes(),
2873 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2874}
2875
Richard Smithdfe85e22016-12-15 02:35:39 +00002876bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2877 QualType U) {
2878 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002879 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002880 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2881 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002882}
2883
Richard Smith0b3a4622014-11-13 20:01:57 +00002884void ASTContext::adjustExceptionSpec(
2885 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2886 bool AsWritten) {
2887 // Update the type.
2888 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002889 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002890 FD->setType(Updated);
2891
2892 if (!AsWritten)
2893 return;
2894
2895 // Update the type in the type source information too.
2896 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2897 // If the type and the type-as-written differ, we may need to update
2898 // the type-as-written too.
2899 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002900 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002901
2902 // FIXME: When we get proper type location information for exceptions,
2903 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2904 // up the TypeSourceInfo;
2905 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2906 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2907 "TypeLoc size mismatch from updating exception specification");
2908 TSInfo->overrideType(Updated);
2909 }
2910}
2911
Chris Lattnerc6395932007-06-22 20:56:16 +00002912/// getComplexType - Return the uniqued reference to the type for a complex
2913/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002914QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002915 // Unique pointers, to guarantee there is only one pointer of a particular
2916 // structure.
2917 llvm::FoldingSetNodeID ID;
2918 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002919
Craig Topper36250ad2014-05-12 05:36:57 +00002920 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002921 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2922 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002923
Chris Lattnerc6395932007-06-22 20:56:16 +00002924 // If the pointee type isn't canonical, this won't be a canonical type either,
2925 // so fill in the canonical type field.
2926 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002927 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002928 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002929
Chris Lattnerc6395932007-06-22 20:56:16 +00002930 // Get the new insert position for the node we care about.
2931 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002932 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002933 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002934 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002935 Types.push_back(New);
2936 ComplexTypes.InsertNode(New, InsertPos);
2937 return QualType(New, 0);
2938}
2939
Chris Lattner970e54e2006-11-12 00:37:36 +00002940/// getPointerType - Return the uniqued reference to the type for a pointer to
2941/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002942QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002943 // Unique pointers, to guarantee there is only one pointer of a particular
2944 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002945 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002946 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002947
Craig Topper36250ad2014-05-12 05:36:57 +00002948 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002949 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002950 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002951
Chris Lattner7ccecb92006-11-12 08:50:50 +00002952 // If the pointee type isn't canonical, this won't be a canonical type either,
2953 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002954 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002955 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002956 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002957
Bob Wilsonc8541f22013-03-15 17:12:43 +00002958 // Get the new insert position for the node we care about.
2959 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002960 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002961 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002962 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002963 Types.push_back(New);
2964 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002965 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002966}
2967
Reid Kleckner0503a872013-12-05 01:23:43 +00002968QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2969 llvm::FoldingSetNodeID ID;
2970 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002971 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002972 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2973 if (AT)
2974 return QualType(AT, 0);
2975
2976 QualType Canonical = getCanonicalType(New);
2977
2978 // Get the new insert position for the node we care about.
2979 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002980 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002981
2982 AT = new (*this, TypeAlignment)
2983 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2984 Types.push_back(AT);
2985 AdjustedTypes.InsertNode(AT, InsertPos);
2986 return QualType(AT, 0);
2987}
2988
Reid Kleckner8a365022013-06-24 17:51:48 +00002989QualType ASTContext::getDecayedType(QualType T) const {
2990 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2991
Reid Kleckner8a365022013-06-24 17:51:48 +00002992 QualType Decayed;
2993
2994 // C99 6.7.5.3p7:
2995 // A declaration of a parameter as "array of type" shall be
2996 // adjusted to "qualified pointer to type", where the type
2997 // qualifiers (if any) are those specified within the [ and ] of
2998 // the array type derivation.
2999 if (T->isArrayType())
3000 Decayed = getArrayDecayedType(T);
3001
3002 // C99 6.7.5.3p8:
3003 // A declaration of a parameter as "function returning type"
3004 // shall be adjusted to "pointer to function returning type", as
3005 // in 6.3.2.1.
3006 if (T->isFunctionType())
3007 Decayed = getPointerType(T);
3008
Reid Kleckner0503a872013-12-05 01:23:43 +00003009 llvm::FoldingSetNodeID ID;
3010 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00003011 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00003012 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3013 if (AT)
3014 return QualType(AT, 0);
3015
Reid Kleckner8a365022013-06-24 17:51:48 +00003016 QualType Canonical = getCanonicalType(Decayed);
3017
3018 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00003019 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003020 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00003021
Reid Kleckner0503a872013-12-05 01:23:43 +00003022 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
3023 Types.push_back(AT);
3024 AdjustedTypes.InsertNode(AT, InsertPos);
3025 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00003026}
3027
Mike Stump11289f42009-09-09 15:08:12 +00003028/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00003029/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00003030QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00003031 assert(T->isFunctionType() && "block of function types only");
3032 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00003033 // structure.
3034 llvm::FoldingSetNodeID ID;
3035 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00003036
Craig Topper36250ad2014-05-12 05:36:57 +00003037 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00003038 if (BlockPointerType *PT =
3039 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3040 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003041
3042 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00003043 // type either so fill in the canonical type field.
3044 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003045 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00003046 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00003047
Steve Naroffec33ed92008-08-27 16:04:49 +00003048 // Get the new insert position for the node we care about.
3049 BlockPointerType *NewIP =
3050 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003051 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00003052 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003053 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00003054 Types.push_back(New);
3055 BlockPointerTypes.InsertNode(New, InsertPos);
3056 return QualType(New, 0);
3057}
3058
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003059/// getLValueReferenceType - Return the uniqued reference to the type for an
3060/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00003061QualType
3062ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003063 assert(getCanonicalType(T) != OverloadTy &&
Douglas Gregor291e8ee2011-05-21 22:16:50 +00003064 "Unresolved overloaded function type");
Fangrui Song6907ce22018-07-30 19:24:48 +00003065
Bill Wendling3708c182007-05-27 10:15:43 +00003066 // Unique pointers, to guarantee there is only one pointer of a particular
3067 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003068 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00003069 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00003070
Craig Topper36250ad2014-05-12 05:36:57 +00003071 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003072 if (LValueReferenceType *RT =
3073 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00003074 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003075
Eugene Zelenko7855e772018-04-03 00:11:50 +00003076 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003077
Bill Wendling3708c182007-05-27 10:15:43 +00003078 // If the referencee type isn't canonical, this won't be a canonical type
3079 // either, so fill in the canonical type field.
3080 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003081 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3082 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3083 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003084
Bill Wendling3708c182007-05-27 10:15:43 +00003085 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003086 LValueReferenceType *NewIP =
3087 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003088 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00003089 }
3090
Eugene Zelenko7855e772018-04-03 00:11:50 +00003091 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3092 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00003093 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003094 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00003095
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003096 return QualType(New, 0);
3097}
3098
3099/// getRValueReferenceType - Return the uniqued reference to the type for an
3100/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00003101QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003102 // Unique pointers, to guarantee there is only one pointer of a particular
3103 // structure.
3104 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00003105 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003106
Craig Topper36250ad2014-05-12 05:36:57 +00003107 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003108 if (RValueReferenceType *RT =
3109 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3110 return QualType(RT, 0);
3111
Eugene Zelenko7855e772018-04-03 00:11:50 +00003112 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003113
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003114 // If the referencee type isn't canonical, this won't be a canonical type
3115 // either, so fill in the canonical type field.
3116 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003117 if (InnerRef || !T.isCanonical()) {
3118 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3119 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003120
3121 // Get the new insert position for the node we care about.
3122 RValueReferenceType *NewIP =
3123 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003124 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003125 }
3126
Eugene Zelenko7855e772018-04-03 00:11:50 +00003127 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003128 Types.push_back(New);
3129 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00003130 return QualType(New, 0);
3131}
3132
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003133/// getMemberPointerType - Return the uniqued reference to the type for a
3134/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00003135QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003136 // Unique pointers, to guarantee there is only one pointer of a particular
3137 // structure.
3138 llvm::FoldingSetNodeID ID;
3139 MemberPointerType::Profile(ID, T, Cls);
3140
Craig Topper36250ad2014-05-12 05:36:57 +00003141 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003142 if (MemberPointerType *PT =
3143 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3144 return QualType(PT, 0);
3145
3146 // If the pointee or class type isn't canonical, this won't be a canonical
3147 // type either, so fill in the canonical type field.
3148 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00003149 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003150 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3151
3152 // Get the new insert position for the node we care about.
3153 MemberPointerType *NewIP =
3154 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003155 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003156 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003157 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003158 Types.push_back(New);
3159 MemberPointerTypes.InsertNode(New, InsertPos);
3160 return QualType(New, 0);
3161}
3162
Mike Stump11289f42009-09-09 15:08:12 +00003163/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00003164/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00003165QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00003166 const llvm::APInt &ArySizeIn,
Richard Smith772e2662019-10-04 01:25:59 +00003167 const Expr *SizeExpr,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003168 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003169 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00003170 assert((EltTy->isDependentType() ||
3171 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00003172 "Constant array of VLAs is illegal!");
3173
Richard Smith772e2662019-10-04 01:25:59 +00003174 // We only need the size as part of the type if it's instantiation-dependent.
3175 if (SizeExpr && !SizeExpr->isInstantiationDependent())
3176 SizeExpr = nullptr;
3177
Chris Lattnere2df3f92009-05-13 04:12:56 +00003178 // Convert the array size into a canonical width matching the pointer size for
3179 // the target.
3180 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00003181 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00003182
Chris Lattner23b7eb62007-06-15 23:05:46 +00003183 llvm::FoldingSetNodeID ID;
Richard Smith772e2662019-10-04 01:25:59 +00003184 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3185 IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00003186
Craig Topper36250ad2014-05-12 05:36:57 +00003187 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003188 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003189 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003190 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003191
Richard Smith772e2662019-10-04 01:25:59 +00003192 // If the element type isn't canonical or has qualifiers, or the array bound
3193 // is instantiation-dependent, this won't be a canonical type either, so fill
3194 // in the canonical type field.
John McCall33ddac02011-01-19 10:06:00 +00003195 QualType Canon;
Richard Smith772e2662019-10-04 01:25:59 +00003196 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
John McCall33ddac02011-01-19 10:06:00 +00003197 SplitQualType canonSplit = getCanonicalType(EltTy).split();
Richard Smith772e2662019-10-04 01:25:59 +00003198 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003199 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003200 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003201
Chris Lattner36f8e652007-01-27 08:31:04 +00003202 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00003203 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003204 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003205 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00003206 }
Mike Stump11289f42009-09-09 15:08:12 +00003207
Richard Smith772e2662019-10-04 01:25:59 +00003208 void *Mem = Allocate(
3209 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
3210 TypeAlignment);
3211 auto *New = new (Mem)
3212 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00003213 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00003214 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003215 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00003216}
3217
John McCall06549462011-01-18 08:40:38 +00003218/// getVariableArrayDecayedType - Turns the given type, which may be
3219/// variably-modified, into the corresponding type with all the known
3220/// sizes replaced with [*].
3221QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3222 // Vastly most common case.
3223 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003224
John McCall06549462011-01-18 08:40:38 +00003225 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003226
John McCall06549462011-01-18 08:40:38 +00003227 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003228 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00003229 switch (ty->getTypeClass()) {
3230#define TYPE(Class, Base)
3231#define ABSTRACT_TYPE(Class, Base)
3232#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
John McCall36b12a82019-10-02 06:35:23 +00003233#include "clang/AST/TypeNodes.inc"
John McCall06549462011-01-18 08:40:38 +00003234 llvm_unreachable("didn't desugar past all non-canonical types?");
3235
3236 // These types should never be variably-modified.
3237 case Type::Builtin:
3238 case Type::Complex:
3239 case Type::Vector:
Erich Keanef702b022018-07-13 19:46:04 +00003240 case Type::DependentVector:
John McCall06549462011-01-18 08:40:38 +00003241 case Type::ExtVector:
3242 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003243 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00003244 case Type::ObjCObject:
3245 case Type::ObjCInterface:
3246 case Type::ObjCObjectPointer:
3247 case Type::Record:
3248 case Type::Enum:
3249 case Type::UnresolvedUsing:
3250 case Type::TypeOfExpr:
3251 case Type::TypeOf:
3252 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00003253 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00003254 case Type::DependentName:
3255 case Type::InjectedClassName:
3256 case Type::TemplateSpecialization:
3257 case Type::DependentTemplateSpecialization:
3258 case Type::TemplateTypeParm:
3259 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00003260 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003261 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00003262 case Type::PackExpansion:
3263 llvm_unreachable("type should never be variably-modified");
3264
3265 // These types can be variably-modified but should never need to
3266 // further decay.
3267 case Type::FunctionNoProto:
3268 case Type::FunctionProto:
3269 case Type::BlockPointer:
3270 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00003271 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00003272 return type;
3273
3274 // These types can be variably-modified. All these modifications
3275 // preserve structure except as noted by comments.
3276 // TODO: if we ever care about optimizing VLAs, there are no-op
3277 // optimizations available here.
3278 case Type::Pointer:
3279 result = getPointerType(getVariableArrayDecayedType(
3280 cast<PointerType>(ty)->getPointeeType()));
3281 break;
3282
3283 case Type::LValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003284 const auto *lv = cast<LValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003285 result = getLValueReferenceType(
3286 getVariableArrayDecayedType(lv->getPointeeType()),
3287 lv->isSpelledAsLValue());
3288 break;
3289 }
3290
3291 case Type::RValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003292 const auto *lv = cast<RValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003293 result = getRValueReferenceType(
3294 getVariableArrayDecayedType(lv->getPointeeType()));
3295 break;
3296 }
3297
Eli Friedman0dfb8892011-10-06 23:00:33 +00003298 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003299 const auto *at = cast<AtomicType>(ty);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003300 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3301 break;
3302 }
3303
John McCall06549462011-01-18 08:40:38 +00003304 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003305 const auto *cat = cast<ConstantArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003306 result = getConstantArrayType(
3307 getVariableArrayDecayedType(cat->getElementType()),
3308 cat->getSize(),
Richard Smith772e2662019-10-04 01:25:59 +00003309 cat->getSizeExpr(),
John McCall06549462011-01-18 08:40:38 +00003310 cat->getSizeModifier(),
3311 cat->getIndexTypeCVRQualifiers());
3312 break;
3313 }
3314
3315 case Type::DependentSizedArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003316 const auto *dat = cast<DependentSizedArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003317 result = getDependentSizedArrayType(
3318 getVariableArrayDecayedType(dat->getElementType()),
3319 dat->getSizeExpr(),
3320 dat->getSizeModifier(),
3321 dat->getIndexTypeCVRQualifiers(),
3322 dat->getBracketsRange());
3323 break;
3324 }
3325
3326 // Turn incomplete types into [*] types.
3327 case Type::IncompleteArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003328 const auto *iat = cast<IncompleteArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003329 result = getVariableArrayType(
3330 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003331 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003332 ArrayType::Normal,
3333 iat->getIndexTypeCVRQualifiers(),
3334 SourceRange());
3335 break;
3336 }
3337
3338 // Turn VLA types into [*] types.
3339 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003340 const auto *vat = cast<VariableArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003341 result = getVariableArrayType(
3342 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003343 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003344 ArrayType::Star,
3345 vat->getIndexTypeCVRQualifiers(),
3346 vat->getBracketsRange());
3347 break;
3348 }
3349 }
3350
3351 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003352 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003353}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003354
Steve Naroffcadebd02007-08-30 18:14:25 +00003355/// getVariableArrayType - Returns a non-unique reference to the type for a
3356/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003357QualType ASTContext::getVariableArrayType(QualType EltTy,
3358 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003359 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003360 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003361 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003362 // Since we don't unique expressions, it isn't possible to unique VLA's
3363 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003364 QualType Canon;
Fangrui Song6907ce22018-07-30 19:24:48 +00003365
John McCall33ddac02011-01-19 10:06:00 +00003366 // Be sure to pull qualifiers off the element type.
3367 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3368 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003369 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003370 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003371 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003372 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003373
Eugene Zelenko7855e772018-04-03 00:11:50 +00003374 auto *New = new (*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003375 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003376
3377 VariableArrayTypes.push_back(New);
3378 Types.push_back(New);
3379 return QualType(New, 0);
3380}
3381
Douglas Gregor4619e432008-12-05 23:32:09 +00003382/// getDependentSizedArrayType - Returns a non-unique reference to
3383/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003384/// type.
John McCall33ddac02011-01-19 10:06:00 +00003385QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3386 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003387 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003388 unsigned elementTypeQuals,
3389 SourceRange brackets) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003390 assert((!numElements || numElements->isTypeDependent() ||
John McCall33ddac02011-01-19 10:06:00 +00003391 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003392 "Size must be type- or value-dependent!");
3393
John McCall33ddac02011-01-19 10:06:00 +00003394 // Dependently-sized array types that do not have a specified number
3395 // of elements will have their sizes deduced from a dependent
3396 // initializer. We do no canonicalization here at all, which is okay
3397 // because they can't be used in most locations.
3398 if (!numElements) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003399 auto *newType
John McCall33ddac02011-01-19 10:06:00 +00003400 = new (*this, TypeAlignment)
3401 DependentSizedArrayType(*this, elementType, QualType(),
3402 numElements, ASM, elementTypeQuals,
3403 brackets);
3404 Types.push_back(newType);
3405 return QualType(newType, 0);
3406 }
3407
3408 // Otherwise, we actually build a new type every time, but we
3409 // also build a canonical type.
3410
3411 SplitQualType canonElementType = getCanonicalType(elementType).split();
3412
Craig Topper36250ad2014-05-12 05:36:57 +00003413 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003414 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003415 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003416 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003417 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003418
John McCall33ddac02011-01-19 10:06:00 +00003419 // Look for an existing type with these properties.
3420 DependentSizedArrayType *canonTy =
3421 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003422
John McCall33ddac02011-01-19 10:06:00 +00003423 // If we don't have one, build one.
3424 if (!canonTy) {
3425 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003426 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003427 QualType(), numElements, ASM, elementTypeQuals,
3428 brackets);
3429 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3430 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003431 }
3432
John McCall33ddac02011-01-19 10:06:00 +00003433 // Apply qualifiers from the element type to the array.
3434 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003435 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003436
David Majnemer16a74702015-07-24 05:54:19 +00003437 // If we didn't need extra canonicalization for the element type or the size
3438 // expression, then just use that as our result.
3439 if (QualType(canonElementType.Ty, 0) == elementType &&
3440 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003441 return canon;
3442
3443 // Otherwise, we need to build a type which follows the spelling
3444 // of the element type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00003445 auto *sugaredType
John McCall33ddac02011-01-19 10:06:00 +00003446 = new (*this, TypeAlignment)
3447 DependentSizedArrayType(*this, elementType, canon, numElements,
3448 ASM, elementTypeQuals, brackets);
3449 Types.push_back(sugaredType);
3450 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003451}
3452
John McCall33ddac02011-01-19 10:06:00 +00003453QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003454 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003455 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003456 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003457 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003458
Craig Topper36250ad2014-05-12 05:36:57 +00003459 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003460 if (IncompleteArrayType *iat =
3461 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3462 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003463
3464 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003465 // either, so fill in the canonical type field. We also have to pull
3466 // qualifiers off the element type.
3467 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003468
John McCall33ddac02011-01-19 10:06:00 +00003469 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3470 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003471 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003472 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003473 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003474
3475 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003476 IncompleteArrayType *existing =
3477 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3478 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003479 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003480
Eugene Zelenko7855e772018-04-03 00:11:50 +00003481 auto *newType = new (*this, TypeAlignment)
John McCall33ddac02011-01-19 10:06:00 +00003482 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003483
John McCall33ddac02011-01-19 10:06:00 +00003484 IncompleteArrayTypes.InsertNode(newType, insertPos);
3485 Types.push_back(newType);
3486 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003487}
3488
Steve Naroff91fcddb2007-07-18 18:00:27 +00003489/// getVectorType - Return the unique reference to a vector type of
3490/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003491QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003492 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003493 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003494
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003495 // Check if we've already instantiated a vector of this type.
3496 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003497 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003498
Craig Topper36250ad2014-05-12 05:36:57 +00003499 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003500 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3501 return QualType(VTP, 0);
3502
3503 // If the element type isn't canonical, this won't be a canonical type either,
3504 // so fill in the canonical type field.
3505 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003506 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003507 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003508
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003509 // Get the new insert position for the node we care about.
3510 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003511 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003512 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003513 auto *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003514 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003515 VectorTypes.InsertNode(New, InsertPos);
3516 Types.push_back(New);
3517 return QualType(New, 0);
3518}
3519
Erich Keanef702b022018-07-13 19:46:04 +00003520QualType
3521ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3522 SourceLocation AttrLoc,
3523 VectorType::VectorKind VecKind) const {
3524 llvm::FoldingSetNodeID ID;
3525 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3526 VecKind);
3527 void *InsertPos = nullptr;
3528 DependentVectorType *Canon =
3529 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3530 DependentVectorType *New;
3531
3532 if (Canon) {
3533 New = new (*this, TypeAlignment) DependentVectorType(
3534 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3535 } else {
3536 QualType CanonVecTy = getCanonicalType(VecType);
3537 if (CanonVecTy == VecType) {
3538 New = new (*this, TypeAlignment) DependentVectorType(
3539 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3540
3541 DependentVectorType *CanonCheck =
3542 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3543 assert(!CanonCheck &&
3544 "Dependent-sized vector_size canonical type broken");
3545 (void)CanonCheck;
3546 DependentVectorTypes.InsertNode(New, InsertPos);
3547 } else {
3548 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3549 SourceLocation());
3550 New = new (*this, TypeAlignment) DependentVectorType(
3551 *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
3552 }
3553 }
3554
3555 Types.push_back(New);
3556 return QualType(New, 0);
3557}
3558
Nate Begemance4d7fc2008-04-18 23:10:10 +00003559/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003560/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003561QualType
3562ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003563 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003564
Steve Naroff91fcddb2007-07-18 18:00:27 +00003565 // Check if we've already instantiated a vector of this type.
3566 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003567 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003568 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003569 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003570 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3571 return QualType(VTP, 0);
3572
3573 // If the element type isn't canonical, this won't be a canonical type either,
3574 // so fill in the canonical type field.
3575 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003576 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003577 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003578
Steve Naroff91fcddb2007-07-18 18:00:27 +00003579 // Get the new insert position for the node we care about.
3580 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003581 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003582 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003583 auto *New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003584 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003585 VectorTypes.InsertNode(New, InsertPos);
3586 Types.push_back(New);
3587 return QualType(New, 0);
3588}
3589
Jay Foad39c79802011-01-12 09:06:06 +00003590QualType
3591ASTContext::getDependentSizedExtVectorType(QualType vecType,
3592 Expr *SizeExpr,
3593 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003594 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003595 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003596 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003597
Craig Topper36250ad2014-05-12 05:36:57 +00003598 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003599 DependentSizedExtVectorType *Canon
3600 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3601 DependentSizedExtVectorType *New;
3602 if (Canon) {
3603 // We already have a canonical version of this array type; use it as
3604 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003605 New = new (*this, TypeAlignment)
3606 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3607 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003608 } else {
3609 QualType CanonVecTy = getCanonicalType(vecType);
3610 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003611 New = new (*this, TypeAlignment)
3612 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3613 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003614
3615 DependentSizedExtVectorType *CanonCheck
3616 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3617 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3618 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003619 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3620 } else {
3621 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3622 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003623 New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003624 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003625 }
3626 }
Mike Stump11289f42009-09-09 15:08:12 +00003627
Douglas Gregor758a8692009-06-17 21:51:59 +00003628 Types.push_back(New);
3629 return QualType(New, 0);
3630}
3631
Fangrui Song6907ce22018-07-30 19:24:48 +00003632QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3633 Expr *AddrSpaceExpr,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003634 SourceLocation AttrLoc) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003635 assert(AddrSpaceExpr->isInstantiationDependent());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003636
3637 QualType canonPointeeType = getCanonicalType(PointeeType);
3638
3639 void *insertPos = nullptr;
3640 llvm::FoldingSetNodeID ID;
3641 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3642 AddrSpaceExpr);
3643
3644 DependentAddressSpaceType *canonTy =
3645 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3646
3647 if (!canonTy) {
3648 canonTy = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003649 DependentAddressSpaceType(*this, canonPointeeType,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003650 QualType(), AddrSpaceExpr, AttrLoc);
3651 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3652 Types.push_back(canonTy);
3653 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003654
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003655 if (canonPointeeType == PointeeType &&
3656 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
Fangrui Song6907ce22018-07-30 19:24:48 +00003657 return QualType(canonTy, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003658
Eugene Zelenko7855e772018-04-03 00:11:50 +00003659 auto *sugaredType
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003660 = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003661 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003662 AddrSpaceExpr, AttrLoc);
3663 Types.push_back(sugaredType);
Fangrui Song6907ce22018-07-30 19:24:48 +00003664 return QualType(sugaredType, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003665}
3666
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003667/// Determine whether \p T is canonical as the result type of a function.
John McCall18afab72016-03-01 00:49:02 +00003668static bool isCanonicalResultType(QualType T) {
3669 return T.isCanonical() &&
3670 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3671 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3672}
3673
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003674/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003675QualType
3676ASTContext::getFunctionNoProtoType(QualType ResultTy,
3677 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003678 // Unique functions, to guarantee there is only one function of a particular
3679 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003680 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003681 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003682
Craig Topper36250ad2014-05-12 05:36:57 +00003683 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003684 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003685 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003686 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003687
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003688 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003689 if (!isCanonicalResultType(ResultTy)) {
3690 Canonical =
3691 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003692
Chris Lattner47955de2007-01-27 08:37:20 +00003693 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003694 FunctionNoProtoType *NewIP =
3695 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003696 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003697 }
Mike Stump11289f42009-09-09 15:08:12 +00003698
Eugene Zelenko7855e772018-04-03 00:11:50 +00003699 auto *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003700 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003701 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003702 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003703 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003704}
3705
Douglas Gregora602a152015-10-01 20:20:47 +00003706CanQualType
3707ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3708 CanQualType CanResultType = getCanonicalType(ResultType);
3709
3710 // Canonical result types do not have ARC lifetime qualifiers.
3711 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3712 Qualifiers Qs = CanResultType.getQualifiers();
3713 Qs.removeObjCLifetime();
3714 return CanQualType::CreateUnsafe(
3715 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3716 }
3717
3718 return CanResultType;
3719}
3720
Richard Smith3c4f8d22016-10-16 17:54:23 +00003721static bool isCanonicalExceptionSpecification(
3722 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3723 if (ESI.Type == EST_None)
3724 return true;
3725 if (!NoexceptInType)
3726 return false;
3727
3728 // C++17 onwards: exception specification is part of the type, as a simple
3729 // boolean "can this function type throw".
3730 if (ESI.Type == EST_BasicNoexcept)
3731 return true;
3732
Richard Smitheaf11ad2018-05-03 03:58:32 +00003733 // A noexcept(expr) specification is (possibly) canonical if expr is
3734 // value-dependent.
3735 if (ESI.Type == EST_DependentNoexcept)
3736 return true;
3737
Richard Smith3c4f8d22016-10-16 17:54:23 +00003738 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003739 // expansions (so we can't tell whether it's non-throwing) and all its
3740 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003741 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003742 bool AnyPackExpansions = false;
3743 for (QualType ET : ESI.Exceptions) {
3744 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003745 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003746 if (ET->getAs<PackExpansionType>())
3747 AnyPackExpansions = true;
3748 }
3749 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003750 }
3751
Richard Smith3c4f8d22016-10-16 17:54:23 +00003752 return false;
3753}
3754
Richard Smith304b1242016-10-18 20:13:25 +00003755QualType ASTContext::getFunctionTypeInternal(
3756 QualType ResultTy, ArrayRef<QualType> ArgArray,
3757 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003758 size_t NumArgs = ArgArray.size();
3759
Richard Smith2a2cda52016-10-18 19:29:18 +00003760 // Unique functions, to guarantee there is only one function of a particular
3761 // structure.
3762 llvm::FoldingSetNodeID ID;
3763 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3764 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003765
Richard Smith2a2cda52016-10-18 19:29:18 +00003766 QualType Canonical;
3767 bool Unique = false;
3768
3769 void *InsertPos = nullptr;
3770 if (FunctionProtoType *FPT =
3771 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3772 QualType Existing = QualType(FPT, 0);
3773
3774 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3775 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003776 // noexcept expression, or we're just looking for a canonical type.
3777 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003778 // sugar node to hold the concrete expression.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003779 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003780 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3781 return Existing;
3782
3783 // We need a new type sugar node for this one, to hold the new noexcept
3784 // expression. We do no canonicalization here, but that's OK since we don't
3785 // expect to see the same noexcept expression much more than once.
3786 Canonical = getCanonicalType(Existing);
3787 Unique = true;
3788 }
3789
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003790 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003791 bool IsCanonicalExceptionSpec =
3792 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3793
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003794 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003795 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003796 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003797 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003798 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003799 isCanonical = false;
3800
Richard Smith304b1242016-10-18 20:13:25 +00003801 if (OnlyWantCanonical)
3802 assert(isCanonical &&
3803 "given non-canonical parameters constructing canonical type");
3804
Richard Smith2a2cda52016-10-18 19:29:18 +00003805 // If this type isn't canonical, get the canonical version of it if we don't
3806 // already have it. The exception spec is only partially part of the
3807 // canonical type, and only in C++17 onwards.
3808 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003809 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003810 CanonicalArgs.reserve(NumArgs);
3811 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003812 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003813
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003814 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003815 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003816 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003817
3818 if (IsCanonicalExceptionSpec) {
3819 // Exception spec is already OK.
3820 } else if (NoexceptInType) {
3821 switch (EPI.ExceptionSpec.Type) {
3822 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3823 // We don't know yet. It shouldn't matter what we pick here; no-one
3824 // should ever look at this.
3825 LLVM_FALLTHROUGH;
Richard Smitheaf11ad2018-05-03 03:58:32 +00003826 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003827 CanonicalEPI.ExceptionSpec.Type = EST_None;
3828 break;
3829
Richard Smith2a2cda52016-10-18 19:29:18 +00003830 // A dynamic exception specification is almost always "not noexcept",
3831 // with the exception that a pack expansion might expand to no types.
3832 case EST_Dynamic: {
3833 bool AnyPacks = false;
3834 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3835 if (ET->getAs<PackExpansionType>())
3836 AnyPacks = true;
3837 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3838 }
3839 if (!AnyPacks)
3840 CanonicalEPI.ExceptionSpec.Type = EST_None;
3841 else {
3842 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3843 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3844 }
3845 break;
3846 }
3847
Erich Keaned02f4a12019-05-30 17:31:54 +00003848 case EST_DynamicNone:
3849 case EST_BasicNoexcept:
3850 case EST_NoexceptTrue:
3851 case EST_NoThrow:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003852 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3853 break;
3854
Richard Smitheaf11ad2018-05-03 03:58:32 +00003855 case EST_DependentNoexcept:
3856 llvm_unreachable("dependent noexcept is already canonical");
Richard Smith3c4f8d22016-10-16 17:54:23 +00003857 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003858 } else {
3859 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3860 }
John McCalldb40c7f2010-12-14 08:05:40 +00003861
Douglas Gregora602a152015-10-01 20:20:47 +00003862 // Adjust the canonical function result type.
3863 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003864 Canonical =
3865 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003866
Chris Lattnerfd4de792007-01-27 01:15:32 +00003867 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003868 FunctionProtoType *NewIP =
3869 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003870 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003871 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003872
Bruno Ricci26a25362018-10-02 11:46:38 +00003873 // Compute the needed size to hold this FunctionProtoType and the
3874 // various trailing objects.
3875 auto ESH = FunctionProtoType::getExceptionSpecSize(
3876 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
3877 size_t Size = FunctionProtoType::totalSizeToAlloc<
Nicolas Manichoncc3c9352019-12-03 08:21:55 -05003878 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
Bruno Ricci26a25362018-10-02 11:46:38 +00003879 FunctionType::ExceptionType, Expr *, FunctionDecl *,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003880 FunctionProtoType::ExtParameterInfo, Qualifiers>(
Nicolas Manichoncc3c9352019-12-03 08:21:55 -05003881 NumArgs, EPI.Variadic,
3882 FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
Bruno Ricci26a25362018-10-02 11:46:38 +00003883 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003884 EPI.ExtParameterInfos ? NumArgs : 0,
3885 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
John McCall18afab72016-03-01 00:49:02 +00003886
Bruno Ricci26a25362018-10-02 11:46:38 +00003887 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003888 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003889 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003890 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003891 if (!Unique)
3892 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003893 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003894}
Chris Lattneref51c202006-11-10 07:17:23 +00003895
Joey Goulye3c85de2016-12-01 11:30:49 +00003896QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003897 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003898 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003899
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00003900 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00003901 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003902 return QualType(PT, 0);
3903
3904 // If the pipe element type isn't canonical, this won't be a canonical type
3905 // either, so fill in the canonical type field.
3906 QualType Canonical;
3907 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003908 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003909
3910 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003911 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003912 assert(!NewIP && "Shouldn't be in the map!");
3913 (void)NewIP;
3914 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003915 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003916 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003917 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003918 return QualType(New, 0);
3919}
3920
Anastasia Stulova59055b92018-05-09 13:23:26 +00003921QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
3922 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3923 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3924 : Ty;
3925}
3926
Joey Goulye3c85de2016-12-01 11:30:49 +00003927QualType ASTContext::getReadPipeType(QualType T) const {
3928 return getPipeType(T, true);
3929}
3930
Joey Gouly5788b782016-11-18 14:10:54 +00003931QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003932 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003933}
3934
John McCalle78aac42010-03-10 03:28:59 +00003935#ifndef NDEBUG
3936static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3937 if (!isa<CXXRecordDecl>(D)) return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00003938 const auto *RD = cast<CXXRecordDecl>(D);
John McCalle78aac42010-03-10 03:28:59 +00003939 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3940 return true;
3941 if (RD->getDescribedClassTemplate() &&
3942 !isa<ClassTemplateSpecializationDecl>(RD))
3943 return true;
3944 return false;
3945}
3946#endif
3947
3948/// getInjectedClassNameType - Return the unique reference to the
3949/// injected class name type for the specified templated declaration.
3950QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003951 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003952 assert(NeedsInjectedClassNameType(Decl));
3953 if (Decl->TypeForDecl) {
3954 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003955 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003956 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3957 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3958 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3959 } else {
John McCall424cec92011-01-19 06:33:43 +00003960 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003961 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003962 Decl->TypeForDecl = newType;
3963 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003964 }
3965 return QualType(Decl->TypeForDecl, 0);
3966}
3967
Douglas Gregor83a586e2008-04-13 21:07:44 +00003968/// getTypeDeclType - Return the unique reference to the type for the
3969/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003970QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003971 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003972 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003973
Eugene Zelenko7855e772018-04-03 00:11:50 +00003974 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003975 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003976
John McCall96f0b5f2010-03-10 06:48:02 +00003977 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3978 "Template type parameter types are always available.");
3979
Eugene Zelenko7855e772018-04-03 00:11:50 +00003980 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003981 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003982 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003983 return getRecordType(Record);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003984 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003985 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003986 return getEnumType(Enum);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003987 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003988 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3989 Decl->TypeForDecl = newType;
3990 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003991 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003992 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003993
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003994 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003995}
3996
Chris Lattner32d920b2007-01-26 02:01:53 +00003997/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003998/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003999QualType
Richard Smithdda56e42011-04-15 14:24:37 +00004000ASTContext::getTypedefType(const TypedefNameDecl *Decl,
4001 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00004002 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004003
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004004 if (Canonical.isNull())
4005 Canonical = getCanonicalType(Decl->getUnderlyingType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00004006 auto *newType = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00004007 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00004008 Decl->TypeForDecl = newType;
4009 Types.push_back(newType);
4010 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00004011}
4012
Jay Foad39c79802011-01-12 09:06:06 +00004013QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004014 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4015
Douglas Gregorec9fd132012-01-14 16:38:05 +00004016 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004017 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00004018 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004019
Eugene Zelenko7855e772018-04-03 00:11:50 +00004020 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
John McCall424cec92011-01-19 06:33:43 +00004021 Decl->TypeForDecl = newType;
4022 Types.push_back(newType);
4023 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004024}
4025
Jay Foad39c79802011-01-12 09:06:06 +00004026QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004027 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4028
Douglas Gregorec9fd132012-01-14 16:38:05 +00004029 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004030 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00004031 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004032
Eugene Zelenko7855e772018-04-03 00:11:50 +00004033 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
John McCall424cec92011-01-19 06:33:43 +00004034 Decl->TypeForDecl = newType;
4035 Types.push_back(newType);
4036 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004037}
4038
Richard Smithe43e2b32018-08-20 21:47:29 +00004039QualType ASTContext::getAttributedType(attr::Kind attrKind,
John McCall81904512011-01-06 01:58:22 +00004040 QualType modifiedType,
4041 QualType equivalentType) {
4042 llvm::FoldingSetNodeID id;
4043 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4044
Craig Topper36250ad2014-05-12 05:36:57 +00004045 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00004046 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4047 if (type) return QualType(type, 0);
4048
4049 QualType canon = getCanonicalType(equivalentType);
4050 type = new (*this, TypeAlignment)
Leonard Chanc72aaf62019-05-07 03:20:17 +00004051 AttributedType(canon, attrKind, modifiedType, equivalentType);
John McCall81904512011-01-06 01:58:22 +00004052
4053 Types.push_back(type);
4054 AttributedTypes.InsertNode(type, insertPos);
4055
4056 return QualType(type, 0);
4057}
4058
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004059/// Retrieve a substitution-result type.
John McCallcebee162009-10-18 09:09:24 +00004060QualType
4061ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00004062 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00004063 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00004064 && "replacement types must always be canonical");
4065
4066 llvm::FoldingSetNodeID ID;
4067 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00004068 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00004069 SubstTemplateTypeParmType *SubstParm
4070 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4071
4072 if (!SubstParm) {
4073 SubstParm = new (*this, TypeAlignment)
4074 SubstTemplateTypeParmType(Parm, Replacement);
4075 Types.push_back(SubstParm);
4076 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4077 }
4078
4079 return QualType(SubstParm, 0);
4080}
4081
Fangrui Song6907ce22018-07-30 19:24:48 +00004082/// Retrieve a
Douglas Gregorada4b792011-01-14 02:55:32 +00004083QualType ASTContext::getSubstTemplateTypeParmPackType(
4084 const TemplateTypeParmType *Parm,
4085 const TemplateArgument &ArgPack) {
4086#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00004087 for (const auto &P : ArgPack.pack_elements()) {
4088 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4089 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00004090 }
4091#endif
Fangrui Song6907ce22018-07-30 19:24:48 +00004092
Douglas Gregorada4b792011-01-14 02:55:32 +00004093 llvm::FoldingSetNodeID ID;
4094 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00004095 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00004096 if (SubstTemplateTypeParmPackType *SubstParm
4097 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4098 return QualType(SubstParm, 0);
Fangrui Song6907ce22018-07-30 19:24:48 +00004099
Douglas Gregorada4b792011-01-14 02:55:32 +00004100 QualType Canon;
4101 if (!Parm->isCanonicalUnqualified()) {
4102 Canon = getCanonicalType(QualType(Parm, 0));
4103 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4104 ArgPack);
4105 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4106 }
4107
Eugene Zelenko7855e772018-04-03 00:11:50 +00004108 auto *SubstParm
Douglas Gregorada4b792011-01-14 02:55:32 +00004109 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4110 ArgPack);
4111 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00004112 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00004113 return QualType(SubstParm, 0);
Douglas Gregorada4b792011-01-14 02:55:32 +00004114}
4115
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004116/// Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00004117/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00004118/// name.
Mike Stump11289f42009-09-09 15:08:12 +00004119QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00004120 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00004121 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00004122 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00004123 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00004124 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004125 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00004126 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4127
4128 if (TypeParm)
4129 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004130
Chandler Carruth08836322011-05-01 00:51:33 +00004131 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00004132 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00004133 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004134
Fangrui Song6907ce22018-07-30 19:24:48 +00004135 TemplateTypeParmType *TypeCheck
Douglas Gregorc42075a2010-02-04 18:10:26 +00004136 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4137 assert(!TypeCheck && "Template type parameter canonical type broken");
4138 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00004139 } else
John McCall90d1c2d2009-09-24 23:30:46 +00004140 TypeParm = new (*this, TypeAlignment)
4141 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00004142
4143 Types.push_back(TypeParm);
4144 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4145
4146 return QualType(TypeParm, 0);
4147}
4148
John McCalle78aac42010-03-10 03:28:59 +00004149TypeSourceInfo *
4150ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4151 SourceLocation NameLoc,
4152 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004153 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004154 assert(!Name.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004155 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004156 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00004157
4158 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00004159 TemplateSpecializationTypeLoc TL =
4160 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00004161 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00004162 TL.setTemplateNameLoc(NameLoc);
4163 TL.setLAngleLoc(Args.getLAngleLoc());
4164 TL.setRAngleLoc(Args.getRAngleLoc());
4165 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4166 TL.setArgLocInfo(i, Args[i].getLocInfo());
4167 return DI;
4168}
4169
Mike Stump11289f42009-09-09 15:08:12 +00004170QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00004171ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00004172 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004173 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004174 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004175 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00004176
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004177 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004178 ArgVec.reserve(Args.size());
4179 for (const TemplateArgumentLoc &Arg : Args.arguments())
4180 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00004181
David Majnemer6fbeee32016-07-07 04:43:07 +00004182 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00004183}
4184
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004185#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00004186static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4187 for (const TemplateArgument &Arg : Args)
4188 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004189 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004190
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004191 return true;
4192}
4193#endif
4194
John McCall0ad16662009-10-29 08:12:44 +00004195QualType
4196ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00004197 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004198 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004199 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004200 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00004201 // Look through qualified template names.
4202 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4203 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004204
4205 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00004206 Template.getAsTemplateDecl() &&
4207 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004208 QualType CanonType;
4209 if (!Underlying.isNull())
4210 CanonType = getCanonicalType(Underlying);
4211 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004212 // We can get here with an alias template when the specialization contains
4213 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00004214 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004215 "Caller must compute aliased type");
4216 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004217 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00004218 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00004219
Douglas Gregora8e02e72009-07-28 23:00:59 +00004220 // Allocate the (non-canonical) template specialization type, but don't
4221 // try to unique it: these types typically have location information that
4222 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004223 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00004224 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004225 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00004226 TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004227 auto *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00004228 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004229 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00004230
Douglas Gregor8bf42052009-02-09 18:46:07 +00004231 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00004232 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00004233}
4234
David Majnemer6fbeee32016-07-07 04:43:07 +00004235QualType ASTContext::getCanonicalTemplateSpecializationType(
4236 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004237 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004238 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004239
Douglas Gregore29139c2011-03-03 17:04:51 +00004240 // Look through qualified template names.
4241 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4242 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004243
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004244 // Build the canonical template specialization type.
4245 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004246 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00004247 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004248 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00004249 for (const TemplateArgument &Arg : Args)
4250 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004251
4252 // Determine whether this canonical template specialization type already
4253 // exists.
4254 llvm::FoldingSetNodeID ID;
4255 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004256 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004257
Craig Topper36250ad2014-05-12 05:36:57 +00004258 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004259 TemplateSpecializationType *Spec
4260 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4261
4262 if (!Spec) {
4263 // Allocate a new canonical template specialization type.
4264 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4265 sizeof(TemplateArgument) * NumArgs),
4266 TypeAlignment);
4267 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004268 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004269 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004270 Types.push_back(Spec);
4271 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4272 }
4273
4274 assert(Spec->isDependentType() &&
4275 "Non-dependent template-id type must have a canonical type");
4276 return QualType(Spec, 0);
4277}
4278
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004279QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4280 NestedNameSpecifier *NNS,
4281 QualType NamedType,
4282 TagDecl *OwnedTagDecl) const {
Douglas Gregor52537682009-03-19 00:18:19 +00004283 llvm::FoldingSetNodeID ID;
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004284 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
Douglas Gregor52537682009-03-19 00:18:19 +00004285
Craig Topper36250ad2014-05-12 05:36:57 +00004286 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00004287 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004288 if (T)
4289 return QualType(T, 0);
4290
Douglas Gregorc42075a2010-02-04 18:10:26 +00004291 QualType Canon = NamedType;
4292 if (!Canon.isCanonical()) {
4293 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004294 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4295 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004296 (void)CheckT;
4297 }
4298
Bruno Riccid6bd5982018-08-16 10:48:16 +00004299 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4300 TypeAlignment);
4301 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4302
Douglas Gregor52537682009-03-19 00:18:19 +00004303 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004304 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004305 return QualType(T, 0);
4306}
4307
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004308QualType
Jay Foad39c79802011-01-12 09:06:06 +00004309ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004310 llvm::FoldingSetNodeID ID;
4311 ParenType::Profile(ID, InnerType);
4312
Craig Topper36250ad2014-05-12 05:36:57 +00004313 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004314 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4315 if (T)
4316 return QualType(T, 0);
4317
4318 QualType Canon = InnerType;
4319 if (!Canon.isCanonical()) {
4320 Canon = getCanonicalType(InnerType);
4321 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4322 assert(!CheckT && "Paren canonical type broken");
4323 (void)CheckT;
4324 }
4325
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004326 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004327 Types.push_back(T);
4328 ParenTypes.InsertNode(T, InsertPos);
4329 return QualType(T, 0);
4330}
4331
Leonard Chanc72aaf62019-05-07 03:20:17 +00004332QualType
4333ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
4334 const IdentifierInfo *MacroII) const {
4335 QualType Canon = UnderlyingTy;
4336 if (!Canon.isCanonical())
4337 Canon = getCanonicalType(UnderlyingTy);
4338
4339 auto *newType = new (*this, TypeAlignment)
4340 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4341 Types.push_back(newType);
4342 return QualType(newType, 0);
4343}
4344
Douglas Gregor02085352010-03-31 20:19:30 +00004345QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4346 NestedNameSpecifier *NNS,
4347 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004348 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004349 if (Canon.isNull()) {
4350 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004351 if (CanonNNS != NNS)
4352 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004353 }
4354
4355 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004356 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004357
Craig Topper36250ad2014-05-12 05:36:57 +00004358 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004359 DependentNameType *T
4360 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004361 if (T)
4362 return QualType(T, 0);
4363
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004364 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004365 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004366 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004367 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004368}
4369
Mike Stump11289f42009-09-09 15:08:12 +00004370QualType
John McCallc392f372010-06-11 00:33:02 +00004371ASTContext::getDependentTemplateSpecializationType(
4372 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004373 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004374 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004375 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004376 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004377 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004378 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4379 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004380 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004381}
4382
4383QualType
4384ASTContext::getDependentTemplateSpecializationType(
4385 ElaboratedTypeKeyword Keyword,
4386 NestedNameSpecifier *NNS,
4387 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004388 ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004389 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor6e068012011-02-28 00:04:36 +00004390 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004391
Douglas Gregorc42075a2010-02-04 18:10:26 +00004392 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004393 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004394 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004395
Craig Topper36250ad2014-05-12 05:36:57 +00004396 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004397 DependentTemplateSpecializationType *T
4398 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004399 if (T)
4400 return QualType(T, 0);
4401
John McCallc392f372010-06-11 00:33:02 +00004402 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004403
John McCallc392f372010-06-11 00:33:02 +00004404 ElaboratedTypeKeyword CanonKeyword = Keyword;
4405 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4406
4407 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004408 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004409 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004410 for (unsigned I = 0; I != NumArgs; ++I) {
4411 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4412 if (!CanonArgs[I].structurallyEquals(Args[I]))
4413 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004414 }
4415
John McCallc392f372010-06-11 00:33:02 +00004416 QualType Canon;
4417 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4418 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004419 Name,
4420 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004421
4422 // Find the insert position again.
4423 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4424 }
4425
4426 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4427 sizeof(TemplateArgument) * NumArgs),
4428 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004429 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004430 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004431 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004432 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004433 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004434}
4435
Richard Smith32918772017-02-14 00:25:28 +00004436TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4437 TemplateArgument Arg;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004438 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith32918772017-02-14 00:25:28 +00004439 QualType ArgType = getTypeDeclType(TTP);
4440 if (TTP->isParameterPack())
4441 ArgType = getPackExpansionType(ArgType, None);
4442
4443 Arg = TemplateArgument(ArgType);
4444 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4445 Expr *E = new (*this) DeclRefExpr(
Bruno Ricci5fc4db72018-12-21 14:10:18 +00004446 *this, NTTP, /*enclosing*/ false,
Richard Smith32918772017-02-14 00:25:28 +00004447 NTTP->getType().getNonLValueExprType(*this),
4448 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4449
4450 if (NTTP->isParameterPack())
4451 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4452 None);
4453 Arg = TemplateArgument(E);
4454 } else {
4455 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4456 if (TTP->isParameterPack())
4457 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4458 else
4459 Arg = TemplateArgument(TemplateName(TTP));
4460 }
4461
4462 if (Param->isTemplateParameterPack())
4463 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4464
4465 return Arg;
4466}
4467
Richard Smith43e14d22016-12-23 02:10:11 +00004468void
4469ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4470 SmallVectorImpl<TemplateArgument> &Args) {
4471 Args.reserve(Args.size() + Params->size());
4472
Richard Smith32918772017-02-14 00:25:28 +00004473 for (NamedDecl *Param : *Params)
4474 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004475}
4476
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004477QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004478 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004479 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004480 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004481
Richard Smithb2997f52019-05-21 20:10:50 +00004482 // A deduced type can deduce to a pack, eg
4483 // auto ...x = some_pack;
4484 // That declaration isn't (yet) valid, but is created as part of building an
4485 // init-capture pack:
4486 // [...x = some_pack] {}
4487 assert((Pattern->containsUnexpandedParameterPack() ||
4488 Pattern->getContainedDeducedType()) &&
Douglas Gregord2fa7662010-12-20 02:24:11 +00004489 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004490 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004491 PackExpansionType *T
4492 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4493 if (T)
4494 return QualType(T, 0);
4495
4496 QualType Canon;
4497 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004498 Canon = getCanonicalType(Pattern);
4499 // The canonical type might not contain an unexpanded parameter pack, if it
4500 // contains an alias template specialization which ignores one of its
4501 // parameters.
4502 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004503 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004504
Richard Smith68eea502012-07-16 00:20:35 +00004505 // Find the insert position again, in case we inserted an element into
4506 // PackExpansionTypes and invalidated our insert position.
4507 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4508 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004509 }
4510
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004511 T = new (*this, TypeAlignment)
4512 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004513 Types.push_back(T);
4514 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004515 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004516}
4517
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004518/// CmpProtocolNames - Comparison predicate for sorting protocols
4519/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004520static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4521 ObjCProtocolDecl *const *RHS) {
4522 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004523}
4524
Craig Topper1f26d5b2016-01-03 19:43:23 +00004525static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4526 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004527
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004528 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4529 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004530
Craig Topper1f26d5b2016-01-03 19:43:23 +00004531 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004532 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004533 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004534 return false;
4535 return true;
4536}
4537
Craig Topper6a8c1512015-10-22 01:56:18 +00004538static void
4539SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004540 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004541 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004542
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004543 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004544 for (ObjCProtocolDecl *&P : Protocols)
4545 P = P->getCanonicalDecl();
4546
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004547 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004548 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4549 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004550}
4551
John McCall8b07ec22010-05-15 11:32:37 +00004552QualType ASTContext::getObjCObjectType(QualType BaseType,
4553 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004554 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004555 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004556 llvm::makeArrayRef(Protocols, NumProtocols),
4557 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004558}
4559
4560QualType ASTContext::getObjCObjectType(
4561 QualType baseType,
4562 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004563 ArrayRef<ObjCProtocolDecl *> protocols,
4564 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004565 // If the base type is an interface and there aren't any protocols or
4566 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004567 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4568 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004569 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004570
4571 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004572 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004573 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004574 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004575 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4576 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004577
Douglas Gregore9d95f12015-07-07 03:57:35 +00004578 // Determine the type arguments to be used for canonicalization,
4579 // which may be explicitly specified here or written on the base
4580 // type.
4581 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4582 if (effectiveTypeArgs.empty()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004583 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
Douglas Gregore9d95f12015-07-07 03:57:35 +00004584 effectiveTypeArgs = baseObject->getTypeArgs();
4585 }
John McCallfc93cf92009-10-22 22:37:11 +00004586
Douglas Gregore9d95f12015-07-07 03:57:35 +00004587 // Build the canonical type, which has the canonical base type and a
4588 // sorted-and-uniqued list of protocols and the type arguments
4589 // canonicalized.
4590 QualType canonical;
4591 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4592 effectiveTypeArgs.end(),
4593 [&](QualType type) {
4594 return type.isCanonical();
4595 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004596 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004597 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4598 // Determine the canonical type arguments.
4599 ArrayRef<QualType> canonTypeArgs;
4600 SmallVector<QualType, 4> canonTypeArgsVec;
4601 if (!typeArgsAreCanonical) {
4602 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4603 for (auto typeArg : effectiveTypeArgs)
4604 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4605 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004606 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004607 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004608 }
4609
Douglas Gregore9d95f12015-07-07 03:57:35 +00004610 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4611 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4612 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004613 canonProtocolsVec.append(protocols.begin(), protocols.end());
4614 SortAndUniqueProtocols(canonProtocolsVec);
4615 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004616 } else {
4617 canonProtocols = protocols;
4618 }
4619
4620 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004621 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004622
John McCallfc93cf92009-10-22 22:37:11 +00004623 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004624 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4625 }
4626
Douglas Gregore9d95f12015-07-07 03:57:35 +00004627 unsigned size = sizeof(ObjCObjectTypeImpl);
4628 size += typeArgs.size() * sizeof(QualType);
4629 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4630 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004631 auto *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004632 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4633 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004634
4635 Types.push_back(T);
4636 ObjCObjectTypes.InsertNode(T, InsertPos);
4637 return QualType(T, 0);
4638}
4639
Manman Ren3569eb52016-09-13 17:03:12 +00004640/// Apply Objective-C protocol qualifiers to the given type.
4641/// If this is for the canonical type of a type parameter, we can apply
4642/// protocol qualifiers on the ObjCObjectPointerType.
4643QualType
4644ASTContext::applyObjCProtocolQualifiers(QualType type,
4645 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4646 bool allowOnPointerType) const {
4647 hasError = false;
4648
Eugene Zelenko7855e772018-04-03 00:11:50 +00004649 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
Manman Renc5705ba2016-09-13 17:41:05 +00004650 return getObjCTypeParamType(objT->getDecl(), protocols);
4651 }
4652
Manman Ren3569eb52016-09-13 17:03:12 +00004653 // Apply protocol qualifiers to ObjCObjectPointerType.
4654 if (allowOnPointerType) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004655 if (const auto *objPtr =
4656 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
Manman Ren3569eb52016-09-13 17:03:12 +00004657 const ObjCObjectType *objT = objPtr->getObjectType();
4658 // Merge protocol lists and construct ObjCObjectType.
4659 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4660 protocolsVec.append(objT->qual_begin(),
4661 objT->qual_end());
4662 protocolsVec.append(protocols.begin(), protocols.end());
4663 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4664 type = getObjCObjectType(
4665 objT->getBaseType(),
4666 objT->getTypeArgsAsWritten(),
4667 protocols,
4668 objT->isKindOfTypeAsWritten());
4669 return getObjCObjectPointerType(type);
4670 }
4671 }
4672
4673 // Apply protocol qualifiers to ObjCObjectType.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004674 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
Manman Ren3569eb52016-09-13 17:03:12 +00004675 // FIXME: Check for protocols to which the class type is already
4676 // known to conform.
4677
4678 return getObjCObjectType(objT->getBaseType(),
4679 objT->getTypeArgsAsWritten(),
4680 protocols,
4681 objT->isKindOfTypeAsWritten());
4682 }
4683
4684 // If the canonical type is ObjCObjectType, ...
4685 if (type->isObjCObjectType()) {
4686 // Silently overwrite any existing protocol qualifiers.
4687 // TODO: determine whether that's the right thing to do.
4688
4689 // FIXME: Check for protocols to which the class type is already
4690 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004691 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004692 }
4693
4694 // id<protocol-list>
4695 if (type->isObjCIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004696 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004697 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004698 objPtr->isKindOfType());
4699 return getObjCObjectPointerType(type);
4700 }
4701
4702 // Class<protocol-list>
4703 if (type->isObjCClassType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004704 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004705 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004706 objPtr->isKindOfType());
4707 return getObjCObjectPointerType(type);
4708 }
4709
4710 hasError = true;
4711 return type;
4712}
4713
Manman Rene6be26c2016-09-13 17:25:08 +00004714QualType
4715ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
Volodymyr Sapsaib95d4c32019-10-11 21:21:02 +00004716 ArrayRef<ObjCProtocolDecl *> protocols) const {
Manman Rene6be26c2016-09-13 17:25:08 +00004717 // Look in the folding set for an existing type.
4718 llvm::FoldingSetNodeID ID;
4719 ObjCTypeParamType::Profile(ID, Decl, protocols);
4720 void *InsertPos = nullptr;
4721 if (ObjCTypeParamType *TypeParam =
4722 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4723 return QualType(TypeParam, 0);
4724
Volodymyr Sapsaib95d4c32019-10-11 21:21:02 +00004725 // We canonicalize to the underlying type.
4726 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
4727 if (!protocols.empty()) {
4728 // Apply the protocol qualifers.
4729 bool hasError;
4730 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
4731 Canonical, protocols, hasError, true /*allowOnPointerType*/));
4732 assert(!hasError && "Error when apply protocol qualifier to bound type");
Manman Rene6be26c2016-09-13 17:25:08 +00004733 }
4734
4735 unsigned size = sizeof(ObjCTypeParamType);
4736 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4737 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004738 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
Manman Rene6be26c2016-09-13 17:25:08 +00004739
4740 Types.push_back(newType);
4741 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4742 return QualType(newType, 0);
4743}
4744
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004745/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4746/// protocol list adopt all protocols in QT's qualified-id protocol
4747/// list.
4748bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4749 ObjCInterfaceDecl *IC) {
4750 if (!QT->isObjCQualifiedIdType())
4751 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004752
Eugene Zelenko7855e772018-04-03 00:11:50 +00004753 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004754 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004755 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004756 if (!IC->ClassImplementsProtocol(Proto, false))
4757 return false;
4758 }
4759 return true;
4760 }
4761 return false;
4762}
4763
4764/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4765/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4766/// of protocols.
4767bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4768 ObjCInterfaceDecl *IDecl) {
4769 if (!QT->isObjCQualifiedIdType())
4770 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004771 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004772 if (!OPT)
4773 return false;
4774 if (!IDecl->hasDefinition())
4775 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004776 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4777 CollectInheritedProtocols(IDecl, InheritedProtocols);
4778 if (InheritedProtocols.empty())
4779 return false;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004780 // Check that if every protocol in list of id<plist> conforms to a protocol
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004781 // of IDecl's, then bridge casting is ok.
4782 bool Conforms = false;
4783 for (auto *Proto : OPT->quals()) {
4784 Conforms = false;
4785 for (auto *PI : InheritedProtocols) {
4786 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4787 Conforms = true;
4788 break;
4789 }
4790 }
4791 if (!Conforms)
4792 break;
4793 }
4794 if (Conforms)
4795 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004796
Aaron Ballman83731462014-03-17 16:14:00 +00004797 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004798 // If both the right and left sides have qualifiers.
4799 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004800 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004801 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004802 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004803 break;
4804 }
4805 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004806 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004807 }
4808 return true;
4809}
4810
John McCall8b07ec22010-05-15 11:32:37 +00004811/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4812/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004813QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004814 llvm::FoldingSetNodeID ID;
4815 ObjCObjectPointerType::Profile(ID, ObjectT);
4816
Craig Topper36250ad2014-05-12 05:36:57 +00004817 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004818 if (ObjCObjectPointerType *QT =
4819 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4820 return QualType(QT, 0);
4821
4822 // Find the canonical object type.
4823 QualType Canonical;
4824 if (!ObjectT.isCanonical()) {
4825 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4826
4827 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004828 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4829 }
4830
Douglas Gregorf85bee62010-02-08 22:59:26 +00004831 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004832 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004833 auto *QType =
John McCall8b07ec22010-05-15 11:32:37 +00004834 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004835
Steve Narofffb4330f2009-06-17 22:40:22 +00004836 Types.push_back(QType);
4837 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004838 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004839}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004840
Douglas Gregor1c283312010-08-11 12:19:30 +00004841/// getObjCInterfaceType - Return the unique reference to the type for the
4842/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004843QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4844 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004845 if (Decl->TypeForDecl)
4846 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004847
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004848 if (PrevDecl) {
4849 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4850 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4851 return QualType(PrevDecl->TypeForDecl, 0);
4852 }
4853
Douglas Gregor7671e532011-12-16 16:34:57 +00004854 // Prefer the definition, if there is one.
4855 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4856 Decl = Def;
Fangrui Song6907ce22018-07-30 19:24:48 +00004857
Douglas Gregor1c283312010-08-11 12:19:30 +00004858 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004859 auto *T = new (Mem) ObjCInterfaceType(Decl);
Douglas Gregor1c283312010-08-11 12:19:30 +00004860 Decl->TypeForDecl = T;
4861 Types.push_back(T);
4862 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004863}
4864
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004865/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4866/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004867/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004868/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004869/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004870QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004871 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004872 if (tofExpr->isTypeDependent()) {
4873 llvm::FoldingSetNodeID ID;
4874 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004875
Craig Topper36250ad2014-05-12 05:36:57 +00004876 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004877 DependentTypeOfExprType *Canon
4878 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4879 if (Canon) {
4880 // We already have a "canonical" version of an identical, dependent
4881 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004882 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004883 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004884 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004885 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004886 Canon
4887 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004888 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4889 toe = Canon;
4890 }
4891 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004892 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004893 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004894 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004895 Types.push_back(toe);
4896 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004897}
4898
Steve Naroffa773cd52007-08-01 18:02:17 +00004899/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004900/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004901/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004902/// an issue. This doesn't affect the type checker, since it operates
4903/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004904QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004905 QualType Canonical = getCanonicalType(tofType);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004906 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004907 Types.push_back(tot);
4908 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004909}
4910
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004911/// Unlike many "get<Type>" functions, we don't unique DecltypeType
Richard Smith8eb1d322014-06-05 20:13:13 +00004912/// nodes. This would never be helpful, since each such type has its own
4913/// expression, and would not give a significant memory saving, since there
4914/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004915QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004916 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004917
4918 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004919 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004920 // unique dependent type. Two such decltype-specifiers refer to the same
4921 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004922 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004923 llvm::FoldingSetNodeID ID;
4924 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004925
Craig Topper36250ad2014-05-12 05:36:57 +00004926 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004927 DependentDecltypeType *Canon
4928 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004929 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004930 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004931 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004932 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004933 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004934 dt = new (*this, TypeAlignment)
4935 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004936 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004937 dt = new (*this, TypeAlignment)
4938 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004939 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004940 Types.push_back(dt);
4941 return QualType(dt, 0);
4942}
4943
Alexis Hunte852b102011-05-24 22:41:36 +00004944/// getUnaryTransformationType - We don't unique these, since the memory
4945/// savings are minimal and these are rare.
4946QualType ASTContext::getUnaryTransformType(QualType BaseType,
4947 QualType UnderlyingType,
4948 UnaryTransformType::UTTKind Kind)
4949 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004950 UnaryTransformType *ut = nullptr;
4951
4952 if (BaseType->isDependentType()) {
4953 // Look in the folding set for an existing type.
4954 llvm::FoldingSetNodeID ID;
4955 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4956
4957 void *InsertPos = nullptr;
4958 DependentUnaryTransformType *Canon
4959 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4960
4961 if (!Canon) {
4962 // Build a new, canonical __underlying_type(type) type.
4963 Canon = new (*this, TypeAlignment)
4964 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4965 Kind);
4966 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4967 }
4968 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4969 QualType(), Kind,
4970 QualType(Canon, 0));
4971 } else {
4972 QualType CanonType = getCanonicalType(UnderlyingType);
4973 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4974 UnderlyingType, Kind,
4975 CanonType);
4976 }
4977 Types.push_back(ut);
4978 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004979}
4980
Richard Smith2a7d4812013-05-04 07:00:32 +00004981/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4982/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4983/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004984QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Richard Smithb2997f52019-05-21 20:10:50 +00004985 bool IsDependent, bool IsPack) const {
4986 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
Richard Smithe301ba22015-11-11 02:02:15 +00004987 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004988 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004989
Richard Smith2a7d4812013-05-04 07:00:32 +00004990 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004991 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004992 llvm::FoldingSetNodeID ID;
Richard Smithb2997f52019-05-21 20:10:50 +00004993 AutoType::Profile(ID, DeducedType, Keyword, IsDependent, IsPack);
Richard Smith2a7d4812013-05-04 07:00:32 +00004994 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4995 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004996
Eugene Zelenko7855e772018-04-03 00:11:50 +00004997 auto *AT = new (*this, TypeAlignment)
Richard Smithb2997f52019-05-21 20:10:50 +00004998 AutoType(DeducedType, Keyword, IsDependent, IsPack);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004999 Types.push_back(AT);
5000 if (InsertPos)
5001 AutoTypes.InsertNode(AT, InsertPos);
5002 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00005003}
5004
Richard Smith600b5262017-01-26 20:40:47 +00005005/// Return the uniqued reference to the deduced template specialization type
5006/// which has been deduced to the given type, or to the canonical undeduced
5007/// such type, or the canonical deduced-but-dependent such type.
5008QualType ASTContext::getDeducedTemplateSpecializationType(
5009 TemplateName Template, QualType DeducedType, bool IsDependent) const {
5010 // Look in the folding set for an existing type.
5011 void *InsertPos = nullptr;
5012 llvm::FoldingSetNodeID ID;
5013 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
5014 IsDependent);
5015 if (DeducedTemplateSpecializationType *DTST =
5016 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5017 return QualType(DTST, 0);
5018
Eugene Zelenko7855e772018-04-03 00:11:50 +00005019 auto *DTST = new (*this, TypeAlignment)
Richard Smith600b5262017-01-26 20:40:47 +00005020 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5021 Types.push_back(DTST);
5022 if (InsertPos)
5023 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5024 return QualType(DTST, 0);
5025}
5026
Eli Friedman0dfb8892011-10-06 23:00:33 +00005027/// getAtomicType - Return the uniqued reference to the atomic type for
5028/// the given value type.
5029QualType ASTContext::getAtomicType(QualType T) const {
5030 // Unique pointers, to guarantee there is only one pointer of a particular
5031 // structure.
5032 llvm::FoldingSetNodeID ID;
5033 AtomicType::Profile(ID, T);
5034
Craig Topper36250ad2014-05-12 05:36:57 +00005035 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00005036 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5037 return QualType(AT, 0);
5038
5039 // If the atomic value type isn't canonical, this won't be a canonical type
5040 // either, so fill in the canonical type field.
5041 QualType Canonical;
5042 if (!T.isCanonical()) {
5043 Canonical = getAtomicType(getCanonicalType(T));
5044
5045 // Get the new insert position for the node we care about.
5046 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00005047 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00005048 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00005049 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
Eli Friedman0dfb8892011-10-06 23:00:33 +00005050 Types.push_back(New);
5051 AtomicTypes.InsertNode(New, InsertPos);
5052 return QualType(New, 0);
5053}
5054
Richard Smith02e85f32011-04-14 22:09:26 +00005055/// getAutoDeductType - Get type pattern for deducing against 'auto'.
5056QualType ASTContext::getAutoDeductType() const {
5057 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00005058 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00005059 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Richard Smithb2997f52019-05-21 20:10:50 +00005060 /*dependent*/false, /*pack*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00005061 0);
Richard Smith02e85f32011-04-14 22:09:26 +00005062 return AutoDeductTy;
5063}
5064
5065/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5066QualType ASTContext::getAutoRRefDeductType() const {
5067 if (AutoRRefDeductTy.isNull())
5068 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
5069 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5070 return AutoRRefDeductTy;
5071}
5072
Chris Lattnerfb072462007-01-23 05:45:31 +00005073/// getTagDeclType - Return the unique reference to the type for the
5074/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00005075QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00005076 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00005077 // FIXME: What is the design on getTagDeclType when it requires casting
5078 // away const? mutable?
5079 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00005080}
5081
Mike Stump11289f42009-09-09 15:08:12 +00005082/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5083/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5084/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00005085CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00005086 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00005087}
Chris Lattnerfb072462007-01-23 05:45:31 +00005088
Fangrui Song6907ce22018-07-30 19:24:48 +00005089/// Return the unique signed counterpart of the integer type
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00005090/// corresponding to size_t.
5091CanQualType ASTContext::getSignedSizeType() const {
5092 return getFromTargetType(Target->getSignedSizeType());
5093}
5094
Hans Wennborg27541db2011-10-27 08:29:09 +00005095/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5096CanQualType ASTContext::getIntMaxType() const {
5097 return getFromTargetType(Target->getIntMaxType());
5098}
5099
5100/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5101CanQualType ASTContext::getUIntMaxType() const {
5102 return getFromTargetType(Target->getUIntMaxType());
5103}
5104
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00005105/// getSignedWCharType - Return the type of "signed wchar_t".
5106/// Used when in C++, as a GCC extension.
5107QualType ASTContext::getSignedWCharType() const {
5108 // FIXME: derive from "Target" ?
5109 return WCharTy;
5110}
5111
5112/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5113/// Used when in C++, as a GCC extension.
5114QualType ASTContext::getUnsignedWCharType() const {
5115 // FIXME: derive from "Target" ?
5116 return UnsignedIntTy;
5117}
5118
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00005119QualType ASTContext::getIntPtrType() const {
5120 return getFromTargetType(Target->getIntPtrType());
5121}
5122
5123QualType ASTContext::getUIntPtrType() const {
5124 return getCorrespondingUnsignedType(getIntPtrType());
5125}
5126
Hans Wennborg27541db2011-10-27 08:29:09 +00005127/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005128/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5129QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00005130 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005131}
5132
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005133/// Return the unique unsigned counterpart of "ptrdiff_t"
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00005134/// integer type. The standard (C11 7.21.6.1p7) refers to this type
5135/// in the definition of %tu format specifier.
5136QualType ASTContext::getUnsignedPointerDiffType() const {
5137 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5138}
5139
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005140/// Return the unique type for "pid_t" defined in
Eli Friedman4e91899e2012-11-27 02:58:24 +00005141/// <sys/types.h>. We need this to compute the correct type for vfork().
5142QualType ASTContext::getProcessIDType() const {
5143 return getFromTargetType(Target->getProcessIDType());
5144}
5145
Chris Lattnera21ad802008-04-02 05:18:44 +00005146//===----------------------------------------------------------------------===//
5147// Type Operators
5148//===----------------------------------------------------------------------===//
5149
Jay Foad39c79802011-01-12 09:06:06 +00005150CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00005151 // Push qualifiers into arrays, and then discard any remaining
5152 // qualifiers.
5153 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00005154 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00005155 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00005156 QualType Result;
5157 if (isa<ArrayType>(Ty)) {
5158 Result = getArrayDecayedType(QualType(Ty,0));
5159 } else if (isa<FunctionType>(Ty)) {
5160 Result = getPointerType(QualType(Ty, 0));
5161 } else {
5162 Result = QualType(Ty, 0);
5163 }
5164
5165 return CanQualType::CreateUnsafe(Result);
5166}
5167
John McCall6c9dd522011-01-18 07:41:22 +00005168QualType ASTContext::getUnqualifiedArrayType(QualType type,
5169 Qualifiers &quals) {
5170 SplitQualType splitType = type.getSplitUnqualifiedType();
5171
5172 // FIXME: getSplitUnqualifiedType() actually walks all the way to
5173 // the unqualified desugared type and then drops it on the floor.
5174 // We then have to strip that sugar back off with
5175 // getUnqualifiedDesugaredType(), which is silly.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005176 const auto *AT =
5177 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00005178
5179 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005180 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00005181 quals = splitType.Quals;
5182 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005183 }
5184
John McCall6c9dd522011-01-18 07:41:22 +00005185 // Otherwise, recurse on the array's element type.
5186 QualType elementType = AT->getElementType();
5187 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5188
5189 // If that didn't change the element type, AT has no qualifiers, so we
5190 // can just use the results in splitType.
5191 if (elementType == unqualElementType) {
5192 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00005193 quals = splitType.Quals;
5194 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00005195 }
5196
5197 // Otherwise, add in the qualifiers from the outermost type, then
5198 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00005199 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005200
Eugene Zelenko7855e772018-04-03 00:11:50 +00005201 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005202 return getConstantArrayType(unqualElementType, CAT->getSize(),
Richard Smith772e2662019-10-04 01:25:59 +00005203 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005204 }
5205
Eugene Zelenko7855e772018-04-03 00:11:50 +00005206 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005207 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005208 }
5209
Eugene Zelenko7855e772018-04-03 00:11:50 +00005210 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005211 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00005212 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005213 VAT->getSizeModifier(),
5214 VAT->getIndexTypeCVRQualifiers(),
5215 VAT->getBracketsRange());
5216 }
5217
Eugene Zelenko7855e772018-04-03 00:11:50 +00005218 const auto *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00005219 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005220 DSAT->getSizeModifier(), 0,
5221 SourceRange());
5222}
5223
Richard Smitha3405ff2018-07-11 00:19:19 +00005224/// Attempt to unwrap two types that may both be array types with the same bound
5225/// (or both be array types of unknown bound) for the purpose of comparing the
5226/// cv-decomposition of two types per C++ [conv.qual].
Richard Smith5407d4f2018-07-18 20:13:36 +00005227bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5228 bool UnwrappedAny = false;
Richard Smitha3405ff2018-07-11 00:19:19 +00005229 while (true) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005230 auto *AT1 = getAsArrayType(T1);
5231 if (!AT1) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005232
Richard Smith5407d4f2018-07-18 20:13:36 +00005233 auto *AT2 = getAsArrayType(T2);
5234 if (!AT2) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005235
5236 // If we don't have two array types with the same constant bound nor two
5237 // incomplete array types, we've unwrapped everything we can.
5238 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5239 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5240 if (!CAT2 || CAT1->getSize() != CAT2->getSize())
Richard Smith5407d4f2018-07-18 20:13:36 +00005241 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005242 } else if (!isa<IncompleteArrayType>(AT1) ||
5243 !isa<IncompleteArrayType>(AT2)) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005244 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005245 }
5246
5247 T1 = AT1->getElementType();
5248 T2 = AT2->getElementType();
Richard Smith5407d4f2018-07-18 20:13:36 +00005249 UnwrappedAny = true;
Richard Smitha3405ff2018-07-11 00:19:19 +00005250 }
5251}
5252
5253/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5254///
5255/// If T1 and T2 are both pointer types of the same kind, or both array types
5256/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5257/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5258///
5259/// This function will typically be called in a loop that successively
5260/// "unwraps" pointer and pointer-to-member types to compare them at each
5261/// level.
5262///
5263/// \return \c true if a pointer type was unwrapped, \c false if we reached a
5264/// pair of types that can't be unwrapped further.
5265bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005266 UnwrapSimilarArrayTypes(T1, T2);
Richard Smitha3405ff2018-07-11 00:19:19 +00005267
Eugene Zelenko7855e772018-04-03 00:11:50 +00005268 const auto *T1PtrType = T1->getAs<PointerType>();
5269 const auto *T2PtrType = T2->getAs<PointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005270 if (T1PtrType && T2PtrType) {
5271 T1 = T1PtrType->getPointeeType();
5272 T2 = T2PtrType->getPointeeType();
5273 return true;
5274 }
Richard Smith5407d4f2018-07-18 20:13:36 +00005275
Eugene Zelenko7855e772018-04-03 00:11:50 +00005276 const auto *T1MPType = T1->getAs<MemberPointerType>();
5277 const auto *T2MPType = T2->getAs<MemberPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00005278 if (T1MPType && T2MPType &&
5279 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005280 QualType(T2MPType->getClass(), 0))) {
5281 T1 = T1MPType->getPointeeType();
5282 T2 = T2MPType->getPointeeType();
5283 return true;
5284 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005285
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005286 if (getLangOpts().ObjC) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005287 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5288 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005289 if (T1OPType && T2OPType) {
5290 T1 = T1OPType->getPointeeType();
5291 T2 = T2OPType->getPointeeType();
5292 return true;
5293 }
5294 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005295
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005296 // FIXME: Block pointers, too?
Fangrui Song6907ce22018-07-30 19:24:48 +00005297
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005298 return false;
5299}
5300
Richard Smitha3405ff2018-07-11 00:19:19 +00005301bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5302 while (true) {
5303 Qualifiers Quals;
5304 T1 = getUnqualifiedArrayType(T1, Quals);
5305 T2 = getUnqualifiedArrayType(T2, Quals);
5306 if (hasSameType(T1, T2))
5307 return true;
5308 if (!UnwrapSimilarTypes(T1, T2))
5309 return false;
5310 }
5311}
5312
5313bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5314 while (true) {
5315 Qualifiers Quals1, Quals2;
5316 T1 = getUnqualifiedArrayType(T1, Quals1);
5317 T2 = getUnqualifiedArrayType(T2, Quals2);
5318
5319 Quals1.removeCVRQualifiers();
5320 Quals2.removeCVRQualifiers();
5321 if (Quals1 != Quals2)
5322 return false;
5323
5324 if (hasSameType(T1, T2))
5325 return true;
5326
5327 if (!UnwrapSimilarTypes(T1, T2))
5328 return false;
5329 }
5330}
5331
Jay Foad39c79802011-01-12 09:06:06 +00005332DeclarationNameInfo
5333ASTContext::getNameForTemplate(TemplateName Name,
5334 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005335 switch (Name.getKind()) {
5336 case TemplateName::QualifiedTemplate:
5337 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005338 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00005339 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5340 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005341
John McCalld9dfe3a2011-06-30 08:33:18 +00005342 case TemplateName::OverloadedTemplate: {
5343 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5344 // DNInfo work in progress: CHECKME: what about DNLoc?
5345 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5346 }
5347
Richard Smithb23c5e82019-05-09 03:31:27 +00005348 case TemplateName::AssumedTemplate: {
5349 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5350 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5351 }
5352
John McCalld9dfe3a2011-06-30 08:33:18 +00005353 case TemplateName::DependentTemplate: {
5354 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005355 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00005356 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005357 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5358 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00005359 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005360 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5361 // DNInfo work in progress: FIXME: source locations?
5362 DeclarationNameLoc DNLoc;
5363 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5364 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5365 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00005366 }
5367 }
5368
John McCalld9dfe3a2011-06-30 08:33:18 +00005369 case TemplateName::SubstTemplateTemplateParm: {
5370 SubstTemplateTemplateParmStorage *subst
5371 = Name.getAsSubstTemplateTemplateParm();
5372 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5373 NameLoc);
5374 }
5375
5376 case TemplateName::SubstTemplateTemplateParmPack: {
5377 SubstTemplateTemplateParmPackStorage *subst
5378 = Name.getAsSubstTemplateTemplateParmPack();
5379 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5380 NameLoc);
5381 }
5382 }
5383
5384 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005385}
5386
Jay Foad39c79802011-01-12 09:06:06 +00005387TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005388 switch (Name.getKind()) {
5389 case TemplateName::QualifiedTemplate:
5390 case TemplateName::Template: {
5391 TemplateDecl *Template = Name.getAsTemplateDecl();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005392 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005393 Template = getCanonicalTemplateTemplateParmDecl(TTP);
Fangrui Song6907ce22018-07-30 19:24:48 +00005394
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005395 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005396 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005397 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005398
John McCalld9dfe3a2011-06-30 08:33:18 +00005399 case TemplateName::OverloadedTemplate:
Richard Smithb23c5e82019-05-09 03:31:27 +00005400 case TemplateName::AssumedTemplate:
5401 llvm_unreachable("cannot canonicalize unresolved template");
Mike Stump11289f42009-09-09 15:08:12 +00005402
John McCalld9dfe3a2011-06-30 08:33:18 +00005403 case TemplateName::DependentTemplate: {
5404 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5405 assert(DTN && "Non-dependent template names must refer to template decls.");
5406 return DTN->CanonicalTemplateName;
5407 }
5408
5409 case TemplateName::SubstTemplateTemplateParm: {
5410 SubstTemplateTemplateParmStorage *subst
5411 = Name.getAsSubstTemplateTemplateParm();
5412 return getCanonicalTemplateName(subst->getReplacement());
5413 }
5414
5415 case TemplateName::SubstTemplateTemplateParmPack: {
5416 SubstTemplateTemplateParmPackStorage *subst
5417 = Name.getAsSubstTemplateTemplateParmPack();
5418 TemplateTemplateParmDecl *canonParameter
5419 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5420 TemplateArgument canonArgPack
5421 = getCanonicalTemplateArgument(subst->getArgumentPack());
5422 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5423 }
5424 }
5425
5426 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005427}
5428
Douglas Gregoradee3e32009-11-11 23:06:43 +00005429bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5430 X = getCanonicalTemplateName(X);
5431 Y = getCanonicalTemplateName(Y);
5432 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5433}
5434
Mike Stump11289f42009-09-09 15:08:12 +00005435TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005436ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005437 switch (Arg.getKind()) {
5438 case TemplateArgument::Null:
5439 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005440
Douglas Gregora8e02e72009-07-28 23:00:59 +00005441 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005442 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005443
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005444 case TemplateArgument::Declaration: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005445 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005446 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005447 }
Mike Stump11289f42009-09-09 15:08:12 +00005448
Eli Friedmanb826a002012-09-26 02:36:12 +00005449 case TemplateArgument::NullPtr:
5450 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5451 /*isNullPtr*/true);
5452
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005453 case TemplateArgument::Template:
5454 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005455
5456 case TemplateArgument::TemplateExpansion:
5457 return TemplateArgument(getCanonicalTemplateName(
5458 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005459 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005460
Douglas Gregora8e02e72009-07-28 23:00:59 +00005461 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005462 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005463
Douglas Gregora8e02e72009-07-28 23:00:59 +00005464 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005465 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005466
Douglas Gregora8e02e72009-07-28 23:00:59 +00005467 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005468 if (Arg.pack_size() == 0)
5469 return Arg;
Fangrui Song6907ce22018-07-30 19:24:48 +00005470
Eugene Zelenko7855e772018-04-03 00:11:50 +00005471 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005472 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005473 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005474 AEnd = Arg.pack_end();
5475 A != AEnd; (void)++A, ++Idx)
5476 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005477
Benjamin Kramercce63472015-08-05 09:40:22 +00005478 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005479 }
5480 }
5481
5482 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005483 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005484}
5485
Douglas Gregor333489b2009-03-27 23:10:48 +00005486NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005487ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005488 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005489 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005490
5491 switch (NNS->getKind()) {
5492 case NestedNameSpecifier::Identifier:
5493 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005494 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005495 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5496 NNS->getAsIdentifier());
5497
5498 case NestedNameSpecifier::Namespace:
5499 // A namespace is canonical; build a nested-name-specifier with
5500 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005501 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005502 NNS->getAsNamespace()->getOriginalNamespace());
5503
5504 case NestedNameSpecifier::NamespaceAlias:
5505 // A namespace is canonical; build a nested-name-specifier with
5506 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005507 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005508 NNS->getAsNamespaceAlias()->getNamespace()
5509 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005510
5511 case NestedNameSpecifier::TypeSpec:
5512 case NestedNameSpecifier::TypeSpecWithTemplate: {
5513 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Fangrui Song6907ce22018-07-30 19:24:48 +00005514
Douglas Gregor3ade5702010-11-04 00:09:33 +00005515 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5516 // break it apart into its prefix and identifier, then reconsititute those
5517 // as the canonical nested-name-specifier. This is required to canonicalize
5518 // a dependent nested-name-specifier involving typedefs of dependent-name
5519 // types, e.g.,
5520 // typedef typename T::type T1;
5521 // typedef typename T1::type T2;
Eugene Zelenko7855e772018-04-03 00:11:50 +00005522 if (const auto *DNT = T->getAs<DependentNameType>())
Fangrui Song6907ce22018-07-30 19:24:48 +00005523 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005524 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005525
Eli Friedman5358a0a2012-03-03 04:09:56 +00005526 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5527 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5528 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005529 return NestedNameSpecifier::Create(*this, nullptr, false,
5530 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005531 }
5532
5533 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005534 case NestedNameSpecifier::Super:
5535 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005536 return NNS;
5537 }
5538
David Blaikie8a40f702012-01-17 06:56:22 +00005539 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005540}
5541
Jay Foad39c79802011-01-12 09:06:06 +00005542const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005543 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005544 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005545 // Handle the common positive case fast.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005546 if (const auto *AT = dyn_cast<ArrayType>(T))
Chris Lattner7adf0762008-08-04 07:31:14 +00005547 return AT;
5548 }
Mike Stump11289f42009-09-09 15:08:12 +00005549
John McCall8ccfcb52009-09-24 19:53:00 +00005550 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005551 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005552 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005553
John McCall8ccfcb52009-09-24 19:53:00 +00005554 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005555 // implements C99 6.7.3p8: "If the specification of an array type includes
5556 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005557
Chris Lattner7adf0762008-08-04 07:31:14 +00005558 // If we get here, we either have type qualifiers on the type, or we have
5559 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005560 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005561
John McCall33ddac02011-01-19 10:06:00 +00005562 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005563 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005564
Chris Lattner7adf0762008-08-04 07:31:14 +00005565 // If we have a simple case, just return now.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005566 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005567 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005568 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005569
Chris Lattner7adf0762008-08-04 07:31:14 +00005570 // Otherwise, we have an array and we have qualifiers on it. Push the
5571 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005572 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005573
Eugene Zelenko7855e772018-04-03 00:11:50 +00005574 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005575 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
Richard Smith772e2662019-10-04 01:25:59 +00005576 CAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005577 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005578 CAT->getIndexTypeCVRQualifiers()));
Eugene Zelenko7855e772018-04-03 00:11:50 +00005579 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005580 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5581 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005582 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005583
Eugene Zelenko7855e772018-04-03 00:11:50 +00005584 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
Douglas Gregor4619e432008-12-05 23:32:09 +00005585 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005586 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005587 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005588 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005589 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005590 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005591
Eugene Zelenko7855e772018-04-03 00:11:50 +00005592 const auto *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005593 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005594 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005595 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005596 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005597 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005598}
5599
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005600QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005601 if (T->isArrayType() || T->isFunctionType())
5602 return getDecayedType(T);
5603 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005604}
5605
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005606QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005607 T = getVariableArrayDecayedType(T);
5608 T = getAdjustedParameterType(T);
5609 return T.getUnqualifiedType();
5610}
5611
David Majnemerd09a51c2015-03-03 01:50:05 +00005612QualType ASTContext::getExceptionObjectType(QualType T) const {
5613 // C++ [except.throw]p3:
5614 // A throw-expression initializes a temporary object, called the exception
5615 // object, the type of which is determined by removing any top-level
5616 // cv-qualifiers from the static type of the operand of throw and adjusting
5617 // the type from "array of T" or "function returning T" to "pointer to T"
5618 // or "pointer to function returning T", [...]
5619 T = getVariableArrayDecayedType(T);
5620 if (T->isArrayType() || T->isFunctionType())
5621 T = getDecayedType(T);
5622 return T.getUnqualifiedType();
5623}
5624
Chris Lattnera21ad802008-04-02 05:18:44 +00005625/// getArrayDecayedType - Return the properly qualified result of decaying the
5626/// specified array type to a pointer. This operation is non-trivial when
5627/// handling typedefs etc. The canonical type of "T" must be an array type,
5628/// this returns a pointer to a properly qualified element of the array.
5629///
5630/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005631QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005632 // Get the element type with 'getAsArrayType' so that we don't lose any
5633 // typedefs in the element type of the array. This also handles propagation
5634 // of type qualifiers from the array type into the element type if present
5635 // (C99 6.7.3p8).
5636 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5637 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005638
Chris Lattner7adf0762008-08-04 07:31:14 +00005639 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005640
5641 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005642 QualType Result = getQualifiedType(PtrTy,
5643 PrettyArrayType->getIndexTypeQualifiers());
5644
5645 // int x[_Nullable] -> int * _Nullable
5646 if (auto Nullability = Ty->getNullability(*this)) {
5647 Result = const_cast<ASTContext *>(this)->getAttributedType(
5648 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5649 }
5650 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005651}
5652
John McCall33ddac02011-01-19 10:06:00 +00005653QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5654 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005655}
5656
John McCall33ddac02011-01-19 10:06:00 +00005657QualType ASTContext::getBaseElementType(QualType type) const {
5658 Qualifiers qs;
5659 while (true) {
5660 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005661 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005662 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005663
John McCall33ddac02011-01-19 10:06:00 +00005664 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005665 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005666 }
Mike Stump11289f42009-09-09 15:08:12 +00005667
John McCall33ddac02011-01-19 10:06:00 +00005668 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005669}
5670
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005671/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005672uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005673ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5674 uint64_t ElementCount = 1;
5675 do {
5676 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005677 CA = dyn_cast_or_null<ConstantArrayType>(
5678 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005679 } while (CA);
5680 return ElementCount;
5681}
5682
Steve Naroff0af91202007-04-27 21:51:21 +00005683/// getFloatingRank - Return a relative rank for floating point types.
5684/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005685static FloatingRank getFloatingRank(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005686 if (const auto *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005687 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005688
Simon Pilgrimeed4b122019-10-02 11:48:06 +00005689 switch (T->castAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005690 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005691 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005692 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005693 case BuiltinType::Float: return FloatRank;
5694 case BuiltinType::Double: return DoubleRank;
5695 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005696 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005697 }
5698}
5699
Mike Stump11289f42009-09-09 15:08:12 +00005700/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5701/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005702/// 'typeDomain' is a real floating point or complex type.
5703/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005704QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5705 QualType Domain) const {
5706 FloatingRank EltRank = getFloatingRank(Size);
5707 if (Domain->isComplexType()) {
5708 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005709 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005710 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005711 case FloatRank: return FloatComplexTy;
5712 case DoubleRank: return DoubleComplexTy;
5713 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005714 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005715 }
Steve Naroff0af91202007-04-27 21:51:21 +00005716 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005717
5718 assert(Domain->isRealFloatingType() && "Unknown domain!");
5719 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005720 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005721 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005722 case FloatRank: return FloatTy;
5723 case DoubleRank: return DoubleTy;
5724 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005725 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005726 }
David Blaikief47fa302012-01-17 02:30:50 +00005727 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005728}
5729
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005730/// getFloatingTypeOrder - Compare the rank of the two specified floating
5731/// point types, ignoring the domain of the type (i.e. 'double' ==
5732/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005733/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005734int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005735 FloatingRank LHSR = getFloatingRank(LHS);
5736 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005737
Chris Lattnerb90739d2008-04-06 23:38:49 +00005738 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005739 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005740 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005741 return 1;
5742 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005743}
5744
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +00005745int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
5746 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
5747 return 0;
5748 return getFloatingTypeOrder(LHS, RHS);
5749}
5750
Chris Lattner76a00cf2008-04-06 22:59:24 +00005751/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5752/// routine will assert if passed a built-in type that isn't an integer or enum,
5753/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005754unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005755 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005756
Chris Lattner76a00cf2008-04-06 22:59:24 +00005757 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005758 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005759 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005760 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005761 case BuiltinType::Char_S:
5762 case BuiltinType::Char_U:
5763 case BuiltinType::SChar:
5764 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005765 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005766 case BuiltinType::Short:
5767 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005768 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005769 case BuiltinType::Int:
5770 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005771 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005772 case BuiltinType::Long:
5773 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005774 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005775 case BuiltinType::LongLong:
5776 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005777 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005778 case BuiltinType::Int128:
5779 case BuiltinType::UInt128:
5780 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005781 }
5782}
5783
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005784/// Whether this is a promotable bitfield reference according
Eli Friedman629ffb92009-08-20 04:21:42 +00005785/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5786///
5787/// \returns the type this bit-field will promote to, or NULL if no
5788/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005789QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005790 if (E->isTypeDependent() || E->isValueDependent())
Eugene Zelenko7855e772018-04-03 00:11:50 +00005791 return {};
Richard Smith5b571672014-09-24 23:55:00 +00005792
Richard Smithaadb2542018-06-28 21:17:55 +00005793 // C++ [conv.prom]p5:
5794 // If the bit-field has an enumerated type, it is treated as any other
5795 // value of that type for promotion purposes.
5796 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5797 return {};
5798
Richard Smith5b571672014-09-24 23:55:00 +00005799 // FIXME: We should not do this unless E->refersToBitField() is true. This
5800 // matters in C where getSourceBitField() will find bit-fields for various
5801 // cases where the source expression is not a bit-field designator.
5802
John McCalld25db7e2013-05-06 21:39:12 +00005803 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005804 if (!Field)
Eugene Zelenko7855e772018-04-03 00:11:50 +00005805 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005806
5807 QualType FT = Field->getType();
5808
Richard Smithcaf33902011-10-10 18:28:20 +00005809 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005810 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005811 // C++ [conv.prom]p5:
5812 // A prvalue for an integral bit-field can be converted to a prvalue of type
5813 // int if int can represent all the values of the bit-field; otherwise, it
5814 // can be converted to unsigned int if unsigned int can represent all the
5815 // values of the bit-field. If the bit-field is larger yet, no integral
5816 // promotion applies to it.
5817 // C11 6.3.1.1/2:
5818 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5819 // If an int can represent all values of the original type (as restricted by
5820 // the width, for a bit-field), the value is converted to an int; otherwise,
5821 // it is converted to an unsigned int.
5822 //
5823 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5824 // We perform that promotion here to match GCC and C++.
Richard Smithaadb2542018-06-28 21:17:55 +00005825 // FIXME: C does not permit promotion of an enum bit-field whose rank is
5826 // greater than that of 'int'. We perform that promotion to match GCC.
Eli Friedman629ffb92009-08-20 04:21:42 +00005827 if (BitWidth < IntSize)
5828 return IntTy;
5829
5830 if (BitWidth == IntSize)
5831 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5832
Richard Smithaadb2542018-06-28 21:17:55 +00005833 // Bit-fields wider than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005834 // like the base type. GCC has some weird bugs in this area that we
5835 // deliberately do not follow (GCC follows a pre-standard resolution to
5836 // C's DR315 which treats bit-width as being part of the type, and this leaks
5837 // into their semantics in some cases).
Eugene Zelenko7855e772018-04-03 00:11:50 +00005838 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005839}
5840
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005841/// getPromotedIntegerType - Returns the type that Promotable will
5842/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5843/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005844QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005845 assert(!Promotable.isNull());
5846 assert(Promotable->isPromotableIntegerType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005847 if (const auto *ET = Promotable->getAs<EnumType>())
John McCall56774992009-12-09 09:09:27 +00005848 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005849
Eugene Zelenko7855e772018-04-03 00:11:50 +00005850 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005851 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5852 // (3.9.1) can be converted to a prvalue of the first of the following
5853 // types that can represent all the values of its underlying type:
5854 // int, unsigned int, long int, unsigned long int, long long int, or
5855 // unsigned long long int [...]
5856 // FIXME: Is there some better way to compute this?
5857 if (BT->getKind() == BuiltinType::WChar_S ||
5858 BT->getKind() == BuiltinType::WChar_U ||
Richard Smith3a8244d2018-05-01 05:02:45 +00005859 BT->getKind() == BuiltinType::Char8 ||
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005860 BT->getKind() == BuiltinType::Char16 ||
5861 BT->getKind() == BuiltinType::Char32) {
5862 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5863 uint64_t FromSize = getTypeSize(BT);
5864 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5865 LongLongTy, UnsignedLongLongTy };
5866 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5867 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5868 if (FromSize < ToSize ||
5869 (FromSize == ToSize &&
5870 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5871 return PromoteTypes[Idx];
5872 }
5873 llvm_unreachable("char type should fit into long long");
5874 }
5875 }
5876
5877 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005878 if (Promotable->isSignedIntegerType())
5879 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005880 uint64_t PromotableSize = getIntWidth(Promotable);
5881 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005882 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5883 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5884}
5885
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005886/// Recurses in pointer/array types until it finds an objc retainable
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005887/// type and returns its ownership.
5888Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5889 while (!T.isNull()) {
5890 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5891 return T.getObjCLifetime();
5892 if (T->isArrayType())
5893 T = getBaseElementType(T);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005894 else if (const auto *PT = T->getAs<PointerType>())
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005895 T = PT->getPointeeType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005896 else if (const auto *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005897 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005898 else
5899 break;
5900 }
5901
5902 return Qualifiers::OCL_None;
5903}
5904
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005905static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5906 // Incomplete enum types are not treated as integer types.
5907 // FIXME: In C++, enum types are never integer types.
5908 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5909 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005910 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005911}
5912
Mike Stump11289f42009-09-09 15:08:12 +00005913/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005914/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005915/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005916int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005917 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5918 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005919
5920 // Unwrap enums to their underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005921 if (const auto *ET = dyn_cast<EnumType>(LHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005922 LHSC = getIntegerTypeForEnum(ET);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005923 if (const auto *ET = dyn_cast<EnumType>(RHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005924 RHSC = getIntegerTypeForEnum(ET);
5925
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005926 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005927
Chris Lattner76a00cf2008-04-06 22:59:24 +00005928 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5929 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005930
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005931 unsigned LHSRank = getIntegerRank(LHSC);
5932 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005933
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005934 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5935 if (LHSRank == RHSRank) return 0;
5936 return LHSRank > RHSRank ? 1 : -1;
5937 }
Mike Stump11289f42009-09-09 15:08:12 +00005938
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005939 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5940 if (LHSUnsigned) {
5941 // If the unsigned [LHS] type is larger, return it.
5942 if (LHSRank >= RHSRank)
5943 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005944
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005945 // If the signed type can represent all values of the unsigned type, it
5946 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005947 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005948 return -1;
5949 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005950
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005951 // If the unsigned [RHS] type is larger, return it.
5952 if (RHSRank >= LHSRank)
5953 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005954
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005955 // If the signed type can represent all values of the unsigned type, it
5956 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005957 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005958 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005959}
Anders Carlsson98f07902007-08-17 05:31:46 +00005960
Ben Langmuirf5416742016-02-04 00:55:24 +00005961TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005962 if (CFConstantStringTypeDecl)
5963 return CFConstantStringTypeDecl;
Anders Carlsson6d417272009-11-14 21:45:58 +00005964
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005965 assert(!CFConstantStringTagDecl &&
5966 "tag and typedef should be initialized together");
5967 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5968 CFConstantStringTagDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00005969
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005970 struct {
5971 QualType Type;
5972 const char *Name;
5973 } Fields[5];
5974 unsigned Count = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005975
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005976 /// Objective-C ABI
5977 ///
5978 /// typedef struct __NSConstantString_tag {
Saleem Abdulrasool1f6c41f2018-10-27 06:12:52 +00005979 /// const int *isa;
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005980 /// int flags;
5981 /// const char *str;
5982 /// long length;
5983 /// } __NSConstantString;
5984 ///
5985 /// Swift ABI (4.1, 4.2)
5986 ///
5987 /// typedef struct __NSConstantString_tag {
5988 /// uintptr_t _cfisa;
5989 /// uintptr_t _swift_rc;
5990 /// _Atomic(uint64_t) _cfinfoa;
5991 /// const char *_ptr;
5992 /// uint32_t _length;
5993 /// } __NSConstantString;
5994 ///
5995 /// Swift ABI (5.0)
5996 ///
5997 /// typedef struct __NSConstantString_tag {
5998 /// uintptr_t _cfisa;
5999 /// uintptr_t _swift_rc;
6000 /// _Atomic(uint64_t) _cfinfoa;
6001 /// const char *_ptr;
6002 /// uintptr_t _length;
6003 /// } __NSConstantString;
6004
6005 const auto CFRuntime = getLangOpts().CFRuntime;
6006 if (static_cast<unsigned>(CFRuntime) <
6007 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
6008 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
6009 Fields[Count++] = { IntTy, "flags" };
6010 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
6011 Fields[Count++] = { LongTy, "length" };
6012 } else {
6013 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
6014 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
6015 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
6016 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
6017 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
6018 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
6019 Fields[Count++] = { IntTy, "_ptr" };
6020 else
6021 Fields[Count++] = { getUIntPtrType(), "_ptr" };
6022 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006023
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006024 // Create fields
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00006025 for (unsigned i = 0; i < Count; ++i) {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006026 FieldDecl *Field =
6027 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00006028 SourceLocation(), &Idents.get(Fields[i].Name),
6029 Fields[i].Type, /*TInfo=*/nullptr,
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006030 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6031 Field->setAccess(AS_public);
6032 CFConstantStringTagDecl->addDecl(Field);
Anders Carlsson98f07902007-08-17 05:31:46 +00006033 }
Mike Stump11289f42009-09-09 15:08:12 +00006034
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006035 CFConstantStringTagDecl->completeDefinition();
6036 // This type is designed to be compatible with NSConstantString, but cannot
6037 // use the same name, since NSConstantString is an interface.
6038 auto tagType = getTagDeclType(CFConstantStringTagDecl);
6039 CFConstantStringTypeDecl =
6040 buildImplicitTypedef(tagType, "__NSConstantString");
6041
Quentin Colombet043406b2016-02-03 22:41:00 +00006042 return CFConstantStringTypeDecl;
6043}
6044
Ben Langmuirf5416742016-02-04 00:55:24 +00006045RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
6046 if (!CFConstantStringTagDecl)
6047 getCFConstantStringDecl(); // Build the tag and the typedef.
6048 return CFConstantStringTagDecl;
6049}
6050
Quentin Colombet043406b2016-02-03 22:41:00 +00006051// getCFConstantStringType - Return the type used for constant CFStrings.
6052QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00006053 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00006054}
Anders Carlsson87c149b2007-10-11 01:00:40 +00006055
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00006056QualType ASTContext::getObjCSuperType() const {
6057 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006058 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00006059 TUDecl->addDecl(ObjCSuperTypeDecl);
6060 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
6061 }
6062 return ObjCSuperType;
6063}
6064
Douglas Gregor512b0772009-04-23 22:29:11 +00006065void ASTContext::setCFConstantStringType(QualType T) {
Simon Pilgrim9588ae72019-10-03 21:47:42 +00006066 const auto *TD = T->castAs<TypedefType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00006067 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
Eugene Zelenko7855e772018-04-03 00:11:50 +00006068 const auto *TagType =
Simon Pilgrim9588ae72019-10-03 21:47:42 +00006069 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00006070 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00006071}
6072
Jay Foad39c79802011-01-12 09:06:06 +00006073QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00006074 if (BlockDescriptorType)
6075 return getTagDeclType(BlockDescriptorType);
6076
Alp Toker2dea15b2013-12-17 01:22:38 +00006077 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00006078 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00006079 RD = buildImplicitRecord("__block_descriptor");
6080 RD->startDefinition();
6081
Mike Stumpd0153282009-10-20 02:12:22 +00006082 QualType FieldTypes[] = {
6083 UnsignedLongTy,
6084 UnsignedLongTy,
6085 };
6086
Craig Topperd6d31ac2013-07-15 08:24:27 +00006087 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00006088 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006089 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00006090 };
6091
6092 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006093 FieldDecl *Field = FieldDecl::Create(
6094 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00006095 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6096 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00006097 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006098 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00006099 }
6100
Alp Toker2dea15b2013-12-17 01:22:38 +00006101 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00006102
Alp Toker2dea15b2013-12-17 01:22:38 +00006103 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00006104
6105 return getTagDeclType(BlockDescriptorType);
6106}
6107
Jay Foad39c79802011-01-12 09:06:06 +00006108QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006109 if (BlockDescriptorExtendedType)
6110 return getTagDeclType(BlockDescriptorExtendedType);
6111
Alp Toker2dea15b2013-12-17 01:22:38 +00006112 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006113 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00006114 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6115 RD->startDefinition();
6116
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006117 QualType FieldTypes[] = {
6118 UnsignedLongTy,
6119 UnsignedLongTy,
6120 getPointerType(VoidPtrTy),
6121 getPointerType(VoidPtrTy)
6122 };
6123
Craig Topperd6d31ac2013-07-15 08:24:27 +00006124 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006125 "reserved",
6126 "Size",
6127 "CopyFuncPtr",
6128 "DestroyFuncPtr"
6129 };
6130
6131 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006132 FieldDecl *Field = FieldDecl::Create(
6133 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00006134 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6135 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00006136 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00006137 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006138 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006139 }
6140
Alp Toker2dea15b2013-12-17 01:22:38 +00006141 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006142
Alp Toker2dea15b2013-12-17 01:22:38 +00006143 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006144 return getTagDeclType(BlockDescriptorExtendedType);
6145}
6146
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006147TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006148 const auto *BT = dyn_cast<BuiltinType>(T);
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006149
6150 if (!BT) {
6151 if (isa<PipeType>(T))
6152 return TargetInfo::OCLTK_Pipe;
6153
6154 return TargetInfo::OCLTK_Default;
6155 }
6156
6157 switch (BT->getKind()) {
6158#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6159 case BuiltinType::Id: \
6160 return TargetInfo::OCLTK_Image;
6161#include "clang/Basic/OpenCLImageTypes.def"
6162
6163 case BuiltinType::OCLClkEvent:
6164 return TargetInfo::OCLTK_ClkEvent;
6165
6166 case BuiltinType::OCLEvent:
6167 return TargetInfo::OCLTK_Event;
6168
6169 case BuiltinType::OCLQueue:
6170 return TargetInfo::OCLTK_Queue;
6171
6172 case BuiltinType::OCLReserveID:
6173 return TargetInfo::OCLTK_ReserveID;
6174
6175 case BuiltinType::OCLSampler:
6176 return TargetInfo::OCLTK_Sampler;
6177
6178 default:
6179 return TargetInfo::OCLTK_Default;
6180 }
6181}
6182
6183LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6184 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6185}
6186
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006187/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6188/// requires copy/dispose. Note that this must match the logic
6189/// in buildByrefHelpers.
6190bool ASTContext::BlockRequiresCopying(QualType Ty,
6191 const VarDecl *D) {
6192 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00006193 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006194 if (!copyExpr && record->hasTrivialDestructor()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006195
Mike Stump94967902009-10-21 18:16:27 +00006196 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00006197 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006198
Akira Hatanaka7275da02018-02-28 07:15:55 +00006199 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6200 // move or destroy.
6201 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6202 return true;
6203
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006204 if (!Ty->isObjCRetainableType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006205
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006206 Qualifiers qs = Ty.getQualifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00006207
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006208 // If we have lifetime, that dominates.
6209 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006210 switch (lifetime) {
6211 case Qualifiers::OCL_None: llvm_unreachable("impossible");
Fangrui Song6907ce22018-07-30 19:24:48 +00006212
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006213 // These are just bits as far as the runtime is concerned.
6214 case Qualifiers::OCL_ExplicitNone:
6215 case Qualifiers::OCL_Autoreleasing:
6216 return false;
Akira Hatanaka7275da02018-02-28 07:15:55 +00006217
6218 // These cases should have been taken care of when checking the type's
6219 // non-triviality.
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006220 case Qualifiers::OCL_Weak:
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006221 case Qualifiers::OCL_Strong:
Akira Hatanaka7275da02018-02-28 07:15:55 +00006222 llvm_unreachable("impossible");
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006223 }
6224 llvm_unreachable("fell out of lifetime switch!");
6225 }
6226 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6227 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00006228}
6229
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006230bool ASTContext::getByrefLifetime(QualType Ty,
6231 Qualifiers::ObjCLifetime &LifeTime,
6232 bool &HasByrefExtendedLayout) const {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00006233 if (!getLangOpts().ObjC ||
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006234 getLangOpts().getGC() != LangOptions::NonGC)
6235 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006236
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006237 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00006238 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006239 HasByrefExtendedLayout = true;
6240 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006241 } else if ((LifeTime = Ty.getObjCLifetime())) {
6242 // Honor the ARC qualifiers.
6243 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6244 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006245 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00006246 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006247 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006248 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006249 return true;
6250}
6251
Douglas Gregorbab8a962011-09-08 01:46:34 +00006252TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6253 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00006254 ObjCInstanceTypeDecl =
6255 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00006256 return ObjCInstanceTypeDecl;
6257}
6258
Anders Carlsson18acd442007-10-29 06:33:42 +00006259// This returns true if a type has been typedefed to BOOL:
6260// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00006261static bool isTypeTypedefedAsBOOL(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006262 if (const auto *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00006263 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6264 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00006265
Anders Carlssond8499822007-10-29 05:01:08 +00006266 return false;
6267}
6268
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006269/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006270/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00006271CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00006272 if (!type->isIncompleteArrayType() && type->isIncompleteType())
6273 return CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +00006274
Ken Dyck40775002010-01-11 17:06:35 +00006275 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00006276
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006277 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00006278 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00006279 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006280 // Treat arrays as pointers, since that's how they're passed in.
6281 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00006282 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00006283 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00006284}
6285
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006286bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00006287 return getTargetInfo().getCXXABI().isMicrosoft() &&
6288 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00006289 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00006290 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006291}
6292
Richard Smithd9b90092016-07-02 01:32:16 +00006293ASTContext::InlineVariableDefinitionKind
6294ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6295 if (!VD->isInline())
6296 return InlineVariableDefinitionKind::None;
6297
6298 // In almost all cases, it's a weak definition.
6299 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00006300 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00006301 return InlineVariableDefinitionKind::Weak;
6302
6303 // If there's a file-context declaration in this translation unit, it's a
6304 // non-discardable definition.
6305 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00006306 if (D->getLexicalDeclContext()->isFileContext() &&
6307 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00006308 return InlineVariableDefinitionKind::Strong;
6309
6310 // If we've not seen one yet, we don't know.
6311 return InlineVariableDefinitionKind::WeakUnknown;
6312}
6313
Eugene Zelenko7855e772018-04-03 00:11:50 +00006314static std::string charUnitsToString(const CharUnits &CU) {
Ken Dyck40775002010-01-11 17:06:35 +00006315 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006316}
6317
John McCall351762c2011-02-07 10:33:21 +00006318/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00006319/// declaration.
John McCall351762c2011-02-07 10:33:21 +00006320std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6321 std::string S;
6322
David Chisnall950a9512009-11-17 19:33:30 +00006323 const BlockDecl *Decl = Expr->getBlockDecl();
6324 QualType BlockTy =
Simon Pilgrimeed4b122019-10-02 11:48:06 +00006325 Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
6326 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
David Chisnall950a9512009-11-17 19:33:30 +00006327 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006328 if (getLangOpts().EncodeExtendedBlockSig)
Simon Pilgrimeed4b122019-10-02 11:48:06 +00006329 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
6330 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006331 else
Simon Pilgrimeed4b122019-10-02 11:48:06 +00006332 getObjCEncodingForType(BlockReturnTy, S);
David Chisnall950a9512009-11-17 19:33:30 +00006333 // Compute size of all parameters.
6334 // Start with computing size of a pointer in number of bytes.
6335 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006336 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6337 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006338 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00006339 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006340 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00006341 if (sz.isZero())
6342 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006343 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00006344 ParmOffset += sz;
6345 }
6346 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00006347 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00006348 // Block pointer and offset.
6349 S += "@?0";
Fangrui Song6907ce22018-07-30 19:24:48 +00006350
David Chisnall950a9512009-11-17 19:33:30 +00006351 // Argument types.
6352 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006353 for (auto PVDecl : Decl->parameters()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006354 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006355 if (const auto *AT =
6356 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall950a9512009-11-17 19:33:30 +00006357 // Use array's original type only if it has known number of
6358 // elements.
6359 if (!isa<ConstantArrayType>(AT))
6360 PType = PVDecl->getType();
6361 } else if (PType->isFunctionType())
6362 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006363 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006364 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6365 S, true /*Extended*/);
6366 else
6367 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00006368 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006369 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00006370 }
John McCall351762c2011-02-07 10:33:21 +00006371
6372 return S;
David Chisnall950a9512009-11-17 19:33:30 +00006373}
6374
John McCall843dfcc2016-11-29 21:57:00 +00006375std::string
6376ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6377 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006378 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00006379 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00006380 CharUnits ParmOffset;
6381 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00006382 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00006383 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00006384 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006385 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006386 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006387
6388 assert(sz.isPositive() &&
John McCall843dfcc2016-11-29 21:57:00 +00006389 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00006390 ParmOffset += sz;
6391 }
6392 S += charUnitsToString(ParmOffset);
6393 ParmOffset = CharUnits::Zero();
6394
6395 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00006396 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006397 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006398 if (const auto *AT =
6399 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006400 // Use array's original type only if it has known number of
6401 // elements.
6402 if (!isa<ConstantArrayType>(AT))
6403 PType = PVDecl->getType();
6404 } else if (PType->isFunctionType())
6405 PType = PVDecl->getType();
6406 getObjCEncodingForType(PType, S);
6407 S += charUnitsToString(ParmOffset);
6408 ParmOffset += getObjCEncodingTypeSize(PType);
6409 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006410
John McCall843dfcc2016-11-29 21:57:00 +00006411 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006412}
6413
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006414/// getObjCEncodingForMethodParameter - Return the encoded type for a single
Fangrui Song6907ce22018-07-30 19:24:48 +00006415/// method parameter or return type. If Extended, include class names and
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006416/// block object types.
6417void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6418 QualType T, std::string& S,
6419 bool Extended) const {
6420 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6421 getObjCEncodingForTypeQualifier(QT, S);
6422 // Encode parameter type.
Nico Weber2e9591c2019-05-14 12:32:37 +00006423 ObjCEncOptions Options = ObjCEncOptions()
6424 .setExpandPointedToStructures()
6425 .setExpandStructures()
6426 .setIsOutermostType();
6427 if (Extended)
6428 Options.setEncodeBlockParameters().setEncodeClassNames();
6429 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006430}
6431
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006432/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006433/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00006434std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6435 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006436 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006437 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006438 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006439 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6440 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006441 // Compute size of all parameters.
6442 // Start with computing size of a pointer in number of bytes.
6443 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006444 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006445 // The first two arguments (self and _cmd) are pointers; account for
6446 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006447 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006448 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006449 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006450 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006451 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006452 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006453 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006454
6455 assert(sz.isPositive() &&
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006456 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006457 ParmOffset += sz;
6458 }
Ken Dyck40775002010-01-11 17:06:35 +00006459 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006460 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006461 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006462
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006463 // Argument types.
6464 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006465 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006466 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006467 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006468 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006469 if (const auto *AT =
6470 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
Steve Naroffe4e55d22009-04-14 00:03:58 +00006471 // Use array's original type only if it has known number of
6472 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006473 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006474 PType = PVDecl->getType();
6475 } else if (PType->isFunctionType())
6476 PType = PVDecl->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00006477 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006478 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006479 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006480 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006481 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006482
John McCall843dfcc2016-11-29 21:57:00 +00006483 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006484}
6485
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006486ObjCPropertyImplDecl *
6487ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6488 const ObjCPropertyDecl *PD,
6489 const Decl *Container) const {
6490 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006491 return nullptr;
Eugene Zelenko7855e772018-04-03 00:11:50 +00006492 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006493 for (auto *PID : CID->property_impls())
6494 if (PID->getPropertyDecl() == PD)
6495 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006496 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006497 const auto *OID = cast<ObjCImplementationDecl>(Container);
Craig Topper36250ad2014-05-12 05:36:57 +00006498 for (auto *PID : OID->property_impls())
6499 if (PID->getPropertyDecl() == PD)
6500 return PID;
6501 }
6502 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006503}
6504
Daniel Dunbar4932b362008-08-28 04:38:10 +00006505/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006506/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006507/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6508/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006509/// Property attributes are stored as a comma-delimited C string. The simple
6510/// attributes readonly and bycopy are encoded as single characters. The
6511/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6512/// encoded as single characters, followed by an identifier. Property types
6513/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006514/// these attributes are defined by the following enumeration:
6515/// @code
6516/// enum PropertyAttributes {
6517/// kPropertyReadOnly = 'R', // property is read-only.
6518/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6519/// kPropertyByref = '&', // property is a reference to the value last assigned
6520/// kPropertyDynamic = 'D', // property is dynamic
6521/// kPropertyGetter = 'G', // followed by getter selector name
6522/// kPropertySetter = 'S', // followed by setter selector name
6523/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006524/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006525/// kPropertyWeak = 'W' // 'weak' property
6526/// kPropertyStrong = 'P' // property GC'able
6527/// kPropertyNonAtomic = 'N' // property non-atomic
6528/// };
6529/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006530std::string
6531ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6532 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006533 // Collect information from the property implementation decl(s).
6534 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006535 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006536
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006537 if (ObjCPropertyImplDecl *PropertyImpDecl =
6538 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6539 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6540 Dynamic = true;
6541 else
6542 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006543 }
6544
6545 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006546 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006547
6548 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006549 // GCC has some special rules regarding encoding of properties which
6550 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006551 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006552
6553 if (PD->isReadOnly()) {
6554 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006555 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6556 S += ",C";
6557 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6558 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006559 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6560 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006561 } else {
6562 switch (PD->getSetterKind()) {
6563 case ObjCPropertyDecl::Assign: break;
6564 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006565 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006566 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006567 }
6568 }
6569
6570 // It really isn't clear at all what this means, since properties
6571 // are "dynamic by default".
6572 if (Dynamic)
6573 S += ",D";
6574
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006575 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6576 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006577
Daniel Dunbar4932b362008-08-28 04:38:10 +00006578 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6579 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006580 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006581 }
6582
6583 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6584 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006585 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006586 }
6587
6588 if (SynthesizePID) {
6589 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6590 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006591 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006592 }
6593
6594 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006595 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006596}
6597
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006598/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006599/// Another legacy compatibility encoding: 32-bit longs are encoded as
6600/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006601/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006602void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006603 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006604 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006605 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006606 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006607 else
Jay Foad39c79802011-01-12 09:06:06 +00006608 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006609 PointeeTy = IntTy;
6610 }
6611 }
6612}
6613
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006614void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006615 const FieldDecl *Field,
6616 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006617 // We follow the behavior of gcc, expanding structures which are
6618 // directly pointed to, and expanding embedded structures. Note that
6619 // these rules are sufficient to prevent recursive encoding of the
6620 // same type.
Nico Weber2e9591c2019-05-14 12:32:37 +00006621 getObjCEncodingForTypeImpl(T, S,
6622 ObjCEncOptions()
6623 .setExpandPointedToStructures()
6624 .setExpandStructures()
6625 .setIsOutermostType(),
6626 Field, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006627}
6628
Joe Groff98ac7d22014-07-07 22:25:15 +00006629void ASTContext::getObjCEncodingForPropertyType(QualType T,
6630 std::string& S) const {
6631 // Encode result type.
6632 // GCC has some special rules regarding encoding of properties which
6633 // closely resembles encoding of ivars.
Nico Weber2e9591c2019-05-14 12:32:37 +00006634 getObjCEncodingForTypeImpl(T, S,
6635 ObjCEncOptions()
6636 .setExpandPointedToStructures()
6637 .setExpandStructures()
6638 .setIsOutermostType()
6639 .setEncodingProperty(),
6640 /*Field=*/nullptr);
Joe Groff98ac7d22014-07-07 22:25:15 +00006641}
6642
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006643static char getObjCEncodingForPrimitiveType(const ASTContext *C,
6644 const BuiltinType *BT) {
6645 BuiltinType::Kind kind = BT->getKind();
John McCall393a78d2012-12-20 02:45:14 +00006646 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006647 case BuiltinType::Void: return 'v';
6648 case BuiltinType::Bool: return 'B';
Richard Smith3a8244d2018-05-01 05:02:45 +00006649 case BuiltinType::Char8:
David Chisnallb190a2c2010-06-04 01:10:52 +00006650 case BuiltinType::Char_U:
6651 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006652 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006653 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006654 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006655 case BuiltinType::UInt: return 'I';
6656 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006657 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006658 case BuiltinType::UInt128: return 'T';
6659 case BuiltinType::ULongLong: return 'Q';
6660 case BuiltinType::Char_S:
6661 case BuiltinType::SChar: return 'c';
6662 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006663 case BuiltinType::WChar_S:
6664 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006665 case BuiltinType::Int: return 'i';
6666 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006667 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006668 case BuiltinType::LongLong: return 'q';
6669 case BuiltinType::Int128: return 't';
6670 case BuiltinType::Float: return 'f';
6671 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006672 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006673 case BuiltinType::NullPtr: return '*'; // like char*
6674
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006675 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006676 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006677 case BuiltinType::Half:
Leonard Chanf921d852018-06-04 16:07:52 +00006678 case BuiltinType::ShortAccum:
6679 case BuiltinType::Accum:
6680 case BuiltinType::LongAccum:
6681 case BuiltinType::UShortAccum:
6682 case BuiltinType::UAccum:
6683 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00006684 case BuiltinType::ShortFract:
6685 case BuiltinType::Fract:
6686 case BuiltinType::LongFract:
6687 case BuiltinType::UShortFract:
6688 case BuiltinType::UFract:
6689 case BuiltinType::ULongFract:
6690 case BuiltinType::SatShortAccum:
6691 case BuiltinType::SatAccum:
6692 case BuiltinType::SatLongAccum:
6693 case BuiltinType::SatUShortAccum:
6694 case BuiltinType::SatUAccum:
6695 case BuiltinType::SatULongAccum:
6696 case BuiltinType::SatShortFract:
6697 case BuiltinType::SatFract:
6698 case BuiltinType::SatLongFract:
6699 case BuiltinType::SatUShortFract:
6700 case BuiltinType::SatUFract:
6701 case BuiltinType::SatULongFract:
John McCall393a78d2012-12-20 02:45:14 +00006702 // FIXME: potentially need @encodes for these!
6703 return ' ';
6704
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006705#define SVE_TYPE(Name, Id, SingletonId) \
6706 case BuiltinType::Id:
6707#include "clang/Basic/AArch64SVEACLETypes.def"
6708 {
6709 DiagnosticsEngine &Diags = C->getDiagnostics();
6710 unsigned DiagID = Diags.getCustomDiagID(
6711 DiagnosticsEngine::Error, "cannot yet @encode type %0");
6712 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
6713 return ' ';
6714 }
6715
John McCall393a78d2012-12-20 02:45:14 +00006716 case BuiltinType::ObjCId:
6717 case BuiltinType::ObjCClass:
6718 case BuiltinType::ObjCSel:
6719 llvm_unreachable("@encoding ObjC primitive type");
6720
6721 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006722#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6723 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006724#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00006725#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6726 case BuiltinType::Id:
6727#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006728 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006729 case BuiltinType::OCLClkEvent:
6730 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006731 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006732 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006733 case BuiltinType::Dependent:
6734#define BUILTIN_TYPE(KIND, ID)
6735#define PLACEHOLDER_TYPE(KIND, ID) \
6736 case BuiltinType::KIND:
6737#include "clang/AST/BuiltinTypes.def"
6738 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006739 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006740 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006741}
6742
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006743static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6744 EnumDecl *Enum = ET->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00006745
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006746 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6747 if (!Enum->isFixed())
6748 return 'i';
Fangrui Song6907ce22018-07-30 19:24:48 +00006749
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006750 // The encoding of a fixed enum type matches its fixed underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00006751 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006752 return getObjCEncodingForPrimitiveType(C, BT);
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006753}
6754
Jay Foad39c79802011-01-12 09:06:06 +00006755static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006756 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006757 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006758 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006759 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6760 // The GNU runtime requires more information; bitfields are encoded as b,
6761 // then the offset (in bits) of the first element, then the type of the
6762 // bitfield, then the size in bits. For example, in this structure:
6763 //
6764 // struct
6765 // {
6766 // int integer;
6767 // int flags:2;
6768 // };
6769 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6770 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6771 // information is not especially sensible, but we're stuck with it for
6772 // compatibility with GCC, although providing it breaks anything that
6773 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006774 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006775 uint64_t Offset;
6776
6777 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6778 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6779 IVD);
6780 } else {
6781 const RecordDecl *RD = FD->getParent();
6782 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6783 Offset = RL.getFieldOffset(FD->getFieldIndex());
6784 }
6785
6786 S += llvm::utostr(Offset);
6787
Eugene Zelenko7855e772018-04-03 00:11:50 +00006788 if (const auto *ET = T->getAs<EnumType>())
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006789 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006790 else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006791 const auto *BT = T->castAs<BuiltinType>();
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006792 S += getObjCEncodingForPrimitiveType(Ctx, BT);
John McCall393a78d2012-12-20 02:45:14 +00006793 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006794 }
Richard Smithcaf33902011-10-10 18:28:20 +00006795 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006796}
6797
Daniel Dunbar07d07852009-10-18 21:17:35 +00006798// FIXME: Use SmallString for accumulating string.
Nico Weber2e9591c2019-05-14 12:32:37 +00006799void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
6800 const ObjCEncOptions Options,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006801 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006802 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006803 CanQualType CT = getCanonicalType(T);
6804 switch (CT->getTypeClass()) {
6805 case Type::Builtin:
6806 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006807 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006808 return EncodeBitField(this, S, T, FD);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006809 if (const auto *BT = dyn_cast<BuiltinType>(CT))
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006810 S += getObjCEncodingForPrimitiveType(this, BT);
John McCall393a78d2012-12-20 02:45:14 +00006811 else
6812 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006813 return;
Mike Stump11289f42009-09-09 15:08:12 +00006814
John McCall393a78d2012-12-20 02:45:14 +00006815 case Type::Complex: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006816 const auto *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006817 S += 'j';
Nico Weber2e9591c2019-05-14 12:32:37 +00006818 getObjCEncodingForTypeImpl(CT->getElementType(), S, ObjCEncOptions(),
6819 /*Field=*/nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006820 return;
6821 }
John McCall393a78d2012-12-20 02:45:14 +00006822
6823 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006824 const auto *AT = T->castAs<AtomicType>();
John McCall393a78d2012-12-20 02:45:14 +00006825 S += 'A';
Nico Weber2e9591c2019-05-14 12:32:37 +00006826 getObjCEncodingForTypeImpl(AT->getValueType(), S, ObjCEncOptions(),
6827 /*Field=*/nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006828 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006829 }
John McCall393a78d2012-12-20 02:45:14 +00006830
6831 // encoding for pointer or reference types.
6832 case Type::Pointer:
6833 case Type::LValueReference:
6834 case Type::RValueReference: {
6835 QualType PointeeTy;
6836 if (isa<PointerType>(CT)) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006837 const auto *PT = T->castAs<PointerType>();
John McCall393a78d2012-12-20 02:45:14 +00006838 if (PT->isObjCSelType()) {
6839 S += ':';
6840 return;
6841 }
6842 PointeeTy = PT->getPointeeType();
6843 } else {
6844 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6845 }
6846
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006847 bool isReadOnly = false;
6848 // For historical/compatibility reasons, the read-only qualifier of the
6849 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6850 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006851 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006852 if (isa<TypedefType>(T.getTypePtr())) {
Nico Weber2e9591c2019-05-14 12:32:37 +00006853 if (Options.IsOutermostType() && T.isConstQualified()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006854 isReadOnly = true;
6855 S += 'r';
6856 }
Nico Weber2e9591c2019-05-14 12:32:37 +00006857 } else if (Options.IsOutermostType()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006858 QualType P = PointeeTy;
Simon Pilgrimd834f1f2019-10-03 15:08:20 +00006859 while (auto PT = P->getAs<PointerType>())
6860 P = PT->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006861 if (P.isConstQualified()) {
6862 isReadOnly = true;
6863 S += 'r';
6864 }
6865 }
6866 if (isReadOnly) {
6867 // Another legacy compatibility encoding. Some ObjC qualifier and type
6868 // combinations need to be rearranged.
6869 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006870 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006871 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006872 }
Mike Stump11289f42009-09-09 15:08:12 +00006873
Anders Carlssond8499822007-10-29 05:01:08 +00006874 if (PointeeTy->isCharType()) {
6875 // char pointer types should be encoded as '*' unless it is a
6876 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006877 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006878 S += '*';
6879 return;
6880 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00006881 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006882 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6883 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6884 S += '#';
6885 return;
6886 }
6887 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6888 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6889 S += '@';
6890 return;
6891 }
6892 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006893 }
Anders Carlssond8499822007-10-29 05:01:08 +00006894 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006895 getLegacyIntegralTypeEncoding(PointeeTy);
6896
Nico Weber2e9591c2019-05-14 12:32:37 +00006897 ObjCEncOptions NewOptions;
6898 if (Options.ExpandPointedToStructures())
6899 NewOptions.setExpandStructures();
6900 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
6901 /*Field=*/nullptr, NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006902 return;
6903 }
John McCall393a78d2012-12-20 02:45:14 +00006904
6905 case Type::ConstantArray:
6906 case Type::IncompleteArray:
6907 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006908 const auto *AT = cast<ArrayType>(CT);
John McCall393a78d2012-12-20 02:45:14 +00006909
Nico Weber2e9591c2019-05-14 12:32:37 +00006910 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006911 // Incomplete arrays are encoded as a pointer to the array element.
6912 S += '^';
6913
Nico Weber2e9591c2019-05-14 12:32:37 +00006914 getObjCEncodingForTypeImpl(
6915 AT->getElementType(), S,
6916 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006917 } else {
6918 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006919
Eugene Zelenko7855e772018-04-03 00:11:50 +00006920 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006921 S += llvm::utostr(CAT->getSize().getZExtValue());
6922 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006923 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006924 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6925 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006926 S += '0';
6927 }
Mike Stump11289f42009-09-09 15:08:12 +00006928
Nico Weberdf129332019-05-10 13:56:56 +00006929 getObjCEncodingForTypeImpl(
6930 AT->getElementType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00006931 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
6932 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006933 S += ']';
6934 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006935 return;
6936 }
Mike Stump11289f42009-09-09 15:08:12 +00006937
John McCall393a78d2012-12-20 02:45:14 +00006938 case Type::FunctionNoProto:
6939 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006940 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006941 return;
Mike Stump11289f42009-09-09 15:08:12 +00006942
John McCall393a78d2012-12-20 02:45:14 +00006943 case Type::Record: {
6944 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006945 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006946 // Anonymous structures print as '?'
6947 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6948 S += II->getName();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006949 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006950 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006951 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00006952 printTemplateArgumentList(OS, TemplateArgs.asArray(),
6953 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006954 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006955 } else {
6956 S += '?';
6957 }
Nico Weber2e9591c2019-05-14 12:32:37 +00006958 if (Options.ExpandStructures()) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006959 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006960 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006961 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006962 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006963 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006964 if (FD) {
6965 S += '"';
6966 S += Field->getNameAsString();
6967 S += '"';
6968 }
Mike Stump11289f42009-09-09 15:08:12 +00006969
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006970 // Special case bit-fields.
6971 if (Field->isBitField()) {
Nico Weberdf129332019-05-10 13:56:56 +00006972 getObjCEncodingForTypeImpl(Field->getType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00006973 ObjCEncOptions().setExpandStructures(),
6974 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006975 } else {
6976 QualType qt = Field->getType();
6977 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00006978 getObjCEncodingForTypeImpl(
Nico Weber2e9591c2019-05-14 12:32:37 +00006979 qt, S,
6980 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
6981 NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006982 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006983 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006984 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006985 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006986 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006987 return;
6988 }
Mike Stump11289f42009-09-09 15:08:12 +00006989
John McCall393a78d2012-12-20 02:45:14 +00006990 case Type::BlockPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006991 const auto *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006992 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Nico Weber2e9591c2019-05-14 12:32:37 +00006993 if (Options.EncodeBlockParameters()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006994 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00006995
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006996 S += '<';
6997 // Block return type
Nico Weber2e9591c2019-05-14 12:32:37 +00006998 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
6999 Options.forComponentType(), FD, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00007000 // Block self
7001 S += "@?";
7002 // Block parameters
Eugene Zelenko7855e772018-04-03 00:11:50 +00007003 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00007004 for (const auto &I : FPT->param_types())
Nico Weber2e9591c2019-05-14 12:32:37 +00007005 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
7006 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00007007 }
7008 S += '>';
7009 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00007010 return;
7011 }
Mike Stump11289f42009-09-09 15:08:12 +00007012
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00007013 case Type::ObjCObject: {
7014 // hack to match legacy encoding of *id and *Class
7015 QualType Ty = getObjCObjectPointerType(CT);
7016 if (Ty->isObjCIdType()) {
7017 S += "{objc_object=}";
7018 return;
7019 }
7020 else if (Ty->isObjCClassType()) {
7021 S += "{objc_class=}";
7022 return;
7023 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007024 // TODO: Double check to make sure this intentionally falls through.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00007025 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00007026 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007027
John McCall393a78d2012-12-20 02:45:14 +00007028 case Type::ObjCInterface: {
7029 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007030 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007031 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007032 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007033 S += OI->getObjCRuntimeNameAsString();
Nico Weber2e9591c2019-05-14 12:32:37 +00007034 if (Options.ExpandStructures()) {
Akira Hatanakafd0fb202016-08-17 19:42:22 +00007035 S += '=';
7036 SmallVector<const ObjCIvarDecl*, 32> Ivars;
7037 DeepCollectObjCIvars(OI, true, Ivars);
7038 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00007039 const FieldDecl *Field = Ivars[i];
Akira Hatanakafd0fb202016-08-17 19:42:22 +00007040 if (Field->isBitField())
Nico Weberdf129332019-05-10 13:56:56 +00007041 getObjCEncodingForTypeImpl(Field->getType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00007042 ObjCEncOptions().setExpandStructures(),
7043 Field);
Akira Hatanakaf3c89b12019-05-29 21:23:30 +00007044 else
7045 getObjCEncodingForTypeImpl(Field->getType(), S,
7046 ObjCEncOptions().setExpandStructures(), FD,
Nico Weber2e9591c2019-05-14 12:32:37 +00007047 NotEncodedT);
Akira Hatanakafd0fb202016-08-17 19:42:22 +00007048 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007049 }
7050 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00007051 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007052 }
Mike Stump11289f42009-09-09 15:08:12 +00007053
John McCall393a78d2012-12-20 02:45:14 +00007054 case Type::ObjCObjectPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007055 const auto *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007056 if (OPT->isObjCIdType()) {
7057 S += '@';
7058 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00007059 }
Mike Stump11289f42009-09-09 15:08:12 +00007060
Steve Narofff0c86112009-10-28 22:03:49 +00007061 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
7062 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
Nico Weberdf129332019-05-10 13:56:56 +00007063 // Since this is a binary compatibility issue, need to consult with
7064 // runtime folks. Fortunately, this is a *very* obscure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007065 S += '#';
7066 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00007067 }
Mike Stump11289f42009-09-09 15:08:12 +00007068
Chris Lattnere7cabb92009-07-13 00:10:46 +00007069 if (OPT->isObjCQualifiedIdType()) {
Nico Weber2e9591c2019-05-14 12:32:37 +00007070 getObjCEncodingForTypeImpl(
7071 getObjCIdType(), S,
7072 Options.keepingOnly(ObjCEncOptions()
7073 .setExpandPointedToStructures()
7074 .setExpandStructures()),
7075 FD);
7076 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00007077 // Note that we do extended encoding of protocol qualifer list
7078 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007079 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00007080 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00007081 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007082 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007083 S += '>';
7084 }
7085 S += '"';
7086 }
7087 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00007088 }
Mike Stump11289f42009-09-09 15:08:12 +00007089
Chris Lattnere7cabb92009-07-13 00:10:46 +00007090 S += '@';
Fangrui Song6907ce22018-07-30 19:24:48 +00007091 if (OPT->getInterfaceDecl() &&
Nico Weber2e9591c2019-05-14 12:32:37 +00007092 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00007093 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007094 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00007095 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00007096 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007097 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00007098 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00007099 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00007100 S += '"';
7101 }
7102 return;
7103 }
Mike Stump11289f42009-09-09 15:08:12 +00007104
John McCalla9e6e8d2010-05-17 23:56:34 +00007105 // gcc just blithely ignores member pointers.
Nico Weber2e9591c2019-05-14 12:32:37 +00007106 // FIXME: we should do better than that. 'M' is available.
John McCall393a78d2012-12-20 02:45:14 +00007107 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007108 // This matches gcc's encoding, even though technically it is insufficient.
7109 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00007110 case Type::Vector:
7111 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007112 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007113 if (NotEncodedT)
7114 *NotEncodedT = T;
7115 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00007116
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007117 // We could see an undeduced auto type here during error recovery.
7118 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00007119 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007120 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00007121 return;
7122
Xiuli Pan9c14e282016-01-09 12:53:17 +00007123 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00007124#define ABSTRACT_TYPE(KIND, BASE)
7125#define TYPE(KIND, BASE)
7126#define DEPENDENT_TYPE(KIND, BASE) \
7127 case Type::KIND:
7128#define NON_CANONICAL_TYPE(KIND, BASE) \
7129 case Type::KIND:
7130#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7131 case Type::KIND:
John McCall36b12a82019-10-02 06:35:23 +00007132#include "clang/AST/TypeNodes.inc"
John McCall393a78d2012-12-20 02:45:14 +00007133 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00007134 }
John McCall393a78d2012-12-20 02:45:14 +00007135 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00007136}
7137
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007138void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7139 std::string &S,
7140 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007141 bool includeVBases,
7142 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007143 assert(RDecl && "Expected non-null RecordDecl");
7144 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00007145 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007146 return;
7147
Eugene Zelenko7855e772018-04-03 00:11:50 +00007148 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007149 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7150 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7151
7152 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00007153 for (const auto &BI : CXXRec->bases()) {
7154 if (!BI.isVirtual()) {
7155 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007156 if (base->isEmpty())
7157 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007158 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007159 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7160 std::make_pair(offs, base));
7161 }
7162 }
7163 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007164
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007165 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00007166 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007167 uint64_t offs = layout.getFieldOffset(i);
7168 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00007169 std::make_pair(offs, Field));
7170 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007171 }
7172
7173 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00007174 for (const auto &BI : CXXRec->vbases()) {
7175 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007176 if (base->isEmpty())
7177 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007178 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00007179 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7180 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00007181 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7182 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007183 }
7184 }
7185
7186 CharUnits size;
7187 if (CXXRec) {
7188 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7189 } else {
7190 size = layout.getSize();
7191 }
7192
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007193#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007194 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007195#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007196 std::multimap<uint64_t, NamedDecl *>::iterator
7197 CurLayObj = FieldOrBaseOffsets.begin();
7198
Douglas Gregorf5d6c742012-04-27 22:30:01 +00007199 if (CXXRec && CXXRec->isDynamicClass() &&
7200 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007201 if (FD) {
7202 S += "\"_vptr$";
7203 std::string recname = CXXRec->getNameAsString();
7204 if (recname.empty()) recname = "?";
7205 S += recname;
7206 S += '"';
7207 }
7208 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007209#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007210 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007211#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007212 }
7213
7214 if (!RDecl->hasFlexibleArrayMember()) {
7215 // Mark the end of the structure.
7216 uint64_t offs = toBits(size);
7217 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00007218 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007219 }
7220
7221 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007222#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007223 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007224 if (CurOffs < CurLayObj->first) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007225 uint64_t padding = CurLayObj->first - CurOffs;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007226 // FIXME: There doesn't seem to be a way to indicate in the encoding that
7227 // packing/alignment of members is different that normal, in which case
7228 // the encoding will be out-of-sync with the real layout.
7229 // If the runtime switches to just consider the size of types without
7230 // taking into account alignment, we could make padding explicit in the
7231 // encoding (e.g. using arrays of chars). The encoding strings would be
7232 // longer then though.
7233 CurOffs += padding;
7234 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007235#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007236
7237 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00007238 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007239 break; // reached end of structure.
7240
Eugene Zelenko7855e772018-04-03 00:11:50 +00007241 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007242 // We expand the bases without their virtual bases since those are going
7243 // in the initial structure. Note that this differs from gcc which
7244 // expands virtual bases each time one is encountered in the hierarchy,
7245 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007246 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7247 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007248 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007249#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007250 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007251#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007252 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007253 const auto *field = cast<FieldDecl>(dcl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007254 if (FD) {
7255 S += '"';
7256 S += field->getNameAsString();
7257 S += '"';
7258 }
7259
7260 if (field->isBitField()) {
7261 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007262#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00007263 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007264#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007265 } else {
7266 QualType qt = field->getType();
7267 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00007268 getObjCEncodingForTypeImpl(
Nico Weber2e9591c2019-05-14 12:32:37 +00007269 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7270 FD, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007271#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007272 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007273#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007274 }
7275 }
7276 }
7277}
7278
Mike Stump11289f42009-09-09 15:08:12 +00007279void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00007280 std::string& S) const {
7281 if (QT & Decl::OBJC_TQ_In)
7282 S += 'n';
7283 if (QT & Decl::OBJC_TQ_Inout)
7284 S += 'N';
7285 if (QT & Decl::OBJC_TQ_Out)
7286 S += 'o';
7287 if (QT & Decl::OBJC_TQ_Bycopy)
7288 S += 'O';
7289 if (QT & Decl::OBJC_TQ_Byref)
7290 S += 'R';
7291 if (QT & Decl::OBJC_TQ_Oneway)
7292 S += 'V';
7293}
7294
Douglas Gregor3ea72692011-08-12 05:46:01 +00007295TypedefDecl *ASTContext::getObjCIdDecl() const {
7296 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007297 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00007298 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007299 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00007300 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00007301 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00007302}
7303
Douglas Gregor52e02802011-08-12 06:17:30 +00007304TypedefDecl *ASTContext::getObjCSelDecl() const {
7305 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007306 QualType T = getPointerType(ObjCBuiltinSelTy);
7307 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00007308 }
7309 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00007310}
7311
Douglas Gregor0a586182011-08-12 05:59:41 +00007312TypedefDecl *ASTContext::getObjCClassDecl() const {
7313 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007314 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00007315 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007316 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00007317 }
Douglas Gregor0a586182011-08-12 05:59:41 +00007318 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00007319}
7320
Douglas Gregord53ae832012-01-17 18:09:05 +00007321ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7322 if (!ObjCProtocolClassDecl) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007323 ObjCProtocolClassDecl
7324 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregord53ae832012-01-17 18:09:05 +00007325 SourceLocation(),
7326 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00007327 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00007328 /*PrevDecl=*/nullptr,
Fangrui Song6907ce22018-07-30 19:24:48 +00007329 SourceLocation(), true);
Douglas Gregord53ae832012-01-17 18:09:05 +00007330 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007331
Douglas Gregord53ae832012-01-17 18:09:05 +00007332 return ObjCProtocolClassDecl;
7333}
7334
Meador Inge5d3fb222012-06-16 03:34:49 +00007335//===----------------------------------------------------------------------===//
7336// __builtin_va_list Construction Functions
7337//===----------------------------------------------------------------------===//
7338
Charles Davisc7d5c942015-09-17 20:55:33 +00007339static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7340 StringRef Name) {
7341 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007342 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00007343 return Context->buildImplicitTypedef(T, Name);
7344}
7345
7346static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7347 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7348}
7349
7350static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7351 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007352}
7353
7354static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7355 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007356 QualType T = Context->getPointerType(Context->VoidTy);
7357 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007358}
7359
Tim Northover9bb857a2013-01-31 12:13:10 +00007360static TypedefDecl *
7361CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007362 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007363 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007364 if (Context->getLangOpts().CPlusPlus) {
7365 // namespace std { struct __va_list {
7366 NamespaceDecl *NS;
7367 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7368 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00007369 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00007370 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007371 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007372 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00007373 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00007374 }
7375
7376 VaListTagDecl->startDefinition();
7377
7378 const size_t NumFields = 5;
7379 QualType FieldTypes[NumFields];
7380 const char *FieldNames[NumFields];
7381
7382 // void *__stack;
7383 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7384 FieldNames[0] = "__stack";
7385
7386 // void *__gr_top;
7387 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7388 FieldNames[1] = "__gr_top";
7389
7390 // void *__vr_top;
7391 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7392 FieldNames[2] = "__vr_top";
7393
7394 // int __gr_offs;
7395 FieldTypes[3] = Context->IntTy;
7396 FieldNames[3] = "__gr_offs";
7397
7398 // int __vr_offs;
7399 FieldTypes[4] = Context->IntTy;
7400 FieldNames[4] = "__vr_offs";
7401
7402 // Create fields
7403 for (unsigned i = 0; i < NumFields; ++i) {
7404 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7405 VaListTagDecl,
7406 SourceLocation(),
7407 SourceLocation(),
7408 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007409 FieldTypes[i], /*TInfo=*/nullptr,
7410 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00007411 /*Mutable=*/false,
7412 ICIS_NoInit);
7413 Field->setAccess(AS_public);
7414 VaListTagDecl->addDecl(Field);
7415 }
7416 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007417 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00007418 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00007419
7420 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007421 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007422}
7423
Meador Inge5d3fb222012-06-16 03:34:49 +00007424static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7425 // typedef struct __va_list_tag {
7426 RecordDecl *VaListTagDecl;
7427
Alp Toker2dea15b2013-12-17 01:22:38 +00007428 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007429 VaListTagDecl->startDefinition();
7430
7431 const size_t NumFields = 5;
7432 QualType FieldTypes[NumFields];
7433 const char *FieldNames[NumFields];
7434
7435 // unsigned char gpr;
7436 FieldTypes[0] = Context->UnsignedCharTy;
7437 FieldNames[0] = "gpr";
7438
7439 // unsigned char fpr;
7440 FieldTypes[1] = Context->UnsignedCharTy;
7441 FieldNames[1] = "fpr";
7442
7443 // unsigned short reserved;
7444 FieldTypes[2] = Context->UnsignedShortTy;
7445 FieldNames[2] = "reserved";
7446
7447 // void* overflow_arg_area;
7448 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7449 FieldNames[3] = "overflow_arg_area";
7450
7451 // void* reg_save_area;
7452 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7453 FieldNames[4] = "reg_save_area";
7454
7455 // Create fields
7456 for (unsigned i = 0; i < NumFields; ++i) {
7457 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7458 SourceLocation(),
7459 SourceLocation(),
7460 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007461 FieldTypes[i], /*TInfo=*/nullptr,
7462 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007463 /*Mutable=*/false,
7464 ICIS_NoInit);
7465 Field->setAccess(AS_public);
7466 VaListTagDecl->addDecl(Field);
7467 }
7468 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007469 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007470 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7471
7472 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007473 TypedefDecl *VaListTagTypedefDecl =
7474 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7475
Meador Inge5d3fb222012-06-16 03:34:49 +00007476 QualType VaListTagTypedefType =
7477 Context->getTypedefType(VaListTagTypedefDecl);
7478
7479 // typedef __va_list_tag __builtin_va_list[1];
7480 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7481 QualType VaListTagArrayType
7482 = Context->getConstantArrayType(VaListTagTypedefType,
Richard Smith772e2662019-10-04 01:25:59 +00007483 Size, nullptr, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007484 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007485}
7486
7487static TypedefDecl *
7488CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007489 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007490 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007491 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007492 VaListTagDecl->startDefinition();
7493
7494 const size_t NumFields = 4;
7495 QualType FieldTypes[NumFields];
7496 const char *FieldNames[NumFields];
7497
7498 // unsigned gp_offset;
7499 FieldTypes[0] = Context->UnsignedIntTy;
7500 FieldNames[0] = "gp_offset";
7501
7502 // unsigned fp_offset;
7503 FieldTypes[1] = Context->UnsignedIntTy;
7504 FieldNames[1] = "fp_offset";
7505
7506 // void* overflow_arg_area;
7507 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7508 FieldNames[2] = "overflow_arg_area";
7509
7510 // void* reg_save_area;
7511 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7512 FieldNames[3] = "reg_save_area";
7513
7514 // Create fields
7515 for (unsigned i = 0; i < NumFields; ++i) {
7516 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7517 VaListTagDecl,
7518 SourceLocation(),
7519 SourceLocation(),
7520 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007521 FieldTypes[i], /*TInfo=*/nullptr,
7522 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007523 /*Mutable=*/false,
7524 ICIS_NoInit);
7525 Field->setAccess(AS_public);
7526 VaListTagDecl->addDecl(Field);
7527 }
7528 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007529 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007530 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7531
Richard Smith9b88a4c2015-07-27 05:40:23 +00007532 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007533
Richard Smith9b88a4c2015-07-27 05:40:23 +00007534 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007535 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith772e2662019-10-04 01:25:59 +00007536 QualType VaListTagArrayType = Context->getConstantArrayType(
7537 VaListTagType, Size, nullptr, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007538 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007539}
7540
7541static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7542 // typedef int __builtin_va_list[4];
7543 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Richard Smith772e2662019-10-04 01:25:59 +00007544 QualType IntArrayType = Context->getConstantArrayType(
7545 Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007546 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007547}
7548
Logan Chien57086ce2012-10-10 06:56:20 +00007549static TypedefDecl *
7550CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007551 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007552 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007553 if (Context->getLangOpts().CPlusPlus) {
7554 // namespace std { struct __va_list {
7555 NamespaceDecl *NS;
7556 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7557 Context->getTranslationUnitDecl(),
7558 /*Inline*/false, SourceLocation(),
7559 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007560 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007561 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007562 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007563 }
7564
7565 VaListDecl->startDefinition();
7566
7567 // void * __ap;
7568 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7569 VaListDecl,
7570 SourceLocation(),
7571 SourceLocation(),
7572 &Context->Idents.get("__ap"),
7573 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007574 /*TInfo=*/nullptr,
7575 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007576 /*Mutable=*/false,
7577 ICIS_NoInit);
7578 Field->setAccess(AS_public);
7579 VaListDecl->addDecl(Field);
7580
7581 // };
7582 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007583 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007584
7585 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007586 QualType T = Context->getRecordType(VaListDecl);
7587 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007588}
7589
Ulrich Weigand47445072013-05-06 16:26:41 +00007590static TypedefDecl *
7591CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007592 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007593 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007594 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007595 VaListTagDecl->startDefinition();
7596
7597 const size_t NumFields = 4;
7598 QualType FieldTypes[NumFields];
7599 const char *FieldNames[NumFields];
7600
7601 // long __gpr;
7602 FieldTypes[0] = Context->LongTy;
7603 FieldNames[0] = "__gpr";
7604
7605 // long __fpr;
7606 FieldTypes[1] = Context->LongTy;
7607 FieldNames[1] = "__fpr";
7608
7609 // void *__overflow_arg_area;
7610 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7611 FieldNames[2] = "__overflow_arg_area";
7612
7613 // void *__reg_save_area;
7614 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7615 FieldNames[3] = "__reg_save_area";
7616
7617 // Create fields
7618 for (unsigned i = 0; i < NumFields; ++i) {
7619 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7620 VaListTagDecl,
7621 SourceLocation(),
7622 SourceLocation(),
7623 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007624 FieldTypes[i], /*TInfo=*/nullptr,
7625 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007626 /*Mutable=*/false,
7627 ICIS_NoInit);
7628 Field->setAccess(AS_public);
7629 VaListTagDecl->addDecl(Field);
7630 }
7631 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007632 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007633 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007634
Richard Smith9b88a4c2015-07-27 05:40:23 +00007635 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007636
7637 // typedef __va_list_tag __builtin_va_list[1];
7638 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith772e2662019-10-04 01:25:59 +00007639 QualType VaListTagArrayType = Context->getConstantArrayType(
7640 VaListTagType, Size, nullptr, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007641
Alp Toker56b5cc92013-12-15 10:36:26 +00007642 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007643}
7644
Meador Inge5d3fb222012-06-16 03:34:49 +00007645static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7646 TargetInfo::BuiltinVaListKind Kind) {
7647 switch (Kind) {
7648 case TargetInfo::CharPtrBuiltinVaList:
7649 return CreateCharPtrBuiltinVaListDecl(Context);
7650 case TargetInfo::VoidPtrBuiltinVaList:
7651 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007652 case TargetInfo::AArch64ABIBuiltinVaList:
7653 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007654 case TargetInfo::PowerABIBuiltinVaList:
7655 return CreatePowerABIBuiltinVaListDecl(Context);
7656 case TargetInfo::X86_64ABIBuiltinVaList:
7657 return CreateX86_64ABIBuiltinVaListDecl(Context);
7658 case TargetInfo::PNaClABIBuiltinVaList:
7659 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007660 case TargetInfo::AAPCSABIBuiltinVaList:
7661 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007662 case TargetInfo::SystemZBuiltinVaList:
7663 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007664 }
7665
7666 llvm_unreachable("Unhandled __builtin_va_list type kind");
7667}
7668
7669TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007670 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007671 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007672 assert(BuiltinVaListDecl->isImplicit());
7673 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007674
7675 return BuiltinVaListDecl;
7676}
7677
Richard Smith9b88a4c2015-07-27 05:40:23 +00007678Decl *ASTContext::getVaListTagDecl() const {
7679 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007680 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007681 if (!VaListTagDecl)
7682 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007683
Richard Smith9b88a4c2015-07-27 05:40:23 +00007684 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007685}
7686
Charles Davisc7d5c942015-09-17 20:55:33 +00007687TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7688 if (!BuiltinMSVaListDecl)
7689 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7690
7691 return BuiltinMSVaListDecl;
7692}
7693
Erich Keane41af9712018-04-16 21:30:08 +00007694bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
7695 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
7696}
7697
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007698void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007699 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007700 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007701
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007702 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007703}
7704
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007705/// Retrieve the template name that corresponds to a non-empty
John McCalld28ae272009-12-02 08:04:21 +00007706/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007707TemplateName
7708ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7709 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007710 unsigned size = End - Begin;
7711 assert(size > 1 && "set is not overloaded!");
7712
7713 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7714 size * sizeof(FunctionTemplateDecl*));
Eugene Zelenko7855e772018-04-03 00:11:50 +00007715 auto *OT = new (memory) OverloadedTemplateStorage(size);
John McCalld28ae272009-12-02 08:04:21 +00007716
7717 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007718 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007719 NamedDecl *D = *I;
7720 assert(isa<FunctionTemplateDecl>(D) ||
Richard Smithef53a3e2018-06-06 16:36:56 +00007721 isa<UnresolvedUsingValueDecl>(D) ||
John McCalld28ae272009-12-02 08:04:21 +00007722 (isa<UsingShadowDecl>(D) &&
7723 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7724 *Storage++ = D;
7725 }
7726
7727 return TemplateName(OT);
7728}
7729
Richard Smithb23c5e82019-05-09 03:31:27 +00007730/// Retrieve a template name representing an unqualified-id that has been
7731/// assumed to name a template for ADL purposes.
7732TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
7733 auto *OT = new (*this) AssumedTemplateStorage(Name);
7734 return TemplateName(OT);
7735}
7736
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007737/// Retrieve the template name that represents a qualified
Douglas Gregordc572a32009-03-30 22:58:21 +00007738/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007739TemplateName
7740ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7741 bool TemplateKeyword,
7742 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007743 assert(NNS && "Missing nested-name-specifier in qualified template name");
Fangrui Song6907ce22018-07-30 19:24:48 +00007744
Douglas Gregorc42075a2010-02-04 18:10:26 +00007745 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007746 llvm::FoldingSetNodeID ID;
7747 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7748
Craig Topper36250ad2014-05-12 05:36:57 +00007749 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007750 QualifiedTemplateName *QTN =
7751 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7752 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007753 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007754 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007755 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7756 }
7757
7758 return TemplateName(QTN);
7759}
7760
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007761/// Retrieve the template name that represents a dependent
Douglas Gregordc572a32009-03-30 22:58:21 +00007762/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007763TemplateName
7764ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7765 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007766 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007767 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007768
7769 llvm::FoldingSetNodeID ID;
7770 DependentTemplateName::Profile(ID, NNS, Name);
7771
Craig Topper36250ad2014-05-12 05:36:57 +00007772 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007773 DependentTemplateName *QTN =
7774 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7775
7776 if (QTN)
7777 return TemplateName(QTN);
7778
7779 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7780 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007781 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007782 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007783 } else {
7784 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007785 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007786 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007787 DependentTemplateName *CheckQTN =
7788 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7789 assert(!CheckQTN && "Dependent type name canonicalization broken");
7790 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007791 }
7792
7793 DependentTemplateNames.InsertNode(QTN, InsertPos);
7794 return TemplateName(QTN);
7795}
7796
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007797/// Retrieve the template name that represents a dependent
Douglas Gregor71395fa2009-11-04 00:56:37 +00007798/// template name such as \c MetaFun::template operator+.
Fangrui Song6907ce22018-07-30 19:24:48 +00007799TemplateName
Douglas Gregor71395fa2009-11-04 00:56:37 +00007800ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007801 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007802 assert((!NNS || NNS->isDependent()) &&
7803 "Nested name specifier must be dependent");
Fangrui Song6907ce22018-07-30 19:24:48 +00007804
Douglas Gregor71395fa2009-11-04 00:56:37 +00007805 llvm::FoldingSetNodeID ID;
7806 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007807
7808 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007809 DependentTemplateName *QTN
7810 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007811
Douglas Gregor71395fa2009-11-04 00:56:37 +00007812 if (QTN)
7813 return TemplateName(QTN);
Fangrui Song6907ce22018-07-30 19:24:48 +00007814
Douglas Gregor71395fa2009-11-04 00:56:37 +00007815 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7816 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007817 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007818 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007819 } else {
7820 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007821 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007822 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007823
Douglas Gregorc42075a2010-02-04 18:10:26 +00007824 DependentTemplateName *CheckQTN
7825 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7826 assert(!CheckQTN && "Dependent template name canonicalization broken");
7827 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007828 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007829
Douglas Gregor71395fa2009-11-04 00:56:37 +00007830 DependentTemplateNames.InsertNode(QTN, InsertPos);
7831 return TemplateName(QTN);
7832}
7833
Fangrui Song6907ce22018-07-30 19:24:48 +00007834TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007835ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7836 TemplateName replacement) const {
7837 llvm::FoldingSetNodeID ID;
7838 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007839
7840 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007841 SubstTemplateTemplateParmStorage *subst
7842 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007843
John McCalld9dfe3a2011-06-30 08:33:18 +00007844 if (!subst) {
7845 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7846 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7847 }
7848
7849 return TemplateName(subst);
7850}
7851
Fangrui Song6907ce22018-07-30 19:24:48 +00007852TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007853ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7854 const TemplateArgument &ArgPack) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007855 auto &Self = const_cast<ASTContext &>(*this);
Douglas Gregor5590be02011-01-15 06:45:20 +00007856 llvm::FoldingSetNodeID ID;
7857 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007858
7859 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007860 SubstTemplateTemplateParmPackStorage *Subst
7861 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007862
Douglas Gregor5590be02011-01-15 06:45:20 +00007863 if (!Subst) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007864 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007865 ArgPack.pack_size(),
7866 ArgPack.pack_begin());
7867 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7868 }
7869
7870 return TemplateName(Subst);
7871}
7872
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007873/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007874/// TargetInfo, produce the corresponding type. The unsigned @p Type
7875/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007876CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007877 switch (Type) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007878 case TargetInfo::NoInt: return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007879 case TargetInfo::SignedChar: return SignedCharTy;
7880 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007881 case TargetInfo::SignedShort: return ShortTy;
7882 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7883 case TargetInfo::SignedInt: return IntTy;
7884 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7885 case TargetInfo::SignedLong: return LongTy;
7886 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7887 case TargetInfo::SignedLongLong: return LongLongTy;
7888 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7889 }
7890
David Blaikie83d382b2011-09-23 05:06:16 +00007891 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007892}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007893
7894//===----------------------------------------------------------------------===//
7895// Type Predicates.
7896//===----------------------------------------------------------------------===//
7897
Fariborz Jahanian96207692009-02-18 21:49:28 +00007898/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7899/// garbage collection attribute.
7900///
John McCall553d45a2011-01-12 00:34:59 +00007901Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007902 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007903 return Qualifiers::GCNone;
7904
Erik Pilkingtonfa983902018-10-30 20:31:30 +00007905 assert(getLangOpts().ObjC);
John McCall553d45a2011-01-12 00:34:59 +00007906 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7907
7908 // Default behaviour under objective-C's gc is for ObjC pointers
7909 // (or pointers to them) be treated as though they were declared
7910 // as __strong.
7911 if (GCAttrs == Qualifiers::GCNone) {
7912 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7913 return Qualifiers::Strong;
7914 else if (Ty->isPointerType())
Simon Pilgrimeed4b122019-10-02 11:48:06 +00007915 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
John McCall553d45a2011-01-12 00:34:59 +00007916 } else {
7917 // It's not valid to set GC attributes on anything that isn't a
7918 // pointer.
7919#ifndef NDEBUG
7920 QualType CT = Ty->getCanonicalTypeInternal();
Eugene Zelenko7855e772018-04-03 00:11:50 +00007921 while (const auto *AT = dyn_cast<ArrayType>(CT))
John McCall553d45a2011-01-12 00:34:59 +00007922 CT = AT->getElementType();
7923 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7924#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007925 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007926 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007927}
7928
Chris Lattner49af6a42008-04-07 06:51:04 +00007929//===----------------------------------------------------------------------===//
7930// Type Compatibility Testing
7931//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007932
Mike Stump11289f42009-09-09 15:08:12 +00007933/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007934/// compatible.
7935static bool areCompatVectorTypes(const VectorType *LHS,
7936 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007937 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007938 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007939 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007940}
7941
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007942bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7943 QualType SecondVec) {
7944 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7945 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7946
7947 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7948 return true;
7949
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007950 // Treat Neon vector types and most AltiVec vector types as if they are the
7951 // equivalent GCC vector types.
Simon Pilgrimeed4b122019-10-02 11:48:06 +00007952 const auto *First = FirstVec->castAs<VectorType>();
7953 const auto *Second = SecondVec->castAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007954 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007955 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007956 First->getVectorKind() != VectorType::AltiVecPixel &&
7957 First->getVectorKind() != VectorType::AltiVecBool &&
7958 Second->getVectorKind() != VectorType::AltiVecPixel &&
7959 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007960 return true;
7961
7962 return false;
7963}
7964
Akira Hatanaka3f2c9912019-09-07 00:34:47 +00007965bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
7966 while (true) {
7967 // __strong id
7968 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
7969 if (Attr->getAttrKind() == attr::ObjCOwnership)
7970 return true;
7971
7972 Ty = Attr->getModifiedType();
7973
7974 // X *__strong (...)
7975 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
7976 Ty = Paren->getInnerType();
7977
7978 // We do not want to look through typedefs, typeof(expr),
7979 // typeof(type), or any other way that the type is somehow
7980 // abstracted.
7981 } else {
7982 return false;
7983 }
7984 }
7985}
7986
Steve Naroff8e6aee52009-07-23 01:01:38 +00007987//===----------------------------------------------------------------------===//
7988// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7989//===----------------------------------------------------------------------===//
7990
7991/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7992/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007993bool
7994ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7995 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007996 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007997 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007998 for (auto *PI : rProto->protocols())
7999 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00008000 return true;
8001 return false;
8002}
8003
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00008004/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
8005/// Class<pr1, ...>.
James Y Knightc2ca0032019-09-21 22:31:28 +00008006bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
8007 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
8008 for (auto *lhsProto : lhs->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00008009 bool match = false;
James Y Knightc2ca0032019-09-21 22:31:28 +00008010 for (auto *rhsProto : rhs->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00008011 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
8012 match = true;
8013 break;
8014 }
8015 }
8016 if (!match)
8017 return false;
8018 }
8019 return true;
8020}
8021
Steve Naroff8e6aee52009-07-23 01:01:38 +00008022/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
8023/// ObjCQualifiedIDType.
James Y Knightc2ca0032019-09-21 22:31:28 +00008024bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
8025 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
8026 bool compare) {
James Y Knightccc4d832019-10-17 15:27:04 +00008027 // Allow id<P..> and an 'id' in all cases.
8028 if (lhs->isObjCIdType() || rhs->isObjCIdType())
Steve Naroff8e6aee52009-07-23 01:01:38 +00008029 return true;
James Y Knightccc4d832019-10-17 15:27:04 +00008030
8031 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
8032 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
8033 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
8034 return false;
Steve Naroff8e6aee52009-07-23 01:01:38 +00008035
James Y Knightc2ca0032019-09-21 22:31:28 +00008036 if (lhs->isObjCQualifiedIdType()) {
8037 if (rhs->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00008038 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00008039 // make sure we check the class hierarchy.
James Y Knightc2ca0032019-09-21 22:31:28 +00008040 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8041 for (auto *I : lhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008042 // when comparing an id<P> on lhs with a static type on rhs,
8043 // see if static class implements all of id's protocols, directly or
8044 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00008045 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00008046 return false;
8047 }
8048 }
8049 // If there are no qualifiers and no interface, we have an 'id'.
8050 return true;
8051 }
Mike Stump11289f42009-09-09 15:08:12 +00008052 // Both the right and left sides have qualifiers.
James Y Knightc2ca0032019-09-21 22:31:28 +00008053 for (auto *lhsProto : lhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008054 bool match = false;
8055
8056 // when comparing an id<P> on lhs with a static type on rhs,
8057 // see if static class implements all of id's protocols, directly or
8058 // through its super class and categories.
James Y Knightc2ca0032019-09-21 22:31:28 +00008059 for (auto *rhsProto : rhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008060 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8061 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8062 match = true;
8063 break;
8064 }
8065 }
Mike Stump11289f42009-09-09 15:08:12 +00008066 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00008067 // make sure we check the class hierarchy.
James Y Knightc2ca0032019-09-21 22:31:28 +00008068 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8069 for (auto *I : lhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008070 // when comparing an id<P> on lhs with a static type on rhs,
8071 // see if static class implements all of id's protocols, directly or
8072 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00008073 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008074 match = true;
8075 break;
8076 }
8077 }
8078 }
8079 if (!match)
8080 return false;
8081 }
Mike Stump11289f42009-09-09 15:08:12 +00008082
Steve Naroff8e6aee52009-07-23 01:01:38 +00008083 return true;
8084 }
Mike Stump11289f42009-09-09 15:08:12 +00008085
James Y Knightc2ca0032019-09-21 22:31:28 +00008086 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
Steve Naroff8e6aee52009-07-23 01:01:38 +00008087
James Y Knightc2ca0032019-09-21 22:31:28 +00008088 if (lhs->getInterfaceType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008089 // If both the right and left sides have qualifiers.
James Y Knightc2ca0032019-09-21 22:31:28 +00008090 for (auto *lhsProto : lhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008091 bool match = false;
8092
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008093 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00008094 // see if static class implements all of id's protocols, directly or
8095 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008096 // First, lhs protocols in the qualifier list must be found, direct
8097 // or indirect in rhs's qualifier list or it is a mismatch.
James Y Knightc2ca0032019-09-21 22:31:28 +00008098 for (auto *rhsProto : rhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008099 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8100 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8101 match = true;
8102 break;
8103 }
8104 }
8105 if (!match)
8106 return false;
8107 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008108
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008109 // Static class's protocols, or its super class or category protocols
8110 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
James Y Knightc2ca0032019-09-21 22:31:28 +00008111 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008112 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8113 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8114 // This is rather dubious but matches gcc's behavior. If lhs has
8115 // no type qualifier and its class has no static protocol(s)
8116 // assume that it is mismatch.
James Y Knightc2ca0032019-09-21 22:31:28 +00008117 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008118 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00008119 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008120 bool match = false;
James Y Knightc2ca0032019-09-21 22:31:28 +00008121 for (auto *rhsProto : rhs->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008122 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8123 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8124 match = true;
8125 break;
8126 }
8127 }
8128 if (!match)
8129 return false;
8130 }
8131 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00008132 return true;
8133 }
8134 return false;
8135}
8136
Eli Friedman47f77112008-08-22 00:56:42 +00008137/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00008138/// compatible for assignment from RHS to LHS. This handles validation of any
8139/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00008140bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
8141 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00008142 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8143 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8144
James Y Knightccc4d832019-10-17 15:27:04 +00008145 // If either type represents the built-in 'id' type, return true.
8146 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
Steve Naroff7cae42b2009-07-10 23:34:53 +00008147 return true;
8148
Douglas Gregorab209d82015-07-07 03:58:42 +00008149 // Function object that propagates a successful result or handles
8150 // __kindof types.
8151 auto finish = [&](bool succeeded) -> bool {
8152 if (succeeded)
8153 return true;
8154
8155 if (!RHS->isKindOfType())
8156 return false;
8157
8158 // Strip off __kindof and protocol qualifiers, then check whether
8159 // we can assign the other way.
8160 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8161 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8162 };
8163
James Y Knightccc4d832019-10-17 15:27:04 +00008164 // Casts from or to id<P> are allowed when the other side has compatible
8165 // protocols.
Douglas Gregorab209d82015-07-07 03:58:42 +00008166 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
James Y Knightc2ca0032019-09-21 22:31:28 +00008167 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
Douglas Gregorab209d82015-07-07 03:58:42 +00008168 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008169
James Y Knightccc4d832019-10-17 15:27:04 +00008170 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
Douglas Gregorab209d82015-07-07 03:58:42 +00008171 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
James Y Knightc2ca0032019-09-21 22:31:28 +00008172 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
Douglas Gregorab209d82015-07-07 03:58:42 +00008173 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008174
James Y Knightccc4d832019-10-17 15:27:04 +00008175 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
8176 if (LHS->isObjCClass() && RHS->isObjCClass()) {
8177 return true;
8178 }
8179
John McCall8b07ec22010-05-15 11:32:37 +00008180 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00008181 if (LHS->getInterface() && RHS->getInterface()) {
8182 return finish(canAssignObjCInterfaces(LHS, RHS));
8183 }
Mike Stump11289f42009-09-09 15:08:12 +00008184
Steve Naroff8e6aee52009-07-23 01:01:38 +00008185 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008186}
8187
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008188/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Fangrui Song6907ce22018-07-30 19:24:48 +00008189/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008190/// arguments in block literals. When passed as arguments, passing 'A*' where
8191/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8192/// not OK. For the return type, the opposite is not OK.
8193bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8194 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008195 const ObjCObjectPointerType *RHSOPT,
8196 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008197
8198 // Function object that propagates a successful result or handles
8199 // __kindof types.
8200 auto finish = [&](bool succeeded) -> bool {
8201 if (succeeded)
8202 return true;
8203
8204 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8205 if (!Expected->isKindOfType())
8206 return false;
8207
8208 // Strip off __kindof and protocol qualifiers, then check whether
8209 // we can assign the other way.
8210 return canAssignObjCInterfacesInBlockPointer(
8211 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8212 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8213 BlockReturnType);
8214 };
8215
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008216 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008217 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00008218
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008219 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008220 return finish(RHSOPT->isObjCBuiltinType() ||
8221 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008222 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008223
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008224 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Volodymyr Sapsai73152a22019-08-28 00:25:06 +00008225 return finish(ObjCQualifiedIdTypesAreCompatible(
James Y Knightc2ca0032019-09-21 22:31:28 +00008226 (BlockReturnType ? LHSOPT : RHSOPT),
8227 (BlockReturnType ? RHSOPT : LHSOPT), false));
Fangrui Song6907ce22018-07-30 19:24:48 +00008228
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008229 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8230 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8231 if (LHS && RHS) { // We have 2 user-defined types.
8232 if (LHS != RHS) {
8233 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008234 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008235 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008236 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008237 }
8238 else
8239 return true;
8240 }
8241 return false;
8242}
8243
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008244/// Comparison routine for Objective-C protocols to be used with
8245/// llvm::array_pod_sort.
8246static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8247 ObjCProtocolDecl * const *rhs) {
8248 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008249}
8250
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008251/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008252/// of protocols inherited from two distinct objective-c pointer objects with
8253/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008254/// It is used to build composite qualifier list of the composite type of
8255/// the conditional expression involving two objective-c pointer objects.
Fangrui Song6907ce22018-07-30 19:24:48 +00008256static
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008257void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008258 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008259 const ObjCObjectPointerType *LHSOPT,
8260 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008261 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008262
John McCall8b07ec22010-05-15 11:32:37 +00008263 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8264 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8265 assert(LHS->getInterface() && "LHS must have an interface base");
8266 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008267
8268 // Add all of the protocols for the LHS.
8269 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8270
8271 // Start with the protocol qualifiers.
8272 for (auto proto : LHS->quals()) {
8273 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008274 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008275
8276 // Also add the protocols associated with the LHS interface.
8277 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8278
Raphael Isemannb23ccec2018-12-10 12:37:46 +00008279 // Add all of the protocols for the RHS.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008280 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8281
8282 // Start with the protocol qualifiers.
8283 for (auto proto : RHS->quals()) {
8284 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008285 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008286
8287 // Also add the protocols associated with the RHS interface.
8288 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8289
8290 // Compute the intersection of the collected protocol sets.
8291 for (auto proto : LHSProtocolSet) {
8292 if (RHSProtocolSet.count(proto))
8293 IntersectionSet.push_back(proto);
8294 }
8295
8296 // Compute the set of protocols that is implied by either the common type or
8297 // the protocols within the intersection.
8298 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8299 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8300
8301 // Remove any implied protocols from the list of inherited protocols.
8302 if (!ImpliedProtocols.empty()) {
8303 IntersectionSet.erase(
8304 std::remove_if(IntersectionSet.begin(),
8305 IntersectionSet.end(),
8306 [&](ObjCProtocolDecl *proto) -> bool {
8307 return ImpliedProtocols.count(proto) > 0;
8308 }),
8309 IntersectionSet.end());
8310 }
8311
8312 // Sort the remaining protocols by name.
8313 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8314 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008315}
8316
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008317/// Determine whether the first type is a subtype of the second.
8318static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8319 QualType rhs) {
8320 // Common case: two object pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008321 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8322 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008323 if (lhsOPT && rhsOPT)
8324 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8325
8326 // Two block pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008327 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8328 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008329 if (lhsBlock && rhsBlock)
8330 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8331
8332 // If either is an unqualified 'id' and the other is a block, it's
8333 // acceptable.
8334 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8335 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8336 return true;
8337
8338 return false;
8339}
8340
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008341// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008342static bool sameObjCTypeArgs(ASTContext &ctx,
8343 const ObjCInterfaceDecl *iface,
8344 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00008345 ArrayRef<QualType> rhsArgs,
8346 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008347 if (lhsArgs.size() != rhsArgs.size())
8348 return false;
8349
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008350 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008351 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008352 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8353 continue;
8354
8355 switch (typeParams->begin()[i]->getVariance()) {
8356 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00008357 if (!stripKindOf ||
8358 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8359 rhsArgs[i].stripObjCKindOfType(ctx))) {
8360 return false;
8361 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008362 break;
8363
8364 case ObjCTypeParamVariance::Covariant:
8365 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8366 return false;
8367 break;
8368
8369 case ObjCTypeParamVariance::Contravariant:
8370 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8371 return false;
8372 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00008373 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008374 }
8375
8376 return true;
8377}
8378
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008379QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008380 const ObjCObjectPointerType *Lptr,
8381 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00008382 const ObjCObjectType *LHS = Lptr->getObjectType();
8383 const ObjCObjectType *RHS = Rptr->getObjectType();
8384 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8385 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008386
8387 if (!LDecl || !RDecl)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008388 return {};
Douglas Gregore83b9562015-07-07 03:57:53 +00008389
Manman Renc46f7d12016-05-06 19:35:02 +00008390 // When either LHS or RHS is a kindof type, we should return a kindof type.
8391 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8392 // kindof(A).
8393 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8394
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008395 // Follow the left-hand side up the class hierarchy until we either hit a
8396 // root or find the RHS. Record the ancestors in case we don't find it.
8397 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8398 LHSAncestors;
8399 while (true) {
8400 // Record this ancestor. We'll need this if the common type isn't in the
8401 // path from the LHS to the root.
8402 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00008403
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008404 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8405 // Get the type arguments.
8406 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8407 bool anyChanges = false;
8408 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8409 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008410 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8411 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008412 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008413 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008414 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8415 // If only one has type arguments, the result will not have type
8416 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008417 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008418 anyChanges = true;
8419 }
8420
8421 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008422 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008423 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8424 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00008425 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008426 anyChanges = true;
8427
8428 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00008429 // If we need to return a kindof type but LHS is not a kindof type, we
8430 // build a new result type.
8431 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008432 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008433 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008434 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008435 return getObjCObjectPointerType(Result);
8436 }
8437
8438 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008439 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008440
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008441 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00008442 QualType LHSSuperType = LHS->getSuperClassType();
8443 if (LHSSuperType.isNull())
8444 break;
8445
8446 LHS = LHSSuperType->castAs<ObjCObjectType>();
8447 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008448
8449 // We didn't find anything by following the LHS to its root; now check
8450 // the RHS against the cached set of ancestors.
8451 while (true) {
8452 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8453 if (KnownLHS != LHSAncestors.end()) {
8454 LHS = KnownLHS->second;
8455
8456 // Get the type arguments.
8457 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8458 bool anyChanges = false;
8459 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8460 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008461 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8462 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008463 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008464 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008465 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8466 // If only one has type arguments, the result will not have type
8467 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008468 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008469 anyChanges = true;
8470 }
8471
8472 // Compute the intersection of protocols.
8473 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8474 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8475 Protocols);
8476 if (!Protocols.empty())
8477 anyChanges = true;
8478
Manman Renc46f7d12016-05-06 19:35:02 +00008479 // If we need to return a kindof type but RHS is not a kindof type, we
8480 // build a new result type.
8481 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008482 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008483 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008484 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008485 return getObjCObjectPointerType(Result);
8486 }
8487
8488 return getObjCObjectPointerType(QualType(RHS, 0));
8489 }
8490
8491 // Find the superclass of the RHS.
8492 QualType RHSSuperType = RHS->getSuperClassType();
8493 if (RHSSuperType.isNull())
8494 break;
8495
8496 RHS = RHSSuperType->castAs<ObjCObjectType>();
8497 }
8498
Eugene Zelenko7855e772018-04-03 00:11:50 +00008499 return {};
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008500}
8501
John McCall8b07ec22010-05-15 11:32:37 +00008502bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8503 const ObjCObjectType *RHS) {
8504 assert(LHS->getInterface() && "LHS is not an interface type");
8505 assert(RHS->getInterface() && "RHS is not an interface type");
8506
Chris Lattner49af6a42008-04-07 06:51:04 +00008507 // Verify that the base decls are compatible: the RHS must be a subclass of
8508 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008509 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8510 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8511 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008512 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008513
Douglas Gregore83b9562015-07-07 03:57:53 +00008514 // If the LHS has protocol qualifiers, determine whether all of them are
8515 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8516 // LHS).
8517 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008518 // OK if conversion of LHS to SuperClass results in narrowing of types
8519 // ; i.e., SuperClass may implement at least one of the protocols
8520 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8521 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8522 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8523 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8524 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8525 // qualifiers.
8526 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008527 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008528 // If there is no protocols associated with RHS, it is not a match.
8529 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008530 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008531
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008532 for (const auto *LHSProto : LHS->quals()) {
8533 bool SuperImplementsProtocol = false;
8534 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8535 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8536 SuperImplementsProtocol = true;
8537 break;
8538 }
8539 if (!SuperImplementsProtocol)
8540 return false;
8541 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008542 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008543
8544 // If the LHS is specialized, we may need to check type arguments.
8545 if (LHS->isSpecialized()) {
8546 // Follow the superclass chain until we've matched the LHS class in the
8547 // hierarchy. This substitutes type arguments through.
8548 const ObjCObjectType *RHSSuper = RHS;
8549 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8550 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8551
8552 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008553 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008554 !sameObjCTypeArgs(*this, LHS->getInterface(),
8555 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008556 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008557 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008558 }
8559 }
8560
8561 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008562}
8563
Steve Naroffb7605152009-02-12 17:52:19 +00008564bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8565 // get the "pointed to" types
Eugene Zelenko7855e772018-04-03 00:11:50 +00008566 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8567 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008568
Steve Naroff7cae42b2009-07-10 23:34:53 +00008569 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008570 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008571
8572 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8573 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008574}
8575
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008576bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8577 return canAssignObjCInterfaces(
8578 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8579 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8580}
8581
Mike Stump11289f42009-09-09 15:08:12 +00008582/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008583/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008584/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008585/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008586bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8587 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008588 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008589 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008590
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008591 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008592}
8593
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008594bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008595 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008596}
8597
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008598bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8599 return !mergeTypes(LHS, RHS, true).isNull();
8600}
8601
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008602/// mergeTransparentUnionType - if T is a transparent union type and a member
8603/// of T is compatible with SubType, return the merged type, else return
8604/// QualType()
8605QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8606 bool OfBlockPointer,
8607 bool Unqualified) {
8608 if (const RecordType *UT = T->getAsUnionType()) {
8609 RecordDecl *UD = UT->getDecl();
8610 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008611 for (const auto *I : UD->fields()) {
8612 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008613 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8614 if (!MT.isNull())
8615 return MT;
8616 }
8617 }
8618 }
8619
Eugene Zelenko7855e772018-04-03 00:11:50 +00008620 return {};
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008621}
8622
Alp Toker9cacbab2014-01-20 20:26:09 +00008623/// mergeFunctionParameterTypes - merge two types which appear as function
8624/// parameter types
8625QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8626 bool OfBlockPointer,
8627 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008628 // GNU extension: two types are compatible if they appear as a function
8629 // argument, one of the types is a transparent union type and the other
8630 // type is compatible with a union member
8631 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8632 Unqualified);
8633 if (!lmerge.isNull())
8634 return lmerge;
8635
8636 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8637 Unqualified);
8638 if (!rmerge.isNull())
8639 return rmerge;
8640
8641 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8642}
8643
Fangrui Song6907ce22018-07-30 19:24:48 +00008644QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008645 bool OfBlockPointer,
8646 bool Unqualified) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008647 const auto *lbase = lhs->getAs<FunctionType>();
8648 const auto *rbase = rhs->getAs<FunctionType>();
8649 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8650 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008651 bool allLTypes = true;
8652 bool allRTypes = true;
8653
8654 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008655 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008656 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008657 QualType RHS = rbase->getReturnType();
8658 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008659 bool UnqualifiedResult = Unqualified;
8660 if (!UnqualifiedResult)
8661 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008662 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008663 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008664 else
Alp Toker314cc812014-01-25 16:55:45 +00008665 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008666 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008667 if (retType.isNull())
8668 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00008669
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008670 if (Unqualified)
8671 retType = retType.getUnqualifiedType();
8672
Alp Toker314cc812014-01-25 16:55:45 +00008673 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8674 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008675 if (Unqualified) {
8676 LRetType = LRetType.getUnqualifiedType();
8677 RRetType = RRetType.getUnqualifiedType();
8678 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008679
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008680 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008681 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008682 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008683 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008684
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008685 // FIXME: double check this
8686 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8687 // rbase->getRegParmAttr() != 0 &&
8688 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008689 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8690 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008691
Douglas Gregor8c940862010-01-18 17:14:39 +00008692 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008693 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008694 return {};
Mike Stump11289f42009-09-09 15:08:12 +00008695
John McCall8c6b56f2010-12-15 01:06:38 +00008696 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008697 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008698 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008699 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008700 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008701
John McCall31168b02011-06-15 23:02:42 +00008702 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008703 return {};
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008704 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008705 return {};
Oren Ben Simhon220671a2018-03-17 13:31:35 +00008706 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008707 return {};
John McCall31168b02011-06-15 23:02:42 +00008708
John McCall8c6b56f2010-12-15 01:06:38 +00008709 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8710 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008711
Rafael Espindola8778c282012-11-29 16:09:03 +00008712 if (lbaseInfo.getNoReturn() != NoReturn)
8713 allLTypes = false;
8714 if (rbaseInfo.getNoReturn() != NoReturn)
8715 allRTypes = false;
8716
John McCall31168b02011-06-15 23:02:42 +00008717 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008718
Eli Friedman47f77112008-08-22 00:56:42 +00008719 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008720 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8721 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008722 // Compatible functions must have the same number of parameters
8723 if (lproto->getNumParams() != rproto->getNumParams())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008724 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008725
8726 // Variadic and non-variadic functions aren't compatible
8727 if (lproto->isVariadic() != rproto->isVariadic())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008728 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008729
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008730 if (lproto->getMethodQuals() != rproto->getMethodQuals())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008731 return {};
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008732
Akira Hatanaka98a49332017-09-22 00:41:05 +00008733 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8734 bool canUseLeft, canUseRight;
8735 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8736 newParamInfos))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008737 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008738
Akira Hatanaka98a49332017-09-22 00:41:05 +00008739 if (!canUseLeft)
8740 allLTypes = false;
8741 if (!canUseRight)
8742 allRTypes = false;
8743
Alp Toker601b22c2014-01-21 23:35:24 +00008744 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008745 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008746 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8747 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8748 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8749 QualType paramType = mergeFunctionParameterTypes(
8750 lParamType, rParamType, OfBlockPointer, Unqualified);
8751 if (paramType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008752 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008753
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008754 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008755 paramType = paramType.getUnqualifiedType();
8756
8757 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008758 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008759 lParamType = lParamType.getUnqualifiedType();
8760 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008761 }
Alp Toker601b22c2014-01-21 23:35:24 +00008762
8763 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008764 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008765 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008766 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008767 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008768
Eli Friedman47f77112008-08-22 00:56:42 +00008769 if (allLTypes) return lhs;
8770 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008771
8772 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8773 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008774 EPI.ExtParameterInfos =
8775 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008776 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008777 }
8778
8779 if (lproto) allRTypes = false;
8780 if (rproto) allLTypes = false;
8781
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008782 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008783 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008784 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008785 if (proto->isVariadic())
8786 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008787 // Check that the types are compatible with the types that
8788 // would result from default argument promotions (C99 6.7.5.3p15).
8789 // The only types actually affected are promotable integer
8790 // types and floats, which would be passed as a different
8791 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008792 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8793 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008794
Eli Friedman448ce402012-08-30 00:44:15 +00008795 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008796 // to pass enum values.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008797 if (const auto *Enum = paramTy->getAs<EnumType>()) {
Alp Toker601b22c2014-01-21 23:35:24 +00008798 paramTy = Enum->getDecl()->getIntegerType();
8799 if (paramTy.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008800 return {};
Eli Friedman448ce402012-08-30 00:44:15 +00008801 }
Alp Toker601b22c2014-01-21 23:35:24 +00008802
8803 if (paramTy->isPromotableIntegerType() ||
8804 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008805 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008806 }
8807
8808 if (allLTypes) return lhs;
8809 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008810
8811 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8812 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008813 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008814 }
8815
8816 if (allLTypes) return lhs;
8817 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008818 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008819}
8820
John McCall433c2e62013-03-21 00:10:07 +00008821/// Given that we have an enum type and a non-enum type, try to merge them.
8822static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8823 QualType other, bool isBlockReturnType) {
8824 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8825 // a signed integer type, or an unsigned integer type.
8826 // Compatibility is based on the underlying type, not the promotion
8827 // type.
8828 QualType underlyingType = ET->getDecl()->getIntegerType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00008829 if (underlyingType.isNull())
8830 return {};
John McCall433c2e62013-03-21 00:10:07 +00008831 if (Context.hasSameType(underlyingType, other))
8832 return other;
8833
8834 // In block return types, we're more permissive and accept any
8835 // integral type of the same size.
8836 if (isBlockReturnType && other->isIntegerType() &&
8837 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8838 return other;
8839
Eugene Zelenko7855e772018-04-03 00:11:50 +00008840 return {};
John McCall433c2e62013-03-21 00:10:07 +00008841}
8842
Fangrui Song6907ce22018-07-30 19:24:48 +00008843QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008844 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008845 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008846 // C++ [expr]: If an expression initially has the type "reference to T", the
8847 // type is adjusted to "T" prior to any further analysis, the expression
8848 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008849 // expression is an lvalue unless the reference is an rvalue reference and
8850 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008851 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8852 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008853
8854 if (Unqualified) {
8855 LHS = LHS.getUnqualifiedType();
8856 RHS = RHS.getUnqualifiedType();
8857 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008858
Eli Friedman47f77112008-08-22 00:56:42 +00008859 QualType LHSCan = getCanonicalType(LHS),
8860 RHSCan = getCanonicalType(RHS);
8861
8862 // If two types are identical, they are compatible.
8863 if (LHSCan == RHSCan)
8864 return LHS;
8865
John McCall8ccfcb52009-09-24 19:53:00 +00008866 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008867 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8868 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008869 if (LQuals != RQuals) {
8870 // If any of these qualifiers are different, we have a type
8871 // mismatch.
8872 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008873 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008874 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8875 LQuals.hasUnaligned() != RQuals.hasUnaligned())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008876 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008877
8878 // Exactly one GC qualifier difference is allowed: __strong is
8879 // okay if the other type has no GC qualifier but is an Objective
8880 // C object pointer (i.e. implicitly strong by default). We fix
8881 // this by pretending that the unqualified type was actually
8882 // qualified __strong.
8883 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8884 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8885 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8886
8887 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008888 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008889
8890 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8891 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8892 }
8893 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8894 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8895 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008896 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008897 }
8898
8899 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008900
Eli Friedmandcca6332009-06-01 01:22:52 +00008901 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8902 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008903
Chris Lattnerfd652912008-01-14 05:45:46 +00008904 // We want to consider the two function types to be the same for these
8905 // comparisons, just force one to the other.
8906 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8907 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008908
8909 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008910 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8911 LHSClass = Type::ConstantArray;
8912 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8913 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008914
John McCall8b07ec22010-05-15 11:32:37 +00008915 // ObjCInterfaces are just specialized ObjCObjects.
8916 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8917 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8918
Nate Begemance4d7fc2008-04-18 23:10:10 +00008919 // Canonicalize ExtVector -> Vector.
8920 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8921 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008922
Chris Lattner95554662008-04-07 05:43:21 +00008923 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008924 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008925 // Note that we only have special rules for turning block enum
8926 // returns into block int returns, not vice-versa.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008927 if (const auto *ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008928 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008929 }
John McCall9dd450b2009-09-21 23:43:11 +00008930 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008931 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008932 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008933 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008934 if (OfBlockPointer && !BlockReturnType) {
8935 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8936 return LHS;
8937 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8938 return RHS;
8939 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008940
Eugene Zelenko7855e772018-04-03 00:11:50 +00008941 return {};
Steve Naroff32e44c02007-10-15 20:41:53 +00008942 }
Eli Friedman47f77112008-08-22 00:56:42 +00008943
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008944 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008945 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008946#define TYPE(Class, Base)
8947#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008948#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008949#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8950#define DEPENDENT_TYPE(Class, Base) case Type::Class:
John McCall36b12a82019-10-02 06:35:23 +00008951#include "clang/AST/TypeNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +00008952 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008953
Richard Smith27d807c2013-04-30 13:56:41 +00008954 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008955 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008956 case Type::LValueReference:
8957 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008958 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008959 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008960
John McCall8b07ec22010-05-15 11:32:37 +00008961 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008962 case Type::IncompleteArray:
8963 case Type::VariableArray:
8964 case Type::FunctionProto:
8965 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008966 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008967
Chris Lattnerfd652912008-01-14 05:45:46 +00008968 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008969 {
8970 // Merge two pointer types, while trying to preserve typedef info
Simon Pilgrimeed4b122019-10-02 11:48:06 +00008971 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
8972 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008973 if (Unqualified) {
8974 LHSPointee = LHSPointee.getUnqualifiedType();
8975 RHSPointee = RHSPointee.getUnqualifiedType();
8976 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008977 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008978 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008979 if (ResultType.isNull())
8980 return {};
Eli Friedman091a9ac2009-06-02 05:28:56 +00008981 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008982 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008983 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008984 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008985 return getPointerType(ResultType);
8986 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008987 case Type::BlockPointer:
8988 {
8989 // Merge two block pointer types, while trying to preserve typedef info
Simon Pilgrimeed4b122019-10-02 11:48:06 +00008990 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
8991 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008992 if (Unqualified) {
8993 LHSPointee = LHSPointee.getUnqualifiedType();
8994 RHSPointee = RHSPointee.getUnqualifiedType();
8995 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008996 if (getLangOpts().OpenCL) {
8997 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8998 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8999 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
9000 // 6.12.5) thus the following check is asymmetric.
9001 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
Eugene Zelenko7855e772018-04-03 00:11:50 +00009002 return {};
Anastasia Stulova81a25e352017-03-10 15:23:07 +00009003 LHSPteeQual.removeAddressSpace();
9004 RHSPteeQual.removeAddressSpace();
9005 LHSPointee =
9006 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
9007 RHSPointee =
9008 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
9009 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009010 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
9011 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00009012 if (ResultType.isNull())
9013 return {};
Steve Naroff68e167d2008-12-10 17:49:55 +00009014 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9015 return LHS;
9016 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9017 return RHS;
9018 return getBlockPointerType(ResultType);
9019 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00009020 case Type::Atomic:
9021 {
9022 // Merge two pointer types, while trying to preserve typedef info
Simon Pilgrimeed4b122019-10-02 11:48:06 +00009023 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
9024 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
Eli Friedman0dfb8892011-10-06 23:00:33 +00009025 if (Unqualified) {
9026 LHSValue = LHSValue.getUnqualifiedType();
9027 RHSValue = RHSValue.getUnqualifiedType();
9028 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009029 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
Eli Friedman0dfb8892011-10-06 23:00:33 +00009030 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00009031 if (ResultType.isNull())
9032 return {};
Eli Friedman0dfb8892011-10-06 23:00:33 +00009033 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
9034 return LHS;
9035 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
9036 return RHS;
9037 return getAtomicType(ResultType);
9038 }
Chris Lattnerfd652912008-01-14 05:45:46 +00009039 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00009040 {
9041 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
9042 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
9043 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009044 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00009045
9046 QualType LHSElem = getAsArrayType(LHS)->getElementType();
9047 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009048 if (Unqualified) {
9049 LHSElem = LHSElem.getUnqualifiedType();
9050 RHSElem = RHSElem.getUnqualifiedType();
9051 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009052
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009053 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00009054 if (ResultType.isNull())
9055 return {};
Jeremy Morse8129c5c2018-06-05 09:18:26 +00009056
9057 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
9058 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
9059
9060 // If either side is a variable array, and both are complete, check whether
9061 // the current dimension is definite.
9062 if (LVAT || RVAT) {
9063 auto SizeFetch = [this](const VariableArrayType* VAT,
9064 const ConstantArrayType* CAT)
9065 -> std::pair<bool,llvm::APInt> {
9066 if (VAT) {
9067 llvm::APSInt TheInt;
9068 Expr *E = VAT->getSizeExpr();
9069 if (E && E->isIntegerConstantExpr(TheInt, *this))
9070 return std::make_pair(true, TheInt);
9071 else
9072 return std::make_pair(false, TheInt);
9073 } else if (CAT) {
9074 return std::make_pair(true, CAT->getSize());
9075 } else {
9076 return std::make_pair(false, llvm::APInt());
9077 }
9078 };
9079
9080 bool HaveLSize, HaveRSize;
9081 llvm::APInt LSize, RSize;
9082 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
9083 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
9084 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
9085 return {}; // Definite, but unequal, array dimension
9086 }
9087
Chris Lattner465fa322008-10-05 17:34:18 +00009088 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9089 return LHS;
9090 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9091 return RHS;
Richard Smith772e2662019-10-04 01:25:59 +00009092 if (LCAT)
9093 return getConstantArrayType(ResultType, LCAT->getSize(),
9094 LCAT->getSizeExpr(),
9095 ArrayType::ArraySizeModifier(), 0);
9096 if (RCAT)
9097 return getConstantArrayType(ResultType, RCAT->getSize(),
9098 RCAT->getSizeExpr(),
9099 ArrayType::ArraySizeModifier(), 0);
Chris Lattner465fa322008-10-05 17:34:18 +00009100 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9101 return LHS;
9102 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9103 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00009104 if (LVAT) {
9105 // FIXME: This isn't correct! But tricky to implement because
9106 // the array's size has to be the size of LHS, but the type
9107 // has to be different.
9108 return LHS;
9109 }
9110 if (RVAT) {
9111 // FIXME: This isn't correct! But tricky to implement because
9112 // the array's size has to be the size of RHS, but the type
9113 // has to be different.
9114 return RHS;
9115 }
Eli Friedman3e62c212008-08-22 01:48:21 +00009116 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
9117 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00009118 return getIncompleteArrayType(ResultType,
9119 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00009120 }
Chris Lattnerfd652912008-01-14 05:45:46 +00009121 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009122 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009123 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009124 case Type::Enum:
Eugene Zelenko7855e772018-04-03 00:11:50 +00009125 return {};
Chris Lattnerfd652912008-01-14 05:45:46 +00009126 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009127 // Only exactly equal builtin types are compatible, which is tested above.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009128 return {};
Daniel Dunbar804c0442009-01-28 21:22:12 +00009129 case Type::Complex:
9130 // Distinct complex types are incompatible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009131 return {};
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009132 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00009133 // FIXME: The merged type should be an ExtVector!
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009134 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
9135 RHSCan->castAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00009136 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009137 return {};
John McCall8b07ec22010-05-15 11:32:37 +00009138 case Type::ObjCObject: {
9139 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00009140 // FIXME: This should be type compatibility, e.g. whether
9141 // "LHS x; RHS x;" at global scope is legal.
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009142 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
9143 RHS->castAs<ObjCObjectType>()))
Steve Naroff7a7814c2009-02-21 16:18:07 +00009144 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009145 return {};
Cedric Venet4fc88b72009-02-21 17:14:49 +00009146 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009147 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009148 if (OfBlockPointer) {
9149 if (canAssignObjCInterfacesInBlockPointer(
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009150 LHS->castAs<ObjCObjectPointerType>(),
9151 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00009152 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009153 return {};
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009154 }
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009155 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
9156 RHS->castAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00009157 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009158 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009159 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00009160 assert(LHS != RHS &&
9161 "Equivalent pipe types should have already been handled!");
Eugene Zelenko7855e772018-04-03 00:11:50 +00009162 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009163 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009164
David Blaikie8a40f702012-01-17 06:56:22 +00009165 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00009166}
Ted Kremenekfc581a92007-10-31 17:10:13 +00009167
Akira Hatanaka98a49332017-09-22 00:41:05 +00009168bool ASTContext::mergeExtParameterInfo(
9169 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9170 bool &CanUseFirst, bool &CanUseSecond,
9171 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9172 assert(NewParamInfos.empty() && "param info list not empty");
9173 CanUseFirst = CanUseSecond = true;
9174 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9175 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9176
John McCall18afab72016-03-01 00:49:02 +00009177 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00009178 // we match if and only if the second type also doesn't have them.
9179 if (!FirstHasInfo && !SecondHasInfo)
9180 return true;
John McCall18afab72016-03-01 00:49:02 +00009181
Akira Hatanaka98a49332017-09-22 00:41:05 +00009182 bool NeedParamInfo = false;
9183 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9184 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00009185
Akira Hatanaka98a49332017-09-22 00:41:05 +00009186 for (size_t I = 0; I < E; ++I) {
9187 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9188 if (FirstHasInfo)
9189 FirstParam = FirstFnType->getExtParameterInfo(I);
9190 if (SecondHasInfo)
9191 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00009192
Akira Hatanaka98a49332017-09-22 00:41:05 +00009193 // Cannot merge unless everything except the noescape flag matches.
9194 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00009195 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00009196
9197 bool FirstNoEscape = FirstParam.isNoEscape();
9198 bool SecondNoEscape = SecondParam.isNoEscape();
9199 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9200 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9201 if (NewParamInfos.back().getOpaqueValue())
9202 NeedParamInfo = true;
9203 if (FirstNoEscape != IsNoEscape)
9204 CanUseFirst = false;
9205 if (SecondNoEscape != IsNoEscape)
9206 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00009207 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00009208
9209 if (!NeedParamInfo)
9210 NewParamInfos.clear();
9211
Fariborz Jahanian97676972011-09-28 21:52:05 +00009212 return true;
9213}
9214
Chandler Carruth21c90602015-12-30 03:24:14 +00009215void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9216 ObjCLayouts[CD] = nullptr;
9217}
9218
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009219/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9220/// 'RHS' attributes and returns the merged version; including for function
9221/// return types.
9222QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9223 QualType LHSCan = getCanonicalType(LHS),
9224 RHSCan = getCanonicalType(RHS);
9225 // If two types are identical, they are compatible.
9226 if (LHSCan == RHSCan)
9227 return LHS;
9228 if (RHSCan->isFunctionType()) {
9229 if (!LHSCan->isFunctionType())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009230 return {};
Alp Toker314cc812014-01-25 16:55:45 +00009231 QualType OldReturnType =
9232 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009233 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00009234 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009235 QualType ResReturnType =
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009236 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9237 if (ResReturnType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009238 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009239 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9240 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9241 // In either case, use OldReturnType to build the new function type.
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009242 const auto *F = LHS->castAs<FunctionType>();
Eugene Zelenko7855e772018-04-03 00:11:50 +00009243 if (const auto *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009244 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9245 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00009246 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00009247 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009248 return ResultType;
9249 }
9250 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009251 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009252 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009253
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009254 // If the qualifiers are different, the types can still be merged.
9255 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9256 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9257 if (LQuals != RQuals) {
9258 // If any of these qualifiers are different, we have a type mismatch.
9259 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9260 LQuals.getAddressSpace() != RQuals.getAddressSpace())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009261 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009262
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009263 // Exactly one GC qualifier difference is allowed: __strong is
9264 // okay if the other type has no GC qualifier but is an Objective
9265 // C object pointer (i.e. implicitly strong by default). We fix
9266 // this by pretending that the unqualified type was actually
9267 // qualified __strong.
9268 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9269 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9270 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
Fangrui Song6907ce22018-07-30 19:24:48 +00009271
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009272 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009273 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009274
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009275 if (GC_L == Qualifiers::Strong)
9276 return LHS;
9277 if (GC_R == Qualifiers::Strong)
9278 return RHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009279 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009280 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009281
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009282 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
Simon Pilgrimeed4b122019-10-02 11:48:06 +00009283 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
9284 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009285 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9286 if (ResQT == LHSBaseQT)
9287 return LHS;
9288 if (ResQT == RHSBaseQT)
9289 return RHS;
9290 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009291 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009292}
9293
Chris Lattner4ba0cef2008-04-07 07:01:58 +00009294//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009295// Integer Predicates
9296//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00009297
Jay Foad39c79802011-01-12 09:06:06 +00009298unsigned ASTContext::getIntWidth(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009299 if (const auto *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00009300 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00009301 if (T->isBooleanType())
9302 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00009303 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009304 return (unsigned)getTypeSize(T);
9305}
9306
Abramo Bagnara13640492012-09-09 10:21:24 +00009307QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Leonard Chanab80f3c2018-06-14 14:53:51 +00009308 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9309 "Unexpected type");
Fangrui Song6907ce22018-07-30 19:24:48 +00009310
Chris Lattnerec3a1562009-10-17 20:33:28 +00009311 // Turn <4 x signed int> -> <4 x unsigned int>
Eugene Zelenko7855e772018-04-03 00:11:50 +00009312 if (const auto *VTy = T->getAs<VectorType>())
Chris Lattnerec3a1562009-10-17 20:33:28 +00009313 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00009314 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00009315
9316 // For enums, we return the unsigned version of the base type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009317 if (const auto *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009318 T = ETy->getDecl()->getIntegerType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009319
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009320 switch (T->castAs<BuiltinType>()->getKind()) {
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009321 case BuiltinType::Char_S:
9322 case BuiltinType::SChar:
9323 return UnsignedCharTy;
9324 case BuiltinType::Short:
9325 return UnsignedShortTy;
9326 case BuiltinType::Int:
9327 return UnsignedIntTy;
9328 case BuiltinType::Long:
9329 return UnsignedLongTy;
9330 case BuiltinType::LongLong:
9331 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00009332 case BuiltinType::Int128:
9333 return UnsignedInt128Ty;
Leonard Chanab80f3c2018-06-14 14:53:51 +00009334
9335 case BuiltinType::ShortAccum:
9336 return UnsignedShortAccumTy;
9337 case BuiltinType::Accum:
9338 return UnsignedAccumTy;
9339 case BuiltinType::LongAccum:
9340 return UnsignedLongAccumTy;
9341 case BuiltinType::SatShortAccum:
9342 return SatUnsignedShortAccumTy;
9343 case BuiltinType::SatAccum:
9344 return SatUnsignedAccumTy;
9345 case BuiltinType::SatLongAccum:
9346 return SatUnsignedLongAccumTy;
9347 case BuiltinType::ShortFract:
9348 return UnsignedShortFractTy;
9349 case BuiltinType::Fract:
9350 return UnsignedFractTy;
9351 case BuiltinType::LongFract:
9352 return UnsignedLongFractTy;
9353 case BuiltinType::SatShortFract:
9354 return SatUnsignedShortFractTy;
9355 case BuiltinType::SatFract:
9356 return SatUnsignedFractTy;
9357 case BuiltinType::SatLongFract:
9358 return SatUnsignedLongFractTy;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009359 default:
Leonard Chanab80f3c2018-06-14 14:53:51 +00009360 llvm_unreachable("Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009361 }
9362}
9363
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009364ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00009365
Richard Smith1fa5d642013-05-11 05:45:24 +00009366void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9367 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00009368
9369//===----------------------------------------------------------------------===//
9370// Builtin Type Computation
9371//===----------------------------------------------------------------------===//
9372
9373/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00009374/// pointer over the consumed characters. This returns the resultant type. If
9375/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9376/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9377/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009378///
9379/// RequiresICE is filled in on return to indicate whether the value is required
9380/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00009381static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00009382 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009383 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00009384 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00009385 // Modifiers.
9386 int HowLong = 0;
9387 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009388 RequiresICE = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009389
Chris Lattnerdc226c22010-10-01 22:42:38 +00009390 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00009391 bool Done = false;
9392 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009393 bool IsSpecial = false;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009394 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00009395 while (!Done) {
9396 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00009397 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00009398 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009399 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00009400 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009401 case 'S':
9402 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9403 assert(!Signed && "Can't use 'S' modifier multiple times!");
9404 Signed = true;
9405 break;
9406 case 'U':
9407 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00009408 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009409 Unsigned = true;
9410 break;
9411 case 'L':
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009412 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009413 assert(HowLong <= 2 && "Can't have LLLL modifier");
9414 ++HowLong;
9415 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009416 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009417 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009418 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009419 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009420 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009421 IsSpecial = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009422 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009423 if (Context.getTargetInfo().getLongWidth() == 32)
9424 ++HowLong;
9425 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00009426 case 'W':
9427 // This modifier represents int64 type.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009428 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00009429 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009430 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009431 IsSpecial = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009432 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00009433 switch (Context.getTargetInfo().getInt64Type()) {
9434 default:
9435 llvm_unreachable("Unexpected integer type");
9436 case TargetInfo::SignedLong:
9437 HowLong = 1;
9438 break;
9439 case TargetInfo::SignedLongLong:
9440 HowLong = 2;
9441 break;
9442 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00009443 break;
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009444 case 'Z':
9445 // This modifier represents int32 type.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009446 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009447 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
9448 #ifndef NDEBUG
9449 IsSpecial = true;
9450 #endif
9451 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
9452 default:
9453 llvm_unreachable("Unexpected integer type");
9454 case TargetInfo::SignedInt:
9455 HowLong = 0;
9456 break;
9457 case TargetInfo::SignedLong:
9458 HowLong = 1;
9459 break;
9460 case TargetInfo::SignedLongLong:
9461 HowLong = 2;
9462 break;
9463 }
9464 break;
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009465 case 'O':
9466 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9467 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
9468 #ifndef NDEBUG
9469 IsSpecial = true;
9470 #endif
9471 if (Context.getLangOpts().OpenCL)
9472 HowLong = 1;
9473 else
9474 HowLong = 2;
9475 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009476 }
9477 }
9478
9479 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00009480
Chris Lattnerecd79c62009-06-14 00:45:47 +00009481 // Read the base type.
9482 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00009483 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009484 case 'v':
9485 assert(HowLong == 0 && !Signed && !Unsigned &&
9486 "Bad modifiers used with 'v'!");
9487 Type = Context.VoidTy;
9488 break;
Jack Carter24bef982013-08-15 15:16:57 +00009489 case 'h':
9490 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00009491 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00009492 Type = Context.HalfTy;
9493 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009494 case 'f':
9495 assert(HowLong == 0 && !Signed && !Unsigned &&
9496 "Bad modifiers used with 'f'!");
9497 Type = Context.FloatTy;
9498 break;
9499 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009500 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00009501 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009502 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00009503 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009504 else if (HowLong == 2)
9505 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009506 else
9507 Type = Context.DoubleTy;
9508 break;
9509 case 's':
9510 assert(HowLong == 0 && "Bad modifiers used with 's'!");
9511 if (Unsigned)
9512 Type = Context.UnsignedShortTy;
9513 else
9514 Type = Context.ShortTy;
9515 break;
9516 case 'i':
9517 if (HowLong == 3)
9518 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9519 else if (HowLong == 2)
9520 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9521 else if (HowLong == 1)
9522 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9523 else
9524 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9525 break;
9526 case 'c':
9527 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9528 if (Signed)
9529 Type = Context.SignedCharTy;
9530 else if (Unsigned)
9531 Type = Context.UnsignedCharTy;
9532 else
9533 Type = Context.CharTy;
9534 break;
9535 case 'b': // boolean
9536 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9537 Type = Context.BoolTy;
9538 break;
9539 case 'z': // size_t.
9540 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9541 Type = Context.getSizeType();
9542 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00009543 case 'w': // wchar_t.
9544 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9545 Type = Context.getWideCharType();
9546 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009547 case 'F':
9548 Type = Context.getCFConstantStringType();
9549 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00009550 case 'G':
9551 Type = Context.getObjCIdType();
9552 break;
9553 case 'H':
9554 Type = Context.getObjCSelType();
9555 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00009556 case 'M':
9557 Type = Context.getObjCSuperType();
9558 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009559 case 'a':
9560 Type = Context.getBuiltinVaListType();
9561 assert(!Type.isNull() && "builtin va list type not initialized!");
9562 break;
9563 case 'A':
9564 // This is a "reference" to a va_list; however, what exactly
9565 // this means depends on how va_list is defined. There are two
9566 // different kinds of va_list: ones passed by value, and ones
9567 // passed by reference. An example of a by-value va_list is
9568 // x86, where va_list is a char*. An example of by-ref va_list
9569 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9570 // we want this argument to be a char*&; for x86-64, we want
9571 // it to be a __va_list_tag*.
9572 Type = Context.getBuiltinVaListType();
9573 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009574 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009575 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009576 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009577 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009578 break;
9579 case 'V': {
9580 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009581 unsigned NumElements = strtoul(Str, &End, 10);
9582 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009583 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009584
Fangrui Song6907ce22018-07-30 19:24:48 +00009585 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009586 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009587 assert(!RequiresICE && "Can't require vector ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009588
Chris Lattnerdc226c22010-10-01 22:42:38 +00009589 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009590 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009591 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009592 break;
9593 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009594 case 'E': {
9595 char *End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009596
Douglas Gregorfed66992012-06-07 18:08:25 +00009597 unsigned NumElements = strtoul(Str, &End, 10);
9598 assert(End != Str && "Missing vector size");
Fangrui Song6907ce22018-07-30 19:24:48 +00009599
Douglas Gregorfed66992012-06-07 18:08:25 +00009600 Str = End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009601
Douglas Gregorfed66992012-06-07 18:08:25 +00009602 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009603 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009604 Type = Context.getExtVectorType(ElementType, NumElements);
Fangrui Song6907ce22018-07-30 19:24:48 +00009605 break;
Douglas Gregorfed66992012-06-07 18:08:25 +00009606 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009607 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009608 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009609 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009610 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009611 Type = Context.getComplexType(ElementType);
9612 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00009613 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009614 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009615 Type = Context.getPointerDiffType();
9616 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009617 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009618 Type = Context.getFILEType();
9619 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009620 Error = ASTContext::GE_Missing_stdio;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009621 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009622 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009623 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009624 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009625 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009626 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009627 else
9628 Type = Context.getjmp_bufType();
9629
Mike Stump2adb4da2009-07-28 23:47:15 +00009630 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009631 Error = ASTContext::GE_Missing_setjmp;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009632 return {};
Mike Stump2adb4da2009-07-28 23:47:15 +00009633 }
9634 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009635 case 'K':
9636 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9637 Type = Context.getucontext_tType();
9638
9639 if (Type.isNull()) {
9640 Error = ASTContext::GE_Missing_ucontext;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009641 return {};
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009642 }
9643 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009644 case 'p':
9645 Type = Context.getProcessIDType();
9646 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009647 }
Mike Stump11289f42009-09-09 15:08:12 +00009648
Chris Lattnerdc226c22010-10-01 22:42:38 +00009649 // If there are modifiers and if we're allowed to parse them, go for it.
9650 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009651 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009652 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009653 default: Done = true; --Str; break;
9654 case '*':
9655 case '&': {
9656 // Both pointers and references can have their pointee types
9657 // qualified with an address space.
9658 char *End;
9659 unsigned AddrSpace = strtoul(Str, &End, 10);
Matt Arsenaultc65f9662018-08-02 12:14:28 +00009660 if (End != Str) {
9661 // Note AddrSpace == 0 is not the same as an unspecified address space.
9662 Type = Context.getAddrSpaceQualType(
9663 Type,
9664 Context.getLangASForBuiltinAddressSpace(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009665 Str = End;
9666 }
9667 if (c == '*')
9668 Type = Context.getPointerType(Type);
9669 else
9670 Type = Context.getLValueReferenceType(Type);
9671 break;
9672 }
9673 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9674 case 'C':
9675 Type = Type.withConst();
9676 break;
9677 case 'D':
9678 Type = Context.getVolatileType(Type);
9679 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009680 case 'R':
9681 Type = Type.withRestrict();
9682 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009683 }
9684 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009685
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009686 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Fangrui Song6907ce22018-07-30 19:24:48 +00009687 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009688
Chris Lattnerecd79c62009-06-14 00:45:47 +00009689 return Type;
9690}
9691
9692/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009693QualType ASTContext::GetBuiltinType(unsigned Id,
9694 GetBuiltinTypeError &Error,
9695 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009696 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00009697 if (TypeStr[0] == '\0') {
9698 Error = GE_Missing_type;
9699 return {};
9700 }
Mike Stump11289f42009-09-09 15:08:12 +00009701
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009702 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009703
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009704 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009705 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009706 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9707 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009708 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009709 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009710
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009711 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009712
Chris Lattnerecd79c62009-06-14 00:45:47 +00009713 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009714 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009715 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009716 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009717
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009718 // If this argument is required to be an IntegerConstantExpression and the
9719 // caller cares, fill in the bitmask we return.
9720 if (RequiresICE && IntegerConstantArgs)
9721 *IntegerConstantArgs |= 1 << ArgTypes.size();
Fangrui Song6907ce22018-07-30 19:24:48 +00009722
Chris Lattnerecd79c62009-06-14 00:45:47 +00009723 // Do array -> pointer decay. The builtin should use the decayed type.
9724 if (Ty->isArrayType())
9725 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009726
Chris Lattnerecd79c62009-06-14 00:45:47 +00009727 ArgTypes.push_back(Ty);
9728 }
9729
David Majnemerba3e5ec2015-03-13 18:26:17 +00009730 if (Id == Builtin::BI__GetExceptionInfo)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009731 return {};
David Majnemerba3e5ec2015-03-13 18:26:17 +00009732
Chris Lattnerecd79c62009-06-14 00:45:47 +00009733 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9734 "'.' should only occur at end of builtin type list!");
9735
Erich Keane881e83d2019-03-04 14:54:52 +00009736 bool Variadic = (TypeStr[0] == '.');
9737
Erich Keane00022812019-05-23 16:05:21 +00009738 FunctionType::ExtInfo EI(getDefaultCallingConvention(
9739 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
John McCall991eb4b2010-12-21 00:44:39 +00009740 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9741
John McCall991eb4b2010-12-21 00:44:39 +00009742
Richard Smith836de6b2016-12-19 23:59:34 +00009743 // We really shouldn't be making a no-proto type here.
9744 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00009745 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00009746
John McCalldb40c7f2010-12-14 08:05:40 +00009747 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00009748 EPI.ExtInfo = EI;
9749 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00009750 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9751 EPI.ExceptionSpec.Type =
9752 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00009753
Jordan Rose5c382722013-03-08 21:51:21 +00009754 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009755}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00009756
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009757static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9758 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009759 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009760 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009761
Richard Smithe2467b72017-11-16 23:54:56 +00009762 // Non-user-provided functions get emitted as weak definitions with every
9763 // use, no matter whether they've been explicitly instantiated etc.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009764 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
Richard Smithe2467b72017-11-16 23:54:56 +00009765 if (!MD->isUserProvided())
9766 return GVA_DiscardableODR;
9767
Yaron Keren4cd211b2017-02-22 14:32:39 +00009768 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009769 switch (FD->getTemplateSpecializationKind()) {
9770 case TSK_Undeclared:
9771 case TSK_ExplicitSpecialization:
9772 External = GVA_StrongExternal;
9773 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009774
Rafael Espindola3ae00052013-05-13 00:12:11 +00009775 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009776 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009777
David Majnemerc3d07332014-05-15 06:25:57 +00009778 // C++11 [temp.explicit]p10:
9779 // [ Note: The intent is that an inline function that is the subject of
9780 // an explicit instantiation declaration will still be implicitly
9781 // instantiated when used so that the body can be considered for
9782 // inlining, but that no out-of-line copy of the inline function would be
9783 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00009784 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00009785 return GVA_AvailableExternally;
9786
Rafael Espindola3ae00052013-05-13 00:12:11 +00009787 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009788 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009789 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009790 }
9791
9792 if (!FD->isInlined())
9793 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00009794
David Majnemer3f021502015-10-08 04:53:31 +00009795 if ((!Context.getLangOpts().CPlusPlus &&
9796 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009797 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00009798 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009799 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9800
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009801 // GNU or C99 inline semantics. Determine whether this symbol should be
9802 // externally visible.
9803 if (FD->isInlineDefinitionExternallyVisible())
9804 return External;
9805
9806 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00009807 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009808 }
9809
David Majnemer54e3ba52014-04-02 23:17:29 +00009810 // Functions specified with extern and inline in -fms-compatibility mode
9811 // forcibly get emitted. While the body of the function cannot be later
9812 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00009813 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00009814 return GVA_StrongODR;
9815
David Majnemer27d69db2014-04-28 22:17:59 +00009816 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009817}
9818
Artem Belevichca2b9512016-05-02 20:30:03 +00009819static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00009820 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009821 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9822 // dllexport/dllimport on inline functions.
9823 if (D->hasAttr<DLLImportAttr>()) {
9824 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9825 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00009826 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009827 if (L == GVA_DiscardableODR)
9828 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00009829 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9830 D->hasAttr<CUDAGlobalAttr>()) {
9831 // Device-side functions with __global__ attribute must always be
9832 // visible externally so they can be launched from host.
9833 if (L == GVA_DiscardableODR || L == GVA_Internal)
9834 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009835 }
9836 return L;
9837}
9838
Richard Smitha4653622017-09-06 20:01:14 +00009839/// Adjust the GVALinkage for a declaration based on what an external AST source
9840/// knows about whether there can be other definitions of this declaration.
9841static GVALinkage
9842adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9843 GVALinkage L) {
9844 ExternalASTSource *Source = Ctx.getExternalSource();
9845 if (!Source)
9846 return L;
9847
9848 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00009849 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00009850 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009851 if (L == GVA_DiscardableODR)
9852 return GVA_StrongODR;
9853 break;
Richard Smitha4653622017-09-06 20:01:14 +00009854
David Blaikie9ffe5a32017-01-30 05:00:26 +00009855 case ExternalASTSource::EK_Always:
9856 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00009857
David Blaikie9ffe5a32017-01-30 05:00:26 +00009858 case ExternalASTSource::EK_ReplyHazy:
9859 break;
9860 }
9861 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009862}
9863
Richard Smitha4653622017-09-06 20:01:14 +00009864GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9865 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9866 adjustGVALinkageForAttributes(*this, FD,
9867 basicGVALinkageForFunction(*this, FD)));
9868}
9869
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009870static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9871 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009872 if (!VD->isExternallyVisible())
9873 return GVA_Internal;
9874
David Majnemer27d69db2014-04-28 22:17:59 +00009875 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00009876 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9877 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9878 LexicalContext = LexicalContext->getLexicalParent();
9879
David Blaikieeb210012017-01-27 23:11:10 +00009880 // ObjC Blocks can create local variables that don't have a FunctionDecl
9881 // LexicalContext.
9882 if (!LexicalContext)
9883 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00009884
David Blaikieeb210012017-01-27 23:11:10 +00009885 // Otherwise, let the static local variable inherit its linkage from the
9886 // nearest enclosing function.
9887 auto StaticLocalLinkage =
9888 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9889
9890 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9891 // be emitted in any object with references to the symbol for the object it
9892 // contains, whether inline or out-of-line."
9893 // Similar behavior is observed with MSVC. An alternative ABI could use
9894 // StrongODR/AvailableExternally to match the function, but none are
9895 // known/supported currently.
9896 if (StaticLocalLinkage == GVA_StrongODR ||
9897 StaticLocalLinkage == GVA_AvailableExternally)
9898 return GVA_DiscardableODR;
9899 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009900 }
9901
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009902 // MSVC treats in-class initialized static data members as definitions.
9903 // By giving them non-strong linkage, out-of-line definitions won't
9904 // cause link errors.
9905 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9906 return GVA_DiscardableODR;
9907
Richard Smithd9b90092016-07-02 01:32:16 +00009908 // Most non-template variables have strong linkage; inline variables are
9909 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9910 GVALinkage StrongLinkage;
9911 switch (Context.getInlineVariableDefinitionKind(VD)) {
9912 case ASTContext::InlineVariableDefinitionKind::None:
9913 StrongLinkage = GVA_StrongExternal;
9914 break;
9915 case ASTContext::InlineVariableDefinitionKind::Weak:
9916 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009917 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009918 break;
9919 case ASTContext::InlineVariableDefinitionKind::Strong:
9920 StrongLinkage = GVA_StrongODR;
9921 break;
9922 }
Richard Smith62f19e72016-06-25 00:15:56 +00009923
Richard Smith8809a0c2013-09-27 20:14:12 +00009924 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009925 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009926 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009927
David Majnemer6d1780c2015-07-17 23:36:49 +00009928 case TSK_ExplicitSpecialization:
Hans Wennborg4bdd5132019-09-25 11:09:46 +00009929 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9930 VD->isStaticDataMember()
9931 ? GVA_StrongODR
9932 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009933
Rafael Espindola3ae00052013-05-13 00:12:11 +00009934 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009935 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009936
David Majnemer27d69db2014-04-28 22:17:59 +00009937 case TSK_ExplicitInstantiationDeclaration:
9938 return GVA_AvailableExternally;
9939
Rafael Espindola3ae00052013-05-13 00:12:11 +00009940 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009941 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009942 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009943
9944 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009945}
9946
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009947GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009948 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9949 adjustGVALinkageForAttributes(*this, VD,
9950 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009951}
9952
David Blaikiee6b7c282017-04-11 20:46:34 +00009953bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009954 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009955 if (!VD->isFileVarDecl())
9956 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009957 // Global named register variables (GNU extension) are never emitted.
9958 if (VD->getStorageClass() == SC_Register)
9959 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009960 if (VD->getDescribedVarTemplate() ||
9961 isa<VarTemplatePartialSpecializationDecl>(VD))
9962 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009963 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Smith5205a8c2013-04-01 20:22:16 +00009964 // We never need to emit an uninstantiated function template.
9965 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9966 return false;
Nico Weber66220292016-03-02 17:28:48 +00009967 } else if (isa<PragmaCommentDecl>(D))
9968 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009969 else if (isa<PragmaDetectMismatchDecl>(D))
9970 return true;
Nico Weber66220292016-03-02 17:28:48 +00009971 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009972 return !D->getDeclContext()->isDependentContext();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009973 else if (isa<OMPAllocateDecl>(D))
9974 return !D->getDeclContext()->isDependentContext();
Michael Krused47b9432019-08-05 18:43:21 +00009975 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009976 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009977 else if (isa<ImportDecl>(D))
9978 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009979 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009980 return false;
9981
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009982 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
9983 assert(getExternalSource() && "It's from an AST file; must have a source.");
9984 // On Windows, PCH files are built together with an object file. If this
9985 // declaration comes from such a PCH and DeclMustBeEmitted would return
9986 // true, it would have returned true and the decl would have been emitted
9987 // into that object file, so it doesn't need to be emitted here.
9988 // Note that decls are still emitted if they're referenced, as usual;
9989 // DeclMustBeEmitted is used to decide whether a decl must be emitted even
9990 // if it's not referenced.
9991 //
9992 // Explicit template instantiation definitions are tricky. If there was an
9993 // explicit template instantiation decl in the PCH before, it will look like
9994 // the definition comes from there, even if that was just the declaration.
9995 // (Explicit instantiation defs of variable templates always get emitted.)
9996 bool IsExpInstDef =
9997 isa<FunctionDecl>(D) &&
9998 cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
9999 TSK_ExplicitInstantiationDefinition;
10000
Hans Wennborgb51a7032018-09-14 15:18:30 +000010001 // Implicit member function definitions, such as operator= might not be
10002 // marked as template specializations, since they're not coming from a
10003 // template but synthesized directly on the class.
10004 IsExpInstDef |=
10005 isa<CXXMethodDecl>(D) &&
10006 cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
10007 TSK_ExplicitInstantiationDefinition;
10008
Hans Wennborg08c5a7b2018-06-25 13:23:49 +000010009 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
10010 return false;
10011 }
10012
Richard Smith5205a8c2013-04-01 20:22:16 +000010013 // If this is a member of a class template, we do not need to emit it.
10014 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010015 return false;
10016
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +000010017 // Weak references don't produce any output by themselves.
10018 if (D->hasAttr<WeakRefAttr>())
10019 return false;
10020
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010021 // Aliases and used decls are required.
10022 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
10023 return true;
10024
Eugene Zelenko7855e772018-04-03 00:11:50 +000010025 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010026 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +000010027 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +000010028 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010029
10030 // Constructors and destructors are required.
10031 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
10032 return true;
Hans Wennborg08c5a7b2018-06-25 13:23:49 +000010033
John McCall6bd2a892013-01-25 22:31:03 +000010034 // The key function for a class is required. This rule only comes
10035 // into play when inline functions can be key functions, though.
10036 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +000010037 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
John McCall6bd2a892013-01-25 22:31:03 +000010038 const CXXRecordDecl *RD = MD->getParent();
10039 if (MD->isOutOfLine() && RD->isDynamicClass()) {
10040 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
10041 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
10042 return true;
10043 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010044 }
10045 }
10046
David Blaikie9ffe5a32017-01-30 05:00:26 +000010047 GVALinkage Linkage = GetGVALinkageForFunction(FD);
10048
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010049 // static, static inline, always_inline, and extern inline functions can
10050 // always be deferred. Normal inline functions can be deferred in C99/C++.
10051 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +000010052 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010053 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +000010054
Eugene Zelenko7855e772018-04-03 00:11:50 +000010055 const auto *VD = cast<VarDecl>(D);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010056 assert(VD->isFileVarDecl() && "Expected file scoped var");
10057
Alexey Bataevd01b7492018-08-15 19:45:12 +000010058 // If the decl is marked as `declare target to`, it should be emitted for the
10059 // host and for the device.
10060 if (LangOpts.OpenMP &&
10061 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
10062 return true;
10063
Hans Wennborg56fc62b2014-07-17 20:25:23 +000010064 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
10065 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +000010066 return false;
10067
Richard Smitha0e5e542012-11-12 21:38:00 +000010068 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +000010069 auto Linkage = GetGVALinkageForVariable(VD);
10070 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +000010071 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010072
Richard Smitha4653622017-09-06 20:01:14 +000010073 // We never need to emit a variable that is available in another TU.
10074 if (Linkage == GVA_AvailableExternally)
10075 return false;
10076
Richard Smitha0e5e542012-11-12 21:38:00 +000010077 // Variables that have destruction with side-effects are required.
Richard Smith2b4fa532019-09-29 05:08:46 +000010078 if (VD->needsDestruction(*this))
Richard Smitha0e5e542012-11-12 21:38:00 +000010079 return true;
10080
10081 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +000010082 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +000010083 // We can get a value-dependent initializer during error recovery.
10084 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +000010085 return true;
10086
Richard Smithda383632016-08-15 01:33:41 +000010087 // Likewise, variables with tuple-like bindings are required if their
10088 // bindings have side-effects.
Eugene Zelenko7855e772018-04-03 00:11:50 +000010089 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
10090 for (const auto *BD : DD->bindings())
10091 if (const auto *BindingVD = BD->getHoldingVar())
Richard Smithda383632016-08-15 01:33:41 +000010092 if (DeclMustBeEmitted(BindingVD))
10093 return true;
10094
Richard Smitha0e5e542012-11-12 21:38:00 +000010095 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010096}
Charles Davis53c59df2010-08-16 03:33:14 +000010097
Erich Keane281d20b2018-01-08 21:34:17 +000010098void ASTContext::forEachMultiversionedFunctionVersion(
10099 const FunctionDecl *FD,
Erich Keane0fb16482018-08-13 18:33:20 +000010100 llvm::function_ref<void(FunctionDecl *)> Pred) const {
Erich Keane281d20b2018-01-08 21:34:17 +000010101 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
10102 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
Erich Keane7304f0a2018-11-28 20:58:43 +000010103 FD = FD->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +000010104 for (auto *CurDecl :
10105 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
Erich Keane7304f0a2018-11-28 20:58:43 +000010106 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +000010107 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
10108 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
10109 SeenDecls.insert(CurFD);
10110 Pred(CurFD);
10111 }
10112 }
10113}
10114
Reid Kleckner78af0702013-08-27 23:08:25 +000010115CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
Erich Keane00022812019-05-23 16:05:21 +000010116 bool IsCXXMethod,
10117 bool IsBuiltin) const {
Charles Davis99202b32010-11-09 18:04:24 +000010118 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +000010119 if (IsCXXMethod)
10120 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +000010121
Erich Keane00022812019-05-23 16:05:21 +000010122 // Builtins ignore user-specified default calling convention and remain the
10123 // Target's default calling convention.
10124 if (!IsBuiltin) {
10125 switch (LangOpts.getDefaultCallingConv()) {
10126 case LangOptions::DCC_None:
10127 break;
10128 case LangOptions::DCC_CDecl:
10129 return CC_C;
10130 case LangOptions::DCC_FastCall:
10131 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
10132 return CC_X86FastCall;
10133 break;
10134 case LangOptions::DCC_StdCall:
10135 if (!IsVariadic)
10136 return CC_X86StdCall;
10137 break;
10138 case LangOptions::DCC_VectorCall:
10139 // __vectorcall cannot be applied to variadic functions.
10140 if (!IsVariadic)
10141 return CC_X86VectorCall;
10142 break;
10143 case LangOptions::DCC_RegCall:
10144 // __regcall cannot be applied to variadic functions.
10145 if (!IsVariadic)
10146 return CC_X86RegCall;
10147 break;
10148 }
Alexey Bataeva7547182016-05-18 09:06:38 +000010149 }
Erich Keane39309482019-07-25 17:14:45 +000010150 return Target->getDefaultCallingConv();
Charles Davis99202b32010-11-09 18:04:24 +000010151}
10152
Jay Foad39c79802011-01-12 09:06:06 +000010153bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +000010154 // Pass through to the C++ ABI object
10155 return ABI->isNearlyEmpty(RD);
10156}
10157
Reid Kleckner96f8f932014-02-05 17:27:08 +000010158VTableContextBase *ASTContext::getVTableContext() {
10159 if (!VTContext.get()) {
10160 if (Target->getCXXABI().isMicrosoft())
10161 VTContext.reset(new MicrosoftVTableContext(*this));
10162 else
10163 VTContext.reset(new ItaniumVTableContext(*this));
10164 }
10165 return VTContext.get();
10166}
10167
Yaxun Liuc18e9ec2019-02-14 02:00:09 +000010168MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
10169 if (!T)
10170 T = Target;
10171 switch (T->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000010172 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +000010173 case TargetCXXABI::GenericItanium:
10174 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +000010175 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +000010176 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000010177 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +000010178 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +000010179 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010180 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +000010181 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010182 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010183 }
David Blaikie83d382b2011-09-23 05:06:16 +000010184 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010185}
10186
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010187CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010188
10189size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +000010190 return ASTRecordLayouts.getMemorySize() +
10191 llvm::capacity_in_bytes(ObjCLayouts) +
10192 llvm::capacity_in_bytes(KeyFunctions) +
10193 llvm::capacity_in_bytes(ObjCImpls) +
10194 llvm::capacity_in_bytes(BlockVarCopyInits) +
10195 llvm::capacity_in_bytes(DeclAttrs) +
10196 llvm::capacity_in_bytes(TemplateOrInstantiation) +
10197 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10198 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10199 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10200 llvm::capacity_in_bytes(OverriddenMethods) +
10201 llvm::capacity_in_bytes(Types) +
Richard Smithf19a8b02019-05-02 00:49:14 +000010202 llvm::capacity_in_bytes(VariableArrayTypes);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010203}
Ted Kremenek540017e2011-10-06 05:00:56 +000010204
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010205/// getIntTypeForBitwidth -
10206/// sets integer QualTy according to specified details:
10207/// bitwidth, signed/unsigned.
10208/// Returns empty type if there is no appropriate target types.
10209QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
10210 unsigned Signed) const {
10211 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10212 CanQualType QualTy = getFromTargetType(Ty);
10213 if (!QualTy && DestWidth == 128)
10214 return Signed ? Int128Ty : UnsignedInt128Ty;
10215 return QualTy;
10216}
10217
10218/// getRealTypeForBitwidth -
10219/// sets floating point QualTy according to specified bitwidth.
10220/// Returns empty type if there is no appropriate target types.
10221QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
10222 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
10223 switch (Ty) {
10224 case TargetInfo::Float:
10225 return FloatTy;
10226 case TargetInfo::Double:
10227 return DoubleTy;
10228 case TargetInfo::LongDouble:
10229 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000010230 case TargetInfo::Float128:
10231 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010232 case TargetInfo::NoFloat:
Eugene Zelenko7855e772018-04-03 00:11:50 +000010233 return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010234 }
10235
10236 llvm_unreachable("Unhandled TargetInfo::RealType value");
10237}
10238
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010239void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10240 if (Number > 1)
10241 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +000010242}
10243
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010244unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010245 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010246 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +000010247}
10248
David Majnemer2206bf52014-03-05 08:57:59 +000010249void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10250 if (Number > 1)
10251 StaticLocalNumbers[VD] = Number;
10252}
10253
10254unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010255 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +000010256 return I != StaticLocalNumbers.end() ? I->second : 1;
10257}
10258
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010259MangleNumberingContext &
10260ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010261 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +000010262 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +000010263 if (!MCtx)
10264 MCtx = createMangleNumberingContext();
10265 return *MCtx;
10266}
10267
Reid Klecknerda2bde92019-10-10 01:14:22 +000010268MangleNumberingContext &
10269ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
10270 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
10271 std::unique_ptr<MangleNumberingContext> &MCtx =
10272 ExtraMangleNumberingContexts[D];
10273 if (!MCtx)
10274 MCtx = createMangleNumberingContext();
10275 return *MCtx;
10276}
10277
Justin Lebar20ebffc2016-10-10 16:26:19 +000010278std::unique_ptr<MangleNumberingContext>
10279ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010280 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +000010281}
10282
David Majnemere7a818f2015-03-06 18:53:55 +000010283const CXXConstructorDecl *
10284ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
10285 return ABI->getCopyConstructorForExceptionObject(
10286 cast<CXXRecordDecl>(RD->getFirstDecl()));
10287}
10288
10289void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
10290 CXXConstructorDecl *CD) {
10291 return ABI->addCopyConstructorForExceptionObject(
10292 cast<CXXRecordDecl>(RD->getFirstDecl()),
10293 cast<CXXConstructorDecl>(CD->getFirstDecl()));
10294}
10295
David Majnemer00350522015-08-31 18:48:39 +000010296void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10297 TypedefNameDecl *DD) {
10298 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10299}
10300
10301TypedefNameDecl *
10302ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10303 return ABI->getTypedefNameForUnnamedTagDecl(TD);
10304}
10305
10306void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10307 DeclaratorDecl *DD) {
10308 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10309}
10310
10311DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10312 return ABI->getDeclaratorForUnnamedTagDecl(TD);
10313}
10314
Ted Kremenek540017e2011-10-06 05:00:56 +000010315void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10316 ParamIndices[D] = index;
10317}
10318
10319unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10320 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
Fangrui Song6907ce22018-07-30 19:24:48 +000010321 assert(I != ParamIndices.end() &&
Ted Kremenek540017e2011-10-06 05:00:56 +000010322 "ParmIndices lacks entry set by ParmVarDecl");
10323 return I->second;
10324}
Fariborz Jahanian615de762013-05-28 17:37:39 +000010325
Eric Fiselier708afb52019-05-16 21:04:15 +000010326QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
10327 unsigned Length) const {
10328 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
10329 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
10330 EltTy = EltTy.withConst();
10331
10332 EltTy = adjustStringLiteralBaseType(EltTy);
10333
10334 // Get an array type for the string, according to C99 6.4.5. This includes
10335 // the null terminator character.
Richard Smith772e2662019-10-04 01:25:59 +000010336 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
Eric Fiselier708afb52019-05-16 21:04:15 +000010337 ArrayType::Normal, /*IndexTypeQuals*/ 0);
10338}
10339
10340StringLiteral *
10341ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
10342 StringLiteral *&Result = StringLiteralCache[Key];
10343 if (!Result)
10344 Result = StringLiteral::Create(
10345 *this, Key, StringLiteral::Ascii,
10346 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
10347 SourceLocation());
10348 return Result;
10349}
10350
Fariborz Jahanian615de762013-05-28 17:37:39 +000010351bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10352 const llvm::Triple &T = getTargetInfo().getTriple();
10353 if (!T.isOSDarwin())
10354 return false;
10355
Bob Wilson2c82c3d2013-11-02 23:27:49 +000010356 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10357 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10358 return false;
10359
Fariborz Jahanian615de762013-05-28 17:37:39 +000010360 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10361 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10362 uint64_t Size = sizeChars.getQuantity();
10363 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10364 unsigned Align = alignChars.getQuantity();
10365 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10366 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10367}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010368
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010369/// Template specializations to abstract away from pointers and TypeLocs.
10370/// @{
10371template <typename T>
Sam McCall814e7972018-11-14 10:33:30 +000010372static ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010373 return ast_type_traits::DynTypedNode::create(*Node);
10374}
10375template <>
10376ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
10377 return ast_type_traits::DynTypedNode::create(Node);
10378}
10379template <>
10380ast_type_traits::DynTypedNode
10381createDynTypedNode(const NestedNameSpecifierLoc &Node) {
10382 return ast_type_traits::DynTypedNode::create(Node);
10383}
10384/// @}
10385
Sam McCall814e7972018-11-14 10:33:30 +000010386/// A \c RecursiveASTVisitor that builds a map from nodes to their
10387/// parents as defined by the \c RecursiveASTVisitor.
10388///
10389/// Note that the relationship described here is purely in terms of AST
10390/// traversal - there are other relationships (for example declaration context)
10391/// in the AST that are better modeled by special matchers.
10392///
10393/// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
10394class ASTContext::ParentMap::ASTVisitor
10395 : public RecursiveASTVisitor<ASTVisitor> {
10396public:
10397 ASTVisitor(ParentMap &Map) : Map(Map) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010398
Sam McCall814e7972018-11-14 10:33:30 +000010399private:
10400 friend class RecursiveASTVisitor<ASTVisitor>;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010401
Sam McCall814e7972018-11-14 10:33:30 +000010402 using VisitorBase = RecursiveASTVisitor<ASTVisitor>;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010403
Sam McCall814e7972018-11-14 10:33:30 +000010404 bool shouldVisitTemplateInstantiations() const { return true; }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010405
Sam McCall814e7972018-11-14 10:33:30 +000010406 bool shouldVisitImplicitCode() const { return true; }
10407
10408 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
10409 typename MapTy>
10410 bool TraverseNode(T Node, MapNodeTy MapNode, BaseTraverseFn BaseTraverse,
10411 MapTy *Parents) {
10412 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010413 return true;
Sam McCall814e7972018-11-14 10:33:30 +000010414 if (ParentStack.size() > 0) {
10415 // FIXME: Currently we add the same parent multiple times, but only
10416 // when no memoization data is available for the type.
10417 // For example when we visit all subexpressions of template
10418 // instantiations; this is suboptimal, but benign: the only way to
10419 // visit those is with hasAncestor / hasParent, and those do not create
10420 // new matches.
10421 // The plan is to enable DynTypedNode to be storable in a map or hash
10422 // map. The main problem there is to implement hash functions /
10423 // comparison operators for all types that DynTypedNode supports that
10424 // do not have pointer identity.
10425 auto &NodeOrVector = (*Parents)[MapNode];
10426 if (NodeOrVector.isNull()) {
10427 if (const auto *D = ParentStack.back().get<Decl>())
10428 NodeOrVector = D;
10429 else if (const auto *S = ParentStack.back().get<Stmt>())
10430 NodeOrVector = S;
10431 else
10432 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
10433 } else {
10434 if (!NodeOrVector.template is<ParentVector *>()) {
10435 auto *Vector = new ParentVector(
10436 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
10437 delete NodeOrVector
10438 .template dyn_cast<ast_type_traits::DynTypedNode *>();
10439 NodeOrVector = Vector;
Manuel Klimek95403e62014-05-21 13:28:59 +000010440 }
Sam McCall814e7972018-11-14 10:33:30 +000010441
10442 auto *Vector = NodeOrVector.template get<ParentVector *>();
10443 // Skip duplicates for types that have memoization data.
10444 // We must check that the type has memoization data before calling
10445 // std::find() because DynTypedNode::operator== can't compare all
10446 // types.
10447 bool Found = ParentStack.back().getMemoizationData() &&
10448 std::find(Vector->begin(), Vector->end(),
10449 ParentStack.back()) != Vector->end();
10450 if (!Found)
10451 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +000010452 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010453 }
Sam McCall814e7972018-11-14 10:33:30 +000010454 ParentStack.push_back(createDynTypedNode(Node));
10455 bool Result = BaseTraverse();
10456 ParentStack.pop_back();
10457 return Result;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010458 }
Sam McCall814e7972018-11-14 10:33:30 +000010459
10460 bool TraverseDecl(Decl *DeclNode) {
10461 return TraverseNode(
10462 DeclNode, DeclNode, [&] { return VisitorBase::TraverseDecl(DeclNode); },
10463 &Map.PointerParents);
Manuel Klimek95403e62014-05-21 13:28:59 +000010464 }
Sam McCall814e7972018-11-14 10:33:30 +000010465
10466 bool TraverseStmt(Stmt *StmtNode) {
10467 return TraverseNode(
10468 StmtNode, StmtNode, [&] { return VisitorBase::TraverseStmt(StmtNode); },
10469 &Map.PointerParents);
10470 }
10471
10472 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
10473 return TraverseNode(
10474 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
10475 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
10476 &Map.OtherParents);
10477 }
10478
10479 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
10480 return TraverseNode(
10481 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
10482 [&] { return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); },
10483 &Map.OtherParents);
10484 }
10485
10486 ParentMap &Map;
10487 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
10488};
10489
10490ASTContext::ParentMap::ParentMap(ASTContext &Ctx) {
10491 ASTVisitor(*this).TraverseAST(Ctx);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010492}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010493
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010494ASTContext::DynTypedNodeList
10495ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
Sam McCall814e7972018-11-14 10:33:30 +000010496 if (!Parents)
10497 // We build the parent map for the traversal scope (usually whole TU), as
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010498 // hasAncestor can escape any subtree.
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +000010499 Parents = std::make_unique<ParentMap>(*this);
Sam McCall814e7972018-11-14 10:33:30 +000010500 return Parents->getParents(Node);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010501}
10502
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010503bool
10504ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10505 const ObjCMethodDecl *MethodImpl) {
10506 // No point trying to match an unavailable/deprecated mothod.
10507 if (MethodDecl->hasAttr<UnavailableAttr>()
10508 || MethodDecl->hasAttr<DeprecatedAttr>())
10509 return false;
10510 if (MethodDecl->getObjCDeclQualifier() !=
10511 MethodImpl->getObjCDeclQualifier())
10512 return false;
Alp Toker314cc812014-01-25 16:55:45 +000010513 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010514 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010515
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010516 if (MethodDecl->param_size() != MethodImpl->param_size())
10517 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010518
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010519 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10520 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10521 EF = MethodDecl->param_end();
10522 IM != EM && IF != EF; ++IM, ++IF) {
10523 const ParmVarDecl *DeclVar = (*IF);
10524 const ParmVarDecl *ImplVar = (*IM);
10525 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10526 return false;
10527 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10528 return false;
10529 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010530
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010531 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010532}
Richard Smith053f6c62014-05-16 23:01:30 +000010533
Yaxun Liu402804b2016-12-15 08:09:08 +000010534uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +000010535 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +000010536 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +000010537 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +000010538 else
10539 AS = QT->getPointeeType().getAddressSpace();
10540
10541 return getTargetInfo().getNullPointerValue(AS);
10542}
10543
Alexander Richardson6d989432017-10-15 18:48:14 +000010544unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10545 if (isTargetAddressSpace(AS))
10546 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +000010547 else
Alexander Richardson6d989432017-10-15 18:48:14 +000010548 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +000010549}
10550
Leonard Chanab80f3c2018-06-14 14:53:51 +000010551QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
10552 assert(Ty->isFixedPointType());
10553
10554 if (Ty->isSaturatedFixedPointType()) return Ty;
10555
Simon Pilgrimeed4b122019-10-02 11:48:06 +000010556 switch (Ty->castAs<BuiltinType>()->getKind()) {
Leonard Chanab80f3c2018-06-14 14:53:51 +000010557 default:
10558 llvm_unreachable("Not a fixed point type!");
10559 case BuiltinType::ShortAccum:
10560 return SatShortAccumTy;
10561 case BuiltinType::Accum:
10562 return SatAccumTy;
10563 case BuiltinType::LongAccum:
10564 return SatLongAccumTy;
10565 case BuiltinType::UShortAccum:
10566 return SatUnsignedShortAccumTy;
10567 case BuiltinType::UAccum:
10568 return SatUnsignedAccumTy;
10569 case BuiltinType::ULongAccum:
10570 return SatUnsignedLongAccumTy;
10571 case BuiltinType::ShortFract:
10572 return SatShortFractTy;
10573 case BuiltinType::Fract:
10574 return SatFractTy;
10575 case BuiltinType::LongFract:
10576 return SatLongFractTy;
10577 case BuiltinType::UShortFract:
10578 return SatUnsignedShortFractTy;
10579 case BuiltinType::UFract:
10580 return SatUnsignedFractTy;
10581 case BuiltinType::ULongFract:
10582 return SatUnsignedLongFractTy;
10583 }
10584}
10585
Matt Arsenaultc65f9662018-08-02 12:14:28 +000010586LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
10587 if (LangOpts.OpenCL)
10588 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
10589
10590 if (LangOpts.CUDA)
10591 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
10592
10593 return getLangASFromTargetAS(AS);
10594}
10595
Richard Smith053f6c62014-05-16 23:01:30 +000010596// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10597// doesn't include ASTContext.h
10598template
10599clang::LazyGenerationalUpdatePtr<
10600 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10601clang::LazyGenerationalUpdatePtr<
10602 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10603 const clang::ASTContext &Ctx, Decl *Value);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010604
10605unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10606 assert(Ty->isFixedPointType());
10607
Leonard Chandb01c3a2018-06-20 17:19:40 +000010608 const TargetInfo &Target = getTargetInfo();
Simon Pilgrim9588ae72019-10-03 21:47:42 +000010609 switch (Ty->castAs<BuiltinType>()->getKind()) {
Leonard Chandb01c3a2018-06-20 17:19:40 +000010610 default:
10611 llvm_unreachable("Not a fixed point type!");
10612 case BuiltinType::ShortAccum:
10613 case BuiltinType::SatShortAccum:
10614 return Target.getShortAccumScale();
10615 case BuiltinType::Accum:
10616 case BuiltinType::SatAccum:
10617 return Target.getAccumScale();
10618 case BuiltinType::LongAccum:
10619 case BuiltinType::SatLongAccum:
10620 return Target.getLongAccumScale();
10621 case BuiltinType::UShortAccum:
10622 case BuiltinType::SatUShortAccum:
10623 return Target.getUnsignedShortAccumScale();
10624 case BuiltinType::UAccum:
10625 case BuiltinType::SatUAccum:
10626 return Target.getUnsignedAccumScale();
10627 case BuiltinType::ULongAccum:
10628 case BuiltinType::SatULongAccum:
10629 return Target.getUnsignedLongAccumScale();
10630 case BuiltinType::ShortFract:
10631 case BuiltinType::SatShortFract:
10632 return Target.getShortFractScale();
10633 case BuiltinType::Fract:
10634 case BuiltinType::SatFract:
10635 return Target.getFractScale();
10636 case BuiltinType::LongFract:
10637 case BuiltinType::SatLongFract:
10638 return Target.getLongFractScale();
10639 case BuiltinType::UShortFract:
10640 case BuiltinType::SatUShortFract:
10641 return Target.getUnsignedShortFractScale();
10642 case BuiltinType::UFract:
10643 case BuiltinType::SatUFract:
10644 return Target.getUnsignedFractScale();
10645 case BuiltinType::ULongFract:
10646 case BuiltinType::SatULongFract:
10647 return Target.getUnsignedLongFractScale();
10648 }
10649}
10650
10651unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10652 assert(Ty->isFixedPointType());
10653
Leonard Chandb01c3a2018-06-20 17:19:40 +000010654 const TargetInfo &Target = getTargetInfo();
Simon Pilgrim9588ae72019-10-03 21:47:42 +000010655 switch (Ty->castAs<BuiltinType>()->getKind()) {
Leonard Chandb01c3a2018-06-20 17:19:40 +000010656 default:
10657 llvm_unreachable("Not a fixed point type!");
10658 case BuiltinType::ShortAccum:
10659 case BuiltinType::SatShortAccum:
10660 return Target.getShortAccumIBits();
10661 case BuiltinType::Accum:
10662 case BuiltinType::SatAccum:
10663 return Target.getAccumIBits();
10664 case BuiltinType::LongAccum:
10665 case BuiltinType::SatLongAccum:
10666 return Target.getLongAccumIBits();
10667 case BuiltinType::UShortAccum:
10668 case BuiltinType::SatUShortAccum:
10669 return Target.getUnsignedShortAccumIBits();
10670 case BuiltinType::UAccum:
10671 case BuiltinType::SatUAccum:
10672 return Target.getUnsignedAccumIBits();
10673 case BuiltinType::ULongAccum:
10674 case BuiltinType::SatULongAccum:
10675 return Target.getUnsignedLongAccumIBits();
10676 case BuiltinType::ShortFract:
10677 case BuiltinType::SatShortFract:
10678 case BuiltinType::Fract:
10679 case BuiltinType::SatFract:
10680 case BuiltinType::LongFract:
10681 case BuiltinType::SatLongFract:
10682 case BuiltinType::UShortFract:
10683 case BuiltinType::SatUShortFract:
10684 case BuiltinType::UFract:
10685 case BuiltinType::SatUFract:
10686 case BuiltinType::ULongFract:
10687 case BuiltinType::SatULongFract:
10688 return 0;
10689 }
10690}
Leonard Chana6779422018-08-06 16:42:37 +000010691
10692FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
Erich Keane8e772162019-01-18 19:31:54 +000010693 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
10694 "Can only get the fixed point semantics for a "
10695 "fixed point or integer type.");
Leonard Chan2044ac82019-01-16 18:13:59 +000010696 if (Ty->isIntegerType())
10697 return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty),
10698 Ty->isSignedIntegerType());
10699
Leonard Chana6779422018-08-06 16:42:37 +000010700 bool isSigned = Ty->isSignedFixedPointType();
10701 return FixedPointSemantics(
10702 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
10703 Ty->isSaturatedFixedPointType(),
10704 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
10705}
10706
10707APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
10708 assert(Ty->isFixedPointType());
10709 return APFixedPoint::getMax(getFixedPointSemantics(Ty));
10710}
10711
10712APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
10713 assert(Ty->isFixedPointType());
10714 return APFixedPoint::getMin(getFixedPointSemantics(Ty));
10715}
Leonard Chan2044ac82019-01-16 18:13:59 +000010716
10717QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
10718 assert(Ty->isUnsignedFixedPointType() &&
10719 "Expected unsigned fixed point type");
Leonard Chan2044ac82019-01-16 18:13:59 +000010720
Simon Pilgrim9588ae72019-10-03 21:47:42 +000010721 switch (Ty->castAs<BuiltinType>()->getKind()) {
Leonard Chan2044ac82019-01-16 18:13:59 +000010722 case BuiltinType::UShortAccum:
10723 return ShortAccumTy;
10724 case BuiltinType::UAccum:
10725 return AccumTy;
10726 case BuiltinType::ULongAccum:
10727 return LongAccumTy;
10728 case BuiltinType::SatUShortAccum:
10729 return SatShortAccumTy;
10730 case BuiltinType::SatUAccum:
10731 return SatAccumTy;
10732 case BuiltinType::SatULongAccum:
10733 return SatLongAccumTy;
10734 case BuiltinType::UShortFract:
10735 return ShortFractTy;
10736 case BuiltinType::UFract:
10737 return FractTy;
10738 case BuiltinType::ULongFract:
10739 return LongFractTy;
10740 case BuiltinType::SatUShortFract:
10741 return SatShortFractTy;
10742 case BuiltinType::SatUFract:
10743 return SatFractTy;
10744 case BuiltinType::SatULongFract:
10745 return SatLongFractTy;
10746 default:
10747 llvm_unreachable("Unexpected unsigned fixed point type");
10748 }
10749}