blob: a09b1aca7c2008bda2c55d3ca4e9e06d36a005b5 [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"
Saar Razfdf80e82019-12-06 01:30:21 +020017#include "clang/AST/ASTConcept.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000018#include "clang/AST/ASTMutationListener.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000019#include "clang/AST/ASTTypeTraits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000020#include "clang/AST/Attr.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000021#include "clang/AST/AttrIterator.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000022#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000023#include "clang/AST/Comment.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000024#include "clang/AST/Decl.h"
25#include "clang/AST/DeclBase.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000026#include "clang/AST/DeclCXX.h"
Chandler Carruthaa36b892015-12-30 03:40:23 +000027#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000028#include "clang/AST/DeclObjC.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000029#include "clang/AST/DeclOpenMP.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000030#include "clang/AST/DeclTemplate.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000031#include "clang/AST/DeclarationName.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000032#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000033#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000034#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000035#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000036#include "clang/AST/MangleNumberingContext.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000037#include "clang/AST/NestedNameSpecifier.h"
38#include "clang/AST/RawCommentList.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000039#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000040#include "clang/AST/RecursiveASTVisitor.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000041#include "clang/AST/Stmt.h"
42#include "clang/AST/TemplateBase.h"
43#include "clang/AST/TemplateName.h"
44#include "clang/AST/Type.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000045#include "clang/AST/TypeLoc.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000046#include "clang/AST/UnresolvedSet.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000047#include "clang/AST/VTableBuilder.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000048#include "clang/Basic/AddressSpaces.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000049#include "clang/Basic/Builtins.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000050#include "clang/Basic/CommentOptions.h"
Eugene Zelenko7855e772018-04-03 00:11:50 +000051#include "clang/Basic/ExceptionSpecificationType.h"
Leonard Chana6779422018-08-06 16:42:37 +000052#include "clang/Basic/FixedPoint.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000053#include "clang/Basic/IdentifierTable.h"
54#include "clang/Basic/LLVM.h"
55#include "clang/Basic/LangOptions.h"
56#include "clang/Basic/Linkage.h"
57#include "clang/Basic/ObjCRuntime.h"
58#include "clang/Basic/SanitizerBlacklist.h"
59#include "clang/Basic/SourceLocation.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000060#include "clang/Basic/SourceManager.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000061#include "clang/Basic/Specifiers.h"
62#include "clang/Basic/TargetCXXABI.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000063#include "clang/Basic/TargetInfo.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000064#include "clang/Basic/XRayLists.h"
65#include "llvm/ADT/APInt.h"
66#include "llvm/ADT/APSInt.h"
67#include "llvm/ADT/ArrayRef.h"
68#include "llvm/ADT/DenseMap.h"
69#include "llvm/ADT/DenseSet.h"
70#include "llvm/ADT/FoldingSet.h"
71#include "llvm/ADT/None.h"
72#include "llvm/ADT/Optional.h"
73#include "llvm/ADT/PointerUnion.h"
74#include "llvm/ADT/STLExtras.h"
75#include "llvm/ADT/SmallPtrSet.h"
76#include "llvm/ADT/SmallVector.h"
Anders Carlssond8499822007-10-29 05:01:08 +000077#include "llvm/ADT/StringExtras.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000078#include "llvm/ADT/StringRef.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000079#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000080#include "llvm/Support/Capacity.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000081#include "llvm/Support/Casting.h"
82#include "llvm/Support/Compiler.h"
83#include "llvm/Support/ErrorHandling.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000084#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000085#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000086#include <algorithm>
87#include <cassert>
88#include <cstddef>
89#include <cstdint>
90#include <cstdlib>
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000091#include <map>
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000092#include <memory>
93#include <string>
94#include <tuple>
95#include <utility>
Anders Carlssona4267a62009-07-18 21:19:52 +000096
Chris Lattnerddc135e2006-11-10 06:34:16 +000097using namespace clang;
98
Steve Naroff0af91202007-04-27 21:51:21 +000099enum FloatingRank {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +0000100 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +0000101};
Stephen Kelly0a717d52019-05-12 21:09:32 +0100102const Expr *ASTContext::traverseIgnored(const Expr *E) const {
103 return traverseIgnored(const_cast<Expr *>(E));
104}
105
106Expr *ASTContext::traverseIgnored(Expr *E) const {
107 if (!E)
108 return nullptr;
109
110 switch (Traversal) {
111 case ast_type_traits::TK_AsIs:
112 return E;
113 case ast_type_traits::TK_IgnoreImplicitCastsAndParentheses:
114 return E->IgnoreParenImpCasts();
Stephen Kelly98e8f772019-05-04 16:51:58 +0100115 case ast_type_traits::TK_IgnoreUnlessSpelledInSource:
116 return E->IgnoreUnlessSpelledInSource();
Stephen Kelly0a717d52019-05-12 21:09:32 +0100117 }
118 llvm_unreachable("Invalid Traversal type!");
119}
120
121ast_type_traits::DynTypedNode
122ASTContext::traverseIgnored(const ast_type_traits::DynTypedNode &N) const {
123 if (const auto *E = N.get<Expr>()) {
124 return ast_type_traits::DynTypedNode::create(*traverseIgnored(E));
125 }
126 return N;
127}
Steve Naroff0af91202007-04-27 21:51:21 +0000128
Jan Korousf31d8df2019-08-13 18:11:44 +0000129/// \returns location that is relevant when searching for Doc comments related
130/// to \p D.
131static SourceLocation getDeclLocForCommentSearch(const Decl *D,
132 SourceManager &SourceMgr) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000133 assert(D);
134
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000135 // User can not attach documentation to implicit declarations.
136 if (D->isImplicit())
Jan Korousf31d8df2019-08-13 18:11:44 +0000137 return {};
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000138
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000139 // User can not attach documentation to implicit instantiations.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000140 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000141 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Jan Korousf31d8df2019-08-13 18:11:44 +0000142 return {};
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000143 }
144
Eugene Zelenko7855e772018-04-03 00:11:50 +0000145 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000146 if (VD->isStaticDataMember() &&
147 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Jan Korousf31d8df2019-08-13 18:11:44 +0000148 return {};
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000149 }
150
Eugene Zelenko7855e772018-04-03 00:11:50 +0000151 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000152 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Jan Korousf31d8df2019-08-13 18:11:44 +0000153 return {};
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000154 }
155
Eugene Zelenko7855e772018-04-03 00:11:50 +0000156 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000157 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
158 if (TSK == TSK_ImplicitInstantiation ||
159 TSK == TSK_Undeclared)
Jan Korousf31d8df2019-08-13 18:11:44 +0000160 return {};
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000161 }
162
Eugene Zelenko7855e772018-04-03 00:11:50 +0000163 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000164 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Jan Korousf31d8df2019-08-13 18:11:44 +0000165 return {};
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000166 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000167 if (const auto *TD = dyn_cast<TagDecl>(D)) {
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000168 // When tag declaration (but not definition!) is part of the
169 // decl-specifier-seq of some other declaration, it doesn't get comment
170 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Jan Korousf31d8df2019-08-13 18:11:44 +0000171 return {};
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000172 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000173 // TODO: handle comments for function parameters properly.
174 if (isa<ParmVarDecl>(D))
Jan Korousf31d8df2019-08-13 18:11:44 +0000175 return {};
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000176
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000177 // TODO: we could look up template parameter documentation in the template
178 // documentation.
179 if (isa<TemplateTypeParmDecl>(D) ||
180 isa<NonTypeTemplateParmDecl>(D) ||
181 isa<TemplateTemplateParmDecl>(D))
Jan Korousf31d8df2019-08-13 18:11:44 +0000182 return {};
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000183
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000184 // Find declaration location.
185 // For Objective-C declarations we generally don't expect to have multiple
186 // declarators, thus use declaration starting location as the "declaration
187 // location".
188 // For all other declarations multiple declarators are used quite frequently,
189 // so we use the location of the identifier as the "declaration location".
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000190 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000191 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000192 isa<RedeclarableTemplateDecl>(D) ||
Sam McCalla433e712019-11-13 21:30:31 +0100193 isa<ClassTemplateSpecializationDecl>(D) ||
194 // Allow association with Y across {} in `typedef struct X {} Y`.
195 isa<TypedefDecl>(D))
Jan Korousf31d8df2019-08-13 18:11:44 +0000196 return D->getBeginLoc();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000197 else {
Jan Korousf31d8df2019-08-13 18:11:44 +0000198 const SourceLocation DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000199 if (DeclLoc.isMacroID()) {
200 if (isa<TypedefDecl>(D)) {
201 // If location of the typedef name is in a macro, it is because being
202 // declared via a macro. Try using declaration's starting location as
203 // the "declaration location".
Jan Korousf31d8df2019-08-13 18:11:44 +0000204 return D->getBeginLoc();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000205 } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000206 // If location of the tag decl is inside a macro, but the spelling of
207 // the tag name comes from a macro argument, it looks like a special
208 // macro like NS_ENUM is being used to define the tag decl. In that
209 // case, adjust the source location to the expansion loc so that we can
210 // attach the comment to the tag decl.
211 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
212 TD->isCompleteDefinition())
Jan Korousf31d8df2019-08-13 18:11:44 +0000213 return SourceMgr.getExpansionLoc(DeclLoc);
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000214 }
215 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000216 return DeclLoc;
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000217 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000218
Jan Korousf31d8df2019-08-13 18:11:44 +0000219 return {};
220}
221
222RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
223 const Decl *D, const SourceLocation RepresentativeLocForDecl,
224 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000225 // If the declaration doesn't map directly to a location in a file, we
226 // can't find the comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000227 if (RepresentativeLocForDecl.isInvalid() ||
228 !RepresentativeLocForDecl.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000229 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000230
Jan Korous6644d012019-04-10 20:23:33 +0000231 // If there are no comments anywhere, we won't find anything.
Jan Korousf31d8df2019-08-13 18:11:44 +0000232 if (CommentsInTheFile.empty())
Jan Korous6644d012019-04-10 20:23:33 +0000233 return nullptr;
234
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000235 // Decompose the location for the declaration and find the beginning of the
236 // file buffer.
Jan Korousf31d8df2019-08-13 18:11:44 +0000237 const std::pair<FileID, unsigned> DeclLocDecomp =
238 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
239
240 // Slow path.
241 auto OffsetCommentBehindDecl =
242 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000243
244 // First check whether we have a trailing comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000245 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
246 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
247 if ((CommentBehindDecl->isDocumentation() ||
248 LangOpts.CommentOpts.ParseAllComments) &&
249 CommentBehindDecl->isTrailingComment() &&
250 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
251 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
252
253 // Check that Doxygen trailing comment comes after the declaration, starts
254 // on the same line and in the same file as the declaration.
255 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
256 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
257 OffsetCommentBehindDecl->first)) {
258 return CommentBehindDecl;
259 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000260 }
261 }
262
263 // The comment just after the declaration was not a trailing comment.
264 // Let's look at the previous comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000265 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000266 return nullptr;
Jan Korousf31d8df2019-08-13 18:11:44 +0000267
268 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
269 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000270
271 // Check that we actually have a non-member Doxygen comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000272 if (!(CommentBeforeDecl->isDocumentation() ||
David L. Jones13d5a872018-03-02 00:07:45 +0000273 LangOpts.CommentOpts.ParseAllComments) ||
Jan Korousf31d8df2019-08-13 18:11:44 +0000274 CommentBeforeDecl->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000275 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000276
277 // Decompose the end of the comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000278 const unsigned CommentEndOffset =
279 Comments.getCommentEndOffset(CommentBeforeDecl);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000280
281 // Get the corresponding buffer.
282 bool Invalid = false;
283 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
284 &Invalid).data();
285 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000286 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000287
288 // Extract text between the comment and declaration.
Jan Korousf31d8df2019-08-13 18:11:44 +0000289 StringRef Text(Buffer + CommentEndOffset,
290 DeclLocDecomp.second - CommentEndOffset);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000291
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000292 // There should be no other declarations or preprocessor directives between
293 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000294 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000295 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000296
Jan Korousf31d8df2019-08-13 18:11:44 +0000297 return CommentBeforeDecl;
298}
299
300RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
301 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
302
303 // If the declaration doesn't map directly to a location in a file, we
304 // can't find the comment.
305 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
306 return nullptr;
307
308 if (ExternalSource && !CommentsLoaded) {
309 ExternalSource->ReadComments();
310 CommentsLoaded = true;
311 }
312
313 if (Comments.empty())
314 return nullptr;
315
316 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
317 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
318 if (!CommentsInThisFile || CommentsInThisFile->empty())
319 return nullptr;
320
321 return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000322}
323
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000324/// If we have a 'templated' declaration for a template, adjust 'D' to
325/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000326/// If we have an implicit instantiation, adjust 'D' to refer to template.
Jan Korousf31d8df2019-08-13 18:11:44 +0000327static const Decl &adjustDeclToTemplate(const Decl &D) {
328 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000329 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000330 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Jan Korousf31d8df2019-08-13 18:11:44 +0000331 return *FTD;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000332
333 // Nothing to do if function is not an implicit instantiation.
334 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
335 return D;
336
337 // Function is an implicit instantiation of a function template?
338 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
Jan Korousf31d8df2019-08-13 18:11:44 +0000339 return *FTD;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000340
341 // Function is instantiated from a member definition of a class template?
342 if (const FunctionDecl *MemberDecl =
343 FD->getInstantiatedFromMemberFunction())
Jan Korousf31d8df2019-08-13 18:11:44 +0000344 return *MemberDecl;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000345
346 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000347 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000348 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000349 // Static data member is instantiated from a member definition of a class
350 // template?
351 if (VD->isStaticDataMember())
352 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
Jan Korousf31d8df2019-08-13 18:11:44 +0000353 return *MemberDecl;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000354
355 return D;
356 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000357 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000358 // Is this class declaration part of a class template?
359 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
Jan Korousf31d8df2019-08-13 18:11:44 +0000360 return *CTD;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000361
362 // Class is an implicit instantiation of a class template or partial
363 // specialization?
Eugene Zelenko7855e772018-04-03 00:11:50 +0000364 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000365 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
366 return D;
367 llvm::PointerUnion<ClassTemplateDecl *,
368 ClassTemplatePartialSpecializationDecl *>
369 PU = CTSD->getSpecializedTemplateOrPartial();
Jan Korousf31d8df2019-08-13 18:11:44 +0000370 return PU.is<ClassTemplateDecl *>()
371 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
372 : *static_cast<const Decl *>(
373 PU.get<ClassTemplatePartialSpecializationDecl *>());
Dmitri Gribenko90631802012-08-22 17:44:32 +0000374 }
375
376 // Class is instantiated from a member definition of a class template?
377 if (const MemberSpecializationInfo *Info =
Jan Korousf31d8df2019-08-13 18:11:44 +0000378 CRD->getMemberSpecializationInfo())
379 return *Info->getInstantiatedFrom();
Dmitri Gribenko90631802012-08-22 17:44:32 +0000380
381 return D;
382 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000383 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000384 // Enum is instantiated from a member definition of a class template?
385 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
Jan Korousf31d8df2019-08-13 18:11:44 +0000386 return *MemberDecl;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000387
388 return D;
389 }
390 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000391 return D;
392}
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000393
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000394const RawComment *ASTContext::getRawCommentForAnyRedecl(
395 const Decl *D,
396 const Decl **OriginalDecl) const {
Jan Korousf31d8df2019-08-13 18:11:44 +0000397 if (!D) {
398 if (OriginalDecl)
399 OriginalDecl = nullptr;
400 return nullptr;
401 }
Douglas Gregor35ceb272012-08-13 16:37:30 +0000402
Jan Korousf31d8df2019-08-13 18:11:44 +0000403 D = &adjustDeclToTemplate(*D);
404
405 // Any comment directly attached to D?
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000406 {
Jan Korousf31d8df2019-08-13 18:11:44 +0000407 auto DeclComment = DeclRawComments.find(D);
408 if (DeclComment != DeclRawComments.end()) {
409 if (OriginalDecl)
410 *OriginalDecl = D;
411 return DeclComment->second;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000412 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000413 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000414
Jan Korousf31d8df2019-08-13 18:11:44 +0000415 // Any comment attached to any redeclaration of D?
416 const Decl *CanonicalD = D->getCanonicalDecl();
417 if (!CanonicalD)
418 return nullptr;
419
420 {
421 auto RedeclComment = RedeclChainComments.find(CanonicalD);
422 if (RedeclComment != RedeclChainComments.end()) {
423 if (OriginalDecl)
424 *OriginalDecl = RedeclComment->second;
425 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
426 assert(CommentAtRedecl != DeclRawComments.end() &&
427 "This decl is supposed to have comment attached.");
428 return CommentAtRedecl->second;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000429 }
430 }
431
Jan Korousf31d8df2019-08-13 18:11:44 +0000432 // Any redeclarations of D that we haven't checked for comments yet?
433 // We can't use DenseMap::iterator directly since it'd get invalid.
434 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
435 auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
436 if (LookupRes != CommentlessRedeclChains.end())
437 return LookupRes->second;
438 return nullptr;
439 }();
440
441 for (const auto Redecl : D->redecls()) {
442 assert(Redecl);
443 // Skip all redeclarations that have been checked previously.
444 if (LastCheckedRedecl) {
445 if (LastCheckedRedecl == Redecl) {
446 LastCheckedRedecl = nullptr;
447 }
448 continue;
449 }
450 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
451 if (RedeclComment) {
452 cacheRawCommentForDecl(*Redecl, *RedeclComment);
453 if (OriginalDecl)
454 *OriginalDecl = Redecl;
455 return RedeclComment;
456 }
457 CommentlessRedeclChains[CanonicalD] = Redecl;
458 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000459
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000460 if (OriginalDecl)
Jan Korousf31d8df2019-08-13 18:11:44 +0000461 *OriginalDecl = nullptr;
462 return nullptr;
463}
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000464
Jan Korousf31d8df2019-08-13 18:11:44 +0000465void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
466 const RawComment &Comment) const {
467 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
468 DeclRawComments.try_emplace(&OriginalD, &Comment);
469 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
470 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
471 CommentlessRedeclChains.erase(CanonicalDecl);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000472}
473
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000474static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
475 SmallVectorImpl<const NamedDecl *> &Redeclared) {
476 const DeclContext *DC = ObjCMethod->getDeclContext();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000477 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000478 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
479 if (!ID)
480 return;
481 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000482 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000483 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000484 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000485 ObjCMethod->isInstanceMethod()))
486 Redeclared.push_back(RedeclaredMethod);
487 }
488 }
489}
490
Jan Korousf31d8df2019-08-13 18:11:44 +0000491void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
492 const Preprocessor *PP) {
493 if (Comments.empty() || Decls.empty())
494 return;
495
496 // See if there are any new comments that are not attached to a decl.
497 // The location doesn't have to be precise - we care only about the file.
498 const FileID File =
499 SourceMgr.getDecomposedLoc((*Decls.begin())->getLocation()).first;
500 auto CommentsInThisFile = Comments.getCommentsInFile(File);
501 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
502 CommentsInThisFile->rbegin()->second->isAttached())
503 return;
504
505 // There is at least one comment not attached to a decl.
506 // Maybe it should be attached to one of Decls?
507 //
508 // Note that this way we pick up not only comments that precede the
509 // declaration, but also comments that *follow* the declaration -- thanks to
510 // the lookahead in the lexer: we've consumed the semicolon and looked
511 // ahead through comments.
512
513 for (const Decl *D : Decls) {
514 assert(D);
515 if (D->isInvalidDecl())
516 continue;
517
518 D = &adjustDeclToTemplate(*D);
519
520 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
521
522 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
523 continue;
524
525 if (DeclRawComments.count(D) > 0)
526 continue;
527
528 if (RawComment *const DocComment =
529 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
530 cacheRawCommentForDecl(*D, *DocComment);
531 comments::FullComment *FC = DocComment->parse(*this, PP, D);
532 ParsedComments[D->getCanonicalDecl()] = FC;
533 }
534 }
535}
536
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000537comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
538 const Decl *D) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000539 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000540 ThisDeclInfo->CommentDecl = D;
541 ThisDeclInfo->IsFilled = false;
542 ThisDeclInfo->fill();
543 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000544 if (!ThisDeclInfo->TemplateParameters)
545 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000546 comments::FullComment *CFC =
547 new (*this) comments::FullComment(FC->getBlocks(),
548 ThisDeclInfo);
549 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000550}
551
Richard Smithb39b9d52013-05-21 05:24:00 +0000552comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
553 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000554 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000555}
556
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000557comments::FullComment *ASTContext::getCommentForDecl(
558 const Decl *D,
559 const Preprocessor *PP) const {
Jan Korousf31d8df2019-08-13 18:11:44 +0000560 if (!D || D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000561 return nullptr;
Jan Korousf31d8df2019-08-13 18:11:44 +0000562 D = &adjustDeclToTemplate(*D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000563
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000564 const Decl *Canonical = D->getCanonicalDecl();
565 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
566 ParsedComments.find(Canonical);
Fangrui Song6907ce22018-07-30 19:24:48 +0000567
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000568 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000569 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000570 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000571 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000572 return CFC;
573 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000574 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000575 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000576
Jan Korousf31d8df2019-08-13 18:11:44 +0000577 const Decl *OriginalDecl = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +0000578
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000579 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000580 if (!RC) {
581 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000582 SmallVector<const NamedDecl*, 8> Overridden;
Eugene Zelenko7855e772018-04-03 00:11:50 +0000583 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000584 if (OMD && OMD->isPropertyAccessor())
585 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
586 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
587 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000588 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000589 addRedeclaredMethods(OMD, Overridden);
590 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000591 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
592 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
593 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000594 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000595 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000596 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000597 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000598 QualType QT = TD->getUnderlyingType();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000599 if (const auto *TT = QT->getAs<TagType>())
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000600 if (const Decl *TD = TT->getDecl())
601 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000602 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000603 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000604 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000605 while (IC->getSuperClass()) {
606 IC = IC->getSuperClass();
607 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
608 return cloneFullComment(FC, D);
609 }
610 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000611 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000612 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
613 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
614 return cloneFullComment(FC, D);
615 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000616 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000617 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000618 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000619 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000620 for (const auto &I : RD->bases()) {
621 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000622 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000623 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000624 if (Ty.isNull())
625 continue;
626 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
627 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
628 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000629
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000630 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
631 return cloneFullComment(FC, D);
632 }
633 }
634 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000635 for (const auto &I : RD->vbases()) {
636 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000637 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000638 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000639 if (Ty.isNull())
640 continue;
641 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
642 if (!(VirtualBase= VirtualBase->getDefinition()))
643 continue;
644 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
645 return cloneFullComment(FC, D);
646 }
647 }
648 }
Craig Topper36250ad2014-05-12 05:36:57 +0000649 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000650 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000651
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000652 // If the RawComment was attached to other redeclaration of this Decl, we
653 // should parse the comment in context of that other Decl. This is important
654 // because comments can contain references to parameter names which can be
655 // different across redeclarations.
Jan Korousf31d8df2019-08-13 18:11:44 +0000656 if (D != OriginalDecl && OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000657 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000658
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000659 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000660 ParsedComments[Canonical] = FC;
661 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000662}
663
Fangrui Song6907ce22018-07-30 19:24:48 +0000664void
665ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000666 TemplateTemplateParmDecl *Parm) {
667 ID.AddInteger(Parm->getDepth());
668 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000669 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000670
671 TemplateParameterList *Params = Parm->getTemplateParameters();
672 ID.AddInteger(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000673 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000674 PEnd = Params->end();
675 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000676 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000677 ID.AddInteger(0);
678 ID.AddBoolean(TTP->isParameterPack());
679 continue;
680 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000681
Eugene Zelenko7855e772018-04-03 00:11:50 +0000682 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000683 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000684 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000685 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000686 if (NTTP->isExpandedParameterPack()) {
687 ID.AddBoolean(true);
688 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000689 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
690 QualType T = NTTP->getExpansionType(I);
691 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
692 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000693 } else
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000694 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000695 continue;
696 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000697
Eugene Zelenko7855e772018-04-03 00:11:50 +0000698 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000699 ID.AddInteger(2);
700 Profile(ID, TTP);
701 }
702}
703
704TemplateTemplateParmDecl *
705ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000706 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000707 // Check if we already have a canonical template template parameter.
708 llvm::FoldingSetNodeID ID;
709 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000710 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000711 CanonicalTemplateTemplateParm *Canonical
712 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
713 if (Canonical)
714 return Canonical->getParam();
Fangrui Song6907ce22018-07-30 19:24:48 +0000715
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000716 // Build a canonical template parameter list.
717 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000718 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000719 CanonParams.reserve(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000720 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000721 PEnd = Params->end();
722 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000723 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000724 CanonParams.push_back(
Fangrui Song6907ce22018-07-30 19:24:48 +0000725 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000726 SourceLocation(),
727 SourceLocation(),
728 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000729 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000730 TTP->isParameterPack()));
Eugene Zelenko7855e772018-04-03 00:11:50 +0000731 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000732 QualType T = getCanonicalType(NTTP->getType());
733 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
734 NonTypeTemplateParmDecl *Param;
735 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000736 SmallVector<QualType, 2> ExpandedTypes;
737 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000738 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
739 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
740 ExpandedTInfos.push_back(
741 getTrivialTypeSourceInfo(ExpandedTypes.back()));
742 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000743
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000744 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000745 SourceLocation(),
746 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000747 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000748 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000749 T,
750 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000751 ExpandedTypes,
752 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000753 } else {
754 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000755 SourceLocation(),
756 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000757 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000758 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000759 T,
760 NTTP->isParameterPack(),
761 TInfo);
762 }
763 CanonParams.push_back(Param);
764
765 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000766 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
767 cast<TemplateTemplateParmDecl>(*P)));
768 }
769
Saar Raz0330fba2019-10-15 18:44:06 +0000770 assert(!TTP->getTemplateParameters()->getRequiresClause() &&
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000771 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000772 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000773
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000774 TemplateTemplateParmDecl *CanonTTP
Fangrui Song6907ce22018-07-30 19:24:48 +0000775 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000776 SourceLocation(), TTP->getDepth(),
Fangrui Song6907ce22018-07-30 19:24:48 +0000777 TTP->getPosition(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000778 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000779 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000780 TemplateParameterList::Create(*this, SourceLocation(),
781 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000782 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000783 SourceLocation(),
784 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000785
786 // Get the new insert position for the node we care about.
787 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000788 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000789 (void)Canonical;
790
791 // Create the canonical template template parameter entry.
792 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
793 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
794 return CanonTTP;
795}
796
Charles Davis53c59df2010-08-16 03:33:14 +0000797CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000798 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000799
John McCall359b8852013-01-25 22:30:49 +0000800 switch (T.getCXXABI().getKind()) {
Petr Hosek9c3f9b92019-09-06 18:59:43 -0700801 case TargetCXXABI::Fuchsia:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000802 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000803 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000804 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000805 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000806 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000807 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000808 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000809 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000810 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000811 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000812 return CreateMicrosoftCXXABI(*this);
813 }
David Blaikie8a40f702012-01-17 06:56:22 +0000814 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000815}
816
Nandor Licker950b70d2019-09-13 09:46:16 +0000817interp::Context &ASTContext::getInterpContext() {
818 if (!InterpContext) {
819 InterpContext.reset(new interp::Context(*this));
820 }
821 return *InterpContext.get();
822}
823
Alexander Richardson6d989432017-10-15 18:48:14 +0000824static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
825 const LangOptions &LOpts) {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000826 if (LOpts.FakeAddressSpaceMap) {
827 // The fake address space map must have a distinct entry for each
828 // language-specific address space.
829 static const unsigned FakeAddrSpaceMap[] = {
Amy Huanga85f5ef2019-10-24 16:34:25 -0700830 0, // Default
831 1, // opencl_global
832 3, // opencl_local
833 2, // opencl_constant
834 0, // opencl_private
835 4, // opencl_generic
836 5, // cuda_device
837 6, // cuda_constant
838 7, // cuda_shared
839 8, // ptr32_sptr
840 9, // ptr32_uptr
841 10 // ptr64
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000842 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000843 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000844 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000845 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000846 }
847}
848
David Tweed31d09b02013-09-13 12:04:22 +0000849static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
850 const LangOptions &LangOpts) {
851 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000852 case LangOptions::ASMM_Target:
853 return TI.useAddressSpaceMapMangling();
854 case LangOptions::ASMM_On:
855 return true;
856 case LangOptions::ASMM_Off:
857 return false;
858 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000859 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000860}
861
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000862ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000863 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000864 Builtin::Context &builtins)
Richard Smith772e2662019-10-04 01:25:59 +0000865 : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()),
866 TemplateSpecializationTypes(this_()),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000867 DependentTemplateSpecializationTypes(this_()),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000868 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
Ilya Biryukovdf7ea712019-10-09 09:40:22 +0000869 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000870 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +0000871 LangOpts.XRayNeverInstrumentFiles,
872 LangOpts.XRayAttrListFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000873 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000874 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000875 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
876 CompCategories(this_()), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000877 TUDecl = TranslationUnitDecl::Create(*this);
Sam McCall814e7972018-11-14 10:33:30 +0000878 TraversalScope = {TUDecl};
Daniel Dunbar221fa942008-08-11 04:54:23 +0000879}
880
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000881ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000882 // Release the DenseMaps associated with DeclContext objects.
883 // FIXME: Is this the ideal solution?
884 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000885
Manuel Klimeka7328992013-06-03 13:51:33 +0000886 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000887 for (auto &Pair : Deallocations)
888 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000889
Ted Kremenek076baeb2010-06-08 23:00:58 +0000890 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000891 // because they can contain DenseMaps.
892 for (llvm::DenseMap<const ObjCContainerDecl*,
893 const ASTRecordLayout*>::iterator
894 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
895 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000896 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Douglas Gregor5b11d492010-07-25 17:53:33 +0000897 R->Destroy(*this);
898
Ted Kremenek076baeb2010-06-08 23:00:58 +0000899 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
900 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
901 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000902 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Ted Kremenek076baeb2010-06-08 23:00:58 +0000903 R->Destroy(*this);
904 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000905
Douglas Gregor561eceb2010-08-30 16:49:28 +0000906 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
907 AEnd = DeclAttrs.end();
908 A != AEnd; ++A)
909 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000910
Richard Smith423f46f2016-07-20 21:38:26 +0000911 for (const auto &Value : ModuleInitializers)
912 Value.second->~PerModuleInitializers();
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000913
914 for (APValue *Value : APValueCleanups)
915 Value->~APValue();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000916}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000917
Sam McCall814e7972018-11-14 10:33:30 +0000918class ASTContext::ParentMap {
919 /// Contains parents of a node.
920 using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
921
922 /// Maps from a node to its parents. This is used for nodes that have
923 /// pointer identity only, which are more common and we can save space by
924 /// only storing a unique pointer to them.
925 using ParentMapPointers = llvm::DenseMap<
926 const void *,
927 llvm::PointerUnion4<const Decl *, const Stmt *,
928 ast_type_traits::DynTypedNode *, ParentVector *>>;
929
930 /// Parent map for nodes without pointer identity. We store a full
931 /// DynTypedNode for all keys.
932 using ParentMapOtherNodes = llvm::DenseMap<
933 ast_type_traits::DynTypedNode,
934 llvm::PointerUnion4<const Decl *, const Stmt *,
935 ast_type_traits::DynTypedNode *, ParentVector *>>;
936
937 ParentMapPointers PointerParents;
938 ParentMapOtherNodes OtherParents;
939 class ASTVisitor;
940
941 static ast_type_traits::DynTypedNode
942 getSingleDynTypedNodeFromParentMap(ParentMapPointers::mapped_type U) {
943 if (const auto *D = U.dyn_cast<const Decl *>())
944 return ast_type_traits::DynTypedNode::create(*D);
945 if (const auto *S = U.dyn_cast<const Stmt *>())
946 return ast_type_traits::DynTypedNode::create(*S);
947 return *U.get<ast_type_traits::DynTypedNode *>();
948 }
949
950 template <typename NodeTy, typename MapTy>
951 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
952 const MapTy &Map) {
953 auto I = Map.find(Node);
954 if (I == Map.end()) {
955 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
956 }
957 if (const auto *V = I->second.template dyn_cast<ParentVector *>()) {
958 return llvm::makeArrayRef(*V);
959 }
960 return getSingleDynTypedNodeFromParentMap(I->second);
961 }
962
963public:
964 ParentMap(ASTContext &Ctx);
965 ~ParentMap() {
966 for (const auto &Entry : PointerParents) {
967 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
968 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
969 } else if (Entry.second.is<ParentVector *>()) {
970 delete Entry.second.get<ParentVector *>();
971 }
972 }
973 for (const auto &Entry : OtherParents) {
974 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
975 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
976 } else if (Entry.second.is<ParentVector *>()) {
977 delete Entry.second.get<ParentVector *>();
978 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000979 }
980 }
Sam McCall814e7972018-11-14 10:33:30 +0000981
982 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node) {
983 if (Node.getNodeKind().hasPointerIdentity())
984 return getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
985 return getDynNodeFromMap(Node, OtherParents);
Manuel Klimek95403e62014-05-21 13:28:59 +0000986 }
Sam McCall814e7972018-11-14 10:33:30 +0000987};
988
989void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
990 TraversalScope = TopLevelDecls;
Stephen Kelly0a717d52019-05-12 21:09:32 +0100991 Parents.clear();
Manuel Klimek95403e62014-05-21 13:28:59 +0000992}
993
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000994void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000995 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000996}
997
Mike Stump11289f42009-09-09 15:08:12 +0000998void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000999ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001000 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001001}
1002
Chris Lattner4eb445d2007-01-26 01:27:23 +00001003void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +00001004 llvm::errs() << "\n*** AST Context Stats:\n";
1005 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001006
Douglas Gregora30d0462009-05-26 14:40:08 +00001007 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +00001008#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +00001009#define ABSTRACT_TYPE(Name, Parent)
John McCall36b12a82019-10-02 06:35:23 +00001010#include "clang/AST/TypeNodes.inc"
Douglas Gregora30d0462009-05-26 14:40:08 +00001011 0 // Extra
1012 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +00001013
Chris Lattner4eb445d2007-01-26 01:27:23 +00001014 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1015 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +00001016 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +00001017 }
1018
Douglas Gregora30d0462009-05-26 14:40:08 +00001019 unsigned Idx = 0;
1020 unsigned TotalBytes = 0;
1021#define TYPE(Name, Parent) \
1022 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +00001023 llvm::errs() << " " << counts[Idx] << " " << #Name \
Bruno Ricci58e03222018-08-06 15:17:32 +00001024 << " types, " << sizeof(Name##Type) << " each " \
1025 << "(" << counts[Idx] * sizeof(Name##Type) \
1026 << " bytes)\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +00001027 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1028 ++Idx;
1029#define ABSTRACT_TYPE(Name, Parent)
John McCall36b12a82019-10-02 06:35:23 +00001030#include "clang/AST/TypeNodes.inc"
Mike Stump11289f42009-09-09 15:08:12 +00001031
Chandler Carruth3c147a72011-07-04 05:32:14 +00001032 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1033
Douglas Gregor7454c562010-07-02 20:37:36 +00001034 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +00001035 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1036 << NumImplicitDefaultConstructors
1037 << " implicit default constructors created\n";
1038 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1039 << NumImplicitCopyConstructors
1040 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +00001041 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +00001042 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1043 << NumImplicitMoveConstructors
1044 << " implicit move constructors created\n";
1045 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1046 << NumImplicitCopyAssignmentOperators
1047 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +00001048 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +00001049 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1050 << NumImplicitMoveAssignmentOperators
1051 << " implicit move assignment operators created\n";
1052 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1053 << NumImplicitDestructors
1054 << " implicit destructors created\n";
1055
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +00001056 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +00001057 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001058 ExternalSource->PrintStats();
1059 }
Chandler Carruth3c147a72011-07-04 05:32:14 +00001060
Douglas Gregor5b11d492010-07-25 17:53:33 +00001061 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +00001062}
1063
Richard Smith42413142015-05-15 20:05:43 +00001064void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1065 bool NotifyListeners) {
1066 if (NotifyListeners)
1067 if (auto *Listener = getASTMutationListener())
1068 Listener->RedefinedHiddenDefinition(ND, M);
1069
Richard Smith13897eb2018-09-12 23:37:00 +00001070 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
Richard Smith42413142015-05-15 20:05:43 +00001071}
1072
1073void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
Richard Smith20fbdb32018-09-12 02:13:46 +00001074 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
Richard Smith42413142015-05-15 20:05:43 +00001075 if (It == MergedDefModules.end())
1076 return;
1077
Benjamin Kramera72a70a2016-10-17 13:00:44 +00001078 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +00001079 llvm::DenseSet<Module*> Found;
1080 for (Module *&M : Merged)
1081 if (!Found.insert(M).second)
1082 M = nullptr;
1083 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1084}
1085
Richard Smithdc1f0422016-07-20 19:10:16 +00001086void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1087 if (LazyInitializers.empty())
1088 return;
1089
1090 auto *Source = Ctx.getExternalSource();
1091 assert(Source && "lazy initializers but no external source");
1092
1093 auto LazyInits = std::move(LazyInitializers);
1094 LazyInitializers.clear();
1095
1096 for (auto ID : LazyInits)
1097 Initializers.push_back(Source->GetExternalDecl(ID));
1098
1099 assert(LazyInitializers.empty() &&
1100 "GetExternalDecl for lazy module initializer added more inits");
1101}
1102
1103void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1104 // One special case: if we add a module initializer that imports another
1105 // module, and that module's only initializer is an ImportDecl, simplify.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001106 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001107 auto It = ModuleInitializers.find(ID->getImportedModule());
1108
1109 // Maybe the ImportDecl does nothing at all. (Common case.)
1110 if (It == ModuleInitializers.end())
1111 return;
1112
1113 // Maybe the ImportDecl only imports another ImportDecl.
1114 auto &Imported = *It->second;
1115 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1116 Imported.resolve(*this);
1117 auto *OnlyDecl = Imported.Initializers.front();
1118 if (isa<ImportDecl>(OnlyDecl))
1119 D = OnlyDecl;
1120 }
1121 }
1122
1123 auto *&Inits = ModuleInitializers[M];
1124 if (!Inits)
1125 Inits = new (*this) PerModuleInitializers;
1126 Inits->Initializers.push_back(D);
1127}
1128
1129void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1130 auto *&Inits = ModuleInitializers[M];
1131 if (!Inits)
1132 Inits = new (*this) PerModuleInitializers;
1133 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1134 IDs.begin(), IDs.end());
1135}
1136
Eugene Zelenko7855e772018-04-03 00:11:50 +00001137ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001138 auto It = ModuleInitializers.find(M);
Fangrui Song6907ce22018-07-30 19:24:48 +00001139 if (It == ModuleInitializers.end())
Richard Smithdc1f0422016-07-20 19:10:16 +00001140 return None;
1141
1142 auto *Inits = It->second;
1143 Inits->resolve(*this);
1144 return Inits->Initializers;
1145}
1146
Richard Smithf19e1272015-03-07 00:04:49 +00001147ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1148 if (!ExternCContext)
1149 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1150
1151 return ExternCContext;
1152}
1153
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001154BuiltinTemplateDecl *
1155ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1156 const IdentifierInfo *II) const {
1157 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1158 BuiltinTemplate->setImplicit();
1159 TUDecl->addDecl(BuiltinTemplate);
1160
1161 return BuiltinTemplate;
1162}
1163
1164BuiltinTemplateDecl *
1165ASTContext::getMakeIntegerSeqDecl() const {
1166 if (!MakeIntegerSeqDecl)
1167 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1168 getMakeIntegerSeqName());
1169 return MakeIntegerSeqDecl;
1170}
1171
Eric Fiselier6ad68552016-07-01 01:24:09 +00001172BuiltinTemplateDecl *
1173ASTContext::getTypePackElementDecl() const {
1174 if (!TypePackElementDecl)
1175 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1176 getTypePackElementName());
1177 return TypePackElementDecl;
1178}
1179
Alp Toker2dea15b2013-12-17 01:22:38 +00001180RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1181 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001182 SourceLocation Loc;
1183 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001184 if (getLangOpts().CPlusPlus)
1185 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1186 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001187 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001188 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1189 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001190 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001191 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1192 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001193 return NewDecl;
1194}
1195
1196TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1197 StringRef Name) const {
1198 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1199 TypedefDecl *NewDecl = TypedefDecl::Create(
1200 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1201 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1202 NewDecl->setImplicit();
1203 return NewDecl;
1204}
1205
Douglas Gregor801c99d2011-08-12 06:49:56 +00001206TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001207 if (!Int128Decl)
1208 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001209 return Int128Decl;
1210}
1211
1212TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001213 if (!UInt128Decl)
1214 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001215 return UInt128Decl;
1216}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001217
John McCall48f2d582009-10-23 23:03:21 +00001218void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001219 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001220 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001221 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001222}
1223
Artem Belevichb5bc9232015-09-22 17:23:22 +00001224void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1225 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001226 assert((!this->Target || this->Target == &Target) &&
1227 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001228 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001229
Douglas Gregore8bbc122011-09-02 00:18:52 +00001230 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001231 this->AuxTarget = AuxTarget;
1232
Douglas Gregore8bbc122011-09-02 00:18:52 +00001233 ABI.reset(createCXXABI(Target));
1234 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001235 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Fangrui Song6907ce22018-07-30 19:24:48 +00001236
Chris Lattner970e54e2006-11-12 00:37:36 +00001237 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001238 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001239
Chris Lattner970e54e2006-11-12 00:37:36 +00001240 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001241 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001242 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001243 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001244 InitBuiltinType(CharTy, BuiltinType::Char_S);
1245 else
1246 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001247 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001248 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1249 InitBuiltinType(ShortTy, BuiltinType::Short);
1250 InitBuiltinType(IntTy, BuiltinType::Int);
1251 InitBuiltinType(LongTy, BuiltinType::Long);
1252 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001253
Chris Lattner970e54e2006-11-12 00:37:36 +00001254 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001255 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1256 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1257 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1258 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1259 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001260
Chris Lattner970e54e2006-11-12 00:37:36 +00001261 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001262 InitBuiltinType(FloatTy, BuiltinType::Float);
1263 InitBuiltinType(DoubleTy, BuiltinType::Double);
1264 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001265
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001266 // GNU extension, __float128 for IEEE quadruple precision
1267 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1268
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001269 // C11 extension ISO/IEC TS 18661-3
1270 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1271
Leonard Chanf921d852018-06-04 16:07:52 +00001272 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
Leonard Chanab80f3c2018-06-14 14:53:51 +00001273 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1274 InitBuiltinType(AccumTy, BuiltinType::Accum);
1275 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1276 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1277 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1278 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1279 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1280 InitBuiltinType(FractTy, BuiltinType::Fract);
1281 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1282 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1283 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1284 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1285 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1286 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1287 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1288 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1289 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1290 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1291 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1292 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1293 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1294 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1295 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1296 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
Leonard Chanf921d852018-06-04 16:07:52 +00001297
Chris Lattnerf122cef2009-04-30 02:43:43 +00001298 // GNU extension, 128-bit integers.
1299 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1300 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1301
Hans Wennborg0d81e012013-05-10 10:08:40 +00001302 // C++ 3.9.1p5
1303 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1304 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1305 else // -fshort-wchar makes wchar_t be unsigned.
1306 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1307 if (LangOpts.CPlusPlus && LangOpts.WChar)
1308 WideCharTy = WCharTy;
1309 else {
1310 // C99 (or C++ using -fno-wchar).
1311 WideCharTy = getFromTargetType(Target.getWCharType());
1312 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001313
James Molloy36365542012-05-04 10:55:22 +00001314 WIntTy = getFromTargetType(Target.getWIntType());
1315
Richard Smith3a8244d2018-05-01 05:02:45 +00001316 // C++20 (proposed)
1317 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1318
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001319 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1320 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1321 else // C99
1322 Char16Ty = getFromTargetType(Target.getChar16Type());
1323
1324 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1325 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1326 else // C99
1327 Char32Ty = getFromTargetType(Target.getChar32Type());
1328
Douglas Gregor4619e432008-12-05 23:32:09 +00001329 // Placeholder type for type-dependent expressions whose type is
1330 // completely unknown. No code should ever check a type against
1331 // DependentTy and users should never see it; however, it is here to
1332 // help diagnose failures to properly check for type-dependent
1333 // expressions.
1334 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001335
John McCall36e7fe32010-10-12 00:20:44 +00001336 // Placeholder type for functions.
1337 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1338
John McCall0009fcc2011-04-26 20:42:42 +00001339 // Placeholder type for bound members.
1340 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1341
John McCall526ab472011-10-25 17:37:35 +00001342 // Placeholder type for pseudo-objects.
1343 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1344
John McCall31996342011-04-07 08:22:57 +00001345 // "any" type; useful for debugger-like clients.
1346 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1347
John McCall8a6b59a2011-10-17 18:09:15 +00001348 // Placeholder type for unbridged ARC casts.
1349 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1350
Eli Friedman34866c72012-08-31 00:14:07 +00001351 // Placeholder type for builtin functions.
1352 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1353
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001354 // Placeholder type for OMP array sections.
1355 if (LangOpts.OpenMP)
1356 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1357
Chris Lattner970e54e2006-11-12 00:37:36 +00001358 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001359 FloatComplexTy = getComplexType(FloatTy);
1360 DoubleComplexTy = getComplexType(DoubleTy);
1361 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001362 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001363
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001364 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001365 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1366 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001367 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001368
Alexey Bader954ba212016-04-08 13:40:33 +00001369 if (LangOpts.OpenCL) {
1370#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1371 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001372#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001373
Guy Benyei61054192013-02-07 10:55:47 +00001374 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001375 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001376 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1377 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001378 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001379
1380#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1381 InitBuiltinType(Id##Ty, BuiltinType::Id);
1382#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001383 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001384
Richard Sandifordeb485fb2019-08-09 08:52:54 +00001385 if (Target.hasAArch64SVETypes()) {
1386#define SVE_TYPE(Name, Id, SingletonId) \
1387 InitBuiltinType(SingletonId, BuiltinType::Id);
1388#include "clang/Basic/AArch64SVEACLETypes.def"
1389 }
1390
Ted Kremeneke65b0862012-03-06 20:05:56 +00001391 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001392 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1393 SignedCharTy : BoolTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001394
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001395 ObjCConstantStringType = QualType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001396
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001397 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001398
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001399 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001400 if (LangOpts.OpenCLVersion >= 200) {
1401 auto Q = VoidTy.getQualifiers();
1402 Q.setAddressSpace(LangAS::opencl_generic);
1403 VoidPtrTy = getPointerType(getCanonicalType(
1404 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1405 } else {
1406 VoidPtrTy = getPointerType(VoidTy);
1407 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001408
1409 // nullptr type (C++0x 2.14.7)
1410 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001411
1412 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1413 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001414
1415 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001416 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001417}
1418
David Blaikie9c902b52011-09-25 23:23:43 +00001419DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001420 return SourceMgr.getDiagnostics();
1421}
1422
Douglas Gregor561eceb2010-08-30 16:49:28 +00001423AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1424 AttrVec *&Result = DeclAttrs[D];
1425 if (!Result) {
1426 void *Mem = Allocate(sizeof(AttrVec));
1427 Result = new (Mem) AttrVec;
1428 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001429
Douglas Gregor561eceb2010-08-30 16:49:28 +00001430 return *Result;
1431}
1432
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001433/// Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001434void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001435 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1436 if (Pos != DeclAttrs.end()) {
1437 Pos->second->~AttrVec();
1438 DeclAttrs.erase(Pos);
1439 }
1440}
1441
Larisse Voufo39a1e502013-08-06 01:03:05 +00001442// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001443MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001444ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001445 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001446 return getTemplateOrSpecializationInfo(Var)
1447 .dyn_cast<MemberSpecializationInfo *>();
1448}
1449
1450ASTContext::TemplateOrSpecializationInfo
1451ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1452 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1453 TemplateOrInstantiation.find(Var);
1454 if (Pos == TemplateOrInstantiation.end())
Eugene Zelenko7855e772018-04-03 00:11:50 +00001455 return {};
Mike Stump11289f42009-09-09 15:08:12 +00001456
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001457 return Pos->second;
1458}
1459
Mike Stump11289f42009-09-09 15:08:12 +00001460void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001461ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001462 TemplateSpecializationKind TSK,
1463 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001464 assert(Inst->isStaticDataMember() && "Not a static data member");
1465 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001466 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1467 Tmpl, TSK, PointOfInstantiation));
1468}
1469
1470void
1471ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1472 TemplateOrSpecializationInfo TSI) {
1473 assert(!TemplateOrInstantiation[Inst] &&
1474 "Already noted what the variable was instantiated from");
1475 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001476}
1477
John McCalle61f2ba2009-11-18 02:36:19 +00001478NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001479ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1480 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001481 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001482 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001483
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001484 return Pos->second;
1485}
1486
1487void
Richard Smithd8a9e372016-12-18 21:39:37 +00001488ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001489 assert((isa<UsingDecl>(Pattern) ||
1490 isa<UnresolvedUsingValueDecl>(Pattern) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001491 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
John McCallb96ec562009-12-04 22:46:56 +00001492 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001493 assert((isa<UsingDecl>(Inst) ||
1494 isa<UnresolvedUsingValueDecl>(Inst) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001495 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
Richard Smithd8a9e372016-12-18 21:39:37 +00001496 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001497 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1498 InstantiatedFromUsingDecl[Inst] = Pattern;
1499}
1500
1501UsingShadowDecl *
1502ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1503 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1504 = InstantiatedFromUsingShadowDecl.find(Inst);
1505 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001506 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001507
1508 return Pos->second;
1509}
1510
1511void
1512ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1513 UsingShadowDecl *Pattern) {
1514 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1515 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001516}
1517
Anders Carlsson5da84842009-09-01 04:26:58 +00001518FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1519 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1520 = InstantiatedFromUnnamedFieldDecl.find(Field);
1521 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001522 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001523
Anders Carlsson5da84842009-09-01 04:26:58 +00001524 return Pos->second;
1525}
1526
1527void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1528 FieldDecl *Tmpl) {
1529 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1530 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1531 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1532 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001533
Anders Carlsson5da84842009-09-01 04:26:58 +00001534 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1535}
1536
Douglas Gregor832940b2010-03-02 23:58:15 +00001537ASTContext::overridden_cxx_method_iterator
1538ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001539 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001540}
1541
1542ASTContext::overridden_cxx_method_iterator
1543ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001544 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001545}
1546
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001547unsigned
1548ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001549 auto Range = overridden_methods(Method);
1550 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001551}
1552
Clement Courbet6ecaec82016-07-05 07:49:31 +00001553ASTContext::overridden_method_range
1554ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001555 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1556 OverriddenMethods.find(Method->getCanonicalDecl());
1557 if (Pos == OverriddenMethods.end())
1558 return overridden_method_range(nullptr, nullptr);
1559 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001560}
1561
Fangrui Song6907ce22018-07-30 19:24:48 +00001562void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
Douglas Gregor832940b2010-03-02 23:58:15 +00001563 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001564 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001565 OverriddenMethods[Method].push_back(Overridden);
1566}
1567
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001568void ASTContext::getOverriddenMethods(
1569 const NamedDecl *D,
1570 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001571 assert(D);
1572
Eugene Zelenko7855e772018-04-03 00:11:50 +00001573 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001574 Overridden.append(overridden_methods_begin(CXXMethod),
1575 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001576 return;
1577 }
1578
Eugene Zelenko7855e772018-04-03 00:11:50 +00001579 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001580 if (!Method)
1581 return;
1582
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001583 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1584 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001585 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001586}
1587
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001588void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1589 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1590 assert(!Import->isFromASTFile() && "Non-local import declaration");
1591 if (!FirstLocalImport) {
1592 FirstLocalImport = Import;
1593 LastLocalImport = Import;
1594 return;
1595 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001596
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001597 LastLocalImport->NextLocalImport = Import;
1598 LastLocalImport = Import;
1599}
1600
Chris Lattner53cfe802007-07-18 17:52:12 +00001601//===----------------------------------------------------------------------===//
1602// Type Sizing and Analysis
1603//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001604
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001605/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1606/// scalar floating point type.
1607const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
Simon Pilgrim9588ae72019-10-03 21:47:42 +00001608 switch (T->castAs<BuiltinType>()->getKind()) {
1609 default:
1610 llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001611 case BuiltinType::Float16:
1612 case BuiltinType::Half:
1613 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001614 case BuiltinType::Float: return Target->getFloatFormat();
1615 case BuiltinType::Double: return Target->getDoubleFormat();
Alexey Bataeve509af32019-07-09 14:09:53 +00001616 case BuiltinType::LongDouble:
Fangrui Song3fbd8fd2019-07-09 19:36:22 +00001617 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
Alexey Bataeve509af32019-07-09 14:09:53 +00001618 return AuxTarget->getLongDoubleFormat();
1619 return Target->getLongDoubleFormat();
1620 case BuiltinType::Float128:
Fangrui Song3fbd8fd2019-07-09 19:36:22 +00001621 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
Alexey Bataeve509af32019-07-09 14:09:53 +00001622 return AuxTarget->getFloat128Format();
1623 return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001624 }
1625}
1626
Rafael Espindola71eccb32013-08-08 19:53:46 +00001627CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001628 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001629
John McCall94268702010-10-08 18:24:19 +00001630 bool UseAlignAttrOnly = false;
1631 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1632 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001633
John McCall94268702010-10-08 18:24:19 +00001634 // __attribute__((aligned)) can increase or decrease alignment
1635 // *except* on a struct or struct member, where it only increases
1636 // alignment unless 'packed' is also specified.
1637 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001638 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001639 // ignore that possibility; Sema should diagnose it.
1640 if (isa<FieldDecl>(D)) {
1641 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1642 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1643 } else {
1644 UseAlignAttrOnly = true;
1645 }
1646 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001647 else if (isa<FieldDecl>(D))
Fangrui Song6907ce22018-07-30 19:24:48 +00001648 UseAlignAttrOnly =
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001649 D->hasAttr<PackedAttr>() ||
1650 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001651
John McCall4e819612011-01-20 07:57:12 +00001652 // If we're using the align attribute only, just ignore everything
1653 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001654 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001655 // do nothing
Eugene Zelenko7855e772018-04-03 00:11:50 +00001656 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001657 QualType T = VD->getType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001658 if (const auto *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001659 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001660 T = RT->getPointeeType();
1661 else
1662 T = getPointerType(RT->getPointeeType());
1663 }
Richard Smithf6d70302014-06-10 23:34:28 +00001664 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001665 if (T->isFunctionType())
1666 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1667 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001668 // Adjust alignments of declarations with array type by the
1669 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001670 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001671 unsigned MinWidth = Target->getLargeArrayMinWidth();
1672 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001673 if (isa<VariableArrayType>(arrayType))
1674 Align = std::max(Align, Target->getLargeArrayAlign());
1675 else if (isa<ConstantArrayType>(arrayType) &&
1676 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1677 Align = std::max(Align, Target->getLargeArrayAlign());
1678 }
John McCall33ddac02011-01-19 10:06:00 +00001679 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001680 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001681 if (BaseT.getQualifiers().hasUnaligned())
1682 Align = Target->getCharWidth();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001683 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Tom Tanb7c6d952019-05-02 00:38:14 +00001684 if (VD->hasGlobalStorage() && !ForAlignof) {
1685 uint64_t TypeSize = getTypeSize(T.getTypePtr());
1686 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1687 }
Ulrich Weigandfa806422013-05-06 16:23:57 +00001688 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001689 }
John McCall4e819612011-01-20 07:57:12 +00001690
1691 // Fields can be subject to extra alignment constraints, like if
1692 // the field is packed, the struct is packed, or the struct has a
1693 // a max-field-alignment constraint (#pragma pack). So calculate
1694 // the actual alignment of the field within the struct, and then
1695 // (as we're expected to) constrain that by the alignment of the type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001696 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001697 const RecordDecl *Parent = Field->getParent();
1698 // We can only produce a sensible answer if the record is valid.
1699 if (!Parent->isInvalidDecl()) {
1700 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001701
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001702 // Start with the record's overall alignment.
1703 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001704
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001705 // Use the GCD of that and the offset within the record.
1706 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1707 if (Offset > 0) {
1708 // Alignment is always a power of 2, so the GCD will be a power of 2,
1709 // which means we get to do this crazy thing instead of Euclid's.
1710 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1711 if (LowBitOfOffset < FieldAlign)
1712 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1713 }
1714
1715 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001716 }
Charles Davis3fc51072010-02-23 04:52:00 +00001717 }
Chris Lattner68061312009-01-24 21:53:27 +00001718 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001719
Ken Dyckcc56c542011-01-15 18:38:59 +00001720 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001721}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001722
John McCallf1249922012-08-21 04:10:00 +00001723// getTypeInfoDataSizeInChars - Return the size of a type, in
1724// chars. If the type is a record, its data size is returned. This is
1725// the size of the memcpy that's performed when assigning this type
1726// using a trivial copy/move assignment operator.
1727std::pair<CharUnits, CharUnits>
1728ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1729 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1730
1731 // In C++, objects can sometimes be allocated into the tail padding
1732 // of a base-class subobject. We decide whether that's possible
1733 // during class layout, so here we can just trust the layout results.
1734 if (getLangOpts().CPlusPlus) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001735 if (const auto *RT = T->getAs<RecordType>()) {
John McCallf1249922012-08-21 04:10:00 +00001736 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1737 sizeAndAlign.first = layout.getDataSize();
1738 }
1739 }
1740
1741 return sizeAndAlign;
1742}
1743
Richard Trieu04d2d942013-05-14 21:59:17 +00001744/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1745/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1746std::pair<CharUnits, CharUnits>
1747static getConstantArrayInfoInChars(const ASTContext &Context,
1748 const ConstantArrayType *CAT) {
1749 std::pair<CharUnits, CharUnits> EltInfo =
1750 Context.getTypeInfoInChars(CAT->getElementType());
1751 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001752 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1753 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001754 "Overflow in array type char size evaluation");
1755 uint64_t Width = EltInfo.first.getQuantity() * Size;
1756 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001757 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1758 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001759 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001760 return std::make_pair(CharUnits::fromQuantity(Width),
1761 CharUnits::fromQuantity(Align));
1762}
1763
John McCall87fe5d52010-05-20 01:18:31 +00001764std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001765ASTContext::getTypeInfoInChars(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001766 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
Richard Trieu04d2d942013-05-14 21:59:17 +00001767 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001768 TypeInfo Info = getTypeInfo(T);
1769 return std::make_pair(toCharUnitsFromBits(Info.Width),
1770 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001771}
1772
1773std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001774ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001775 return getTypeInfoInChars(T.getTypePtr());
1776}
1777
David Majnemer34b57492014-07-30 01:30:47 +00001778bool ASTContext::isAlignmentRequired(const Type *T) const {
1779 return getTypeInfo(T).AlignIsRequired;
1780}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001781
David Majnemer34b57492014-07-30 01:30:47 +00001782bool ASTContext::isAlignmentRequired(QualType T) const {
1783 return isAlignmentRequired(T.getTypePtr());
1784}
1785
Richard Smithb2f0f052016-10-10 18:54:32 +00001786unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1787 // An alignment on a typedef overrides anything else.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001788 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001789 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1790 return Align;
1791
1792 // If we have an (array of) complete type, we're done.
1793 T = getBaseElementType(T);
1794 if (!T->isIncompleteType())
1795 return getTypeAlign(T);
1796
1797 // If we had an array type, its element type might be a typedef
1798 // type with an alignment attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001799 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001800 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1801 return Align;
1802
1803 // Otherwise, see if the declaration of the type had an attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001804 if (const auto *TT = T->getAs<TagType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001805 return TT->getDecl()->getMaxAlignment();
1806
1807 return 0;
1808}
1809
David Majnemer34b57492014-07-30 01:30:47 +00001810TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001811 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1812 if (I != MemoizedTypeInfo.end())
1813 return I->second;
1814
1815 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1816 TypeInfo TI = getTypeInfoImpl(T);
1817 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001818 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001819}
1820
1821/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1822/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001823///
1824/// FIXME: Pointers into different addr spaces could have different sizes and
1825/// alignment requirements: getPointerInfo should take an AddrSpace, this
1826/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001827TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1828 uint64_t Width = 0;
1829 unsigned Align = 8;
1830 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001831 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001832 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001833#define TYPE(Class, Base)
1834#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001835#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001836#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001837#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1838 case Type::Class: \
1839 assert(!T->isDependentType() && "should not see dependent types here"); \
1840 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
John McCall36b12a82019-10-02 06:35:23 +00001841#include "clang/AST/TypeNodes.inc"
John McCall15547bb2011-06-28 16:49:23 +00001842 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001843
Chris Lattner355332d2007-07-13 22:27:08 +00001844 case Type::FunctionNoProto:
1845 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001846 // GCC extension: alignof(function) = 32 bits
1847 Width = 0;
1848 Align = 32;
1849 break;
1850
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001851 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001852 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001853 Width = 0;
1854 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1855 break;
1856
Steve Naroff5c131802007-08-30 01:06:46 +00001857 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001858 const auto *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001859
David Majnemer34b57492014-07-30 01:30:47 +00001860 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001861 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001862 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001863 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001864 Width = EltInfo.Width * Size;
1865 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001866 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1867 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001868 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001869 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001870 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001871 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001872 case Type::Vector: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001873 const auto *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001874 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1875 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001876 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001877 // If the alignment is not a power of 2, round up to the next power of 2.
1878 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001879 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001880 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001881 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001882 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001883 // Adjust the alignment based on the target max.
1884 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1885 if (TargetVectorAlign && TargetVectorAlign < Align)
1886 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001887 break;
1888 }
Chris Lattner647fb222007-07-18 18:26:58 +00001889
Chris Lattner7570e9c2008-03-08 08:52:55 +00001890 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001891 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001892 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001893 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001894 // GCC extension: alignof(void) = 8 bits.
1895 Width = 0;
1896 Align = 8;
1897 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001898 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001899 Width = Target->getBoolWidth();
1900 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001901 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001902 case BuiltinType::Char_S:
1903 case BuiltinType::Char_U:
1904 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001905 case BuiltinType::SChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00001906 case BuiltinType::Char8:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001907 Width = Target->getCharWidth();
1908 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001909 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001910 case BuiltinType::WChar_S:
1911 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001912 Width = Target->getWCharWidth();
1913 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001914 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001915 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001916 Width = Target->getChar16Width();
1917 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001918 break;
1919 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001920 Width = Target->getChar32Width();
1921 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001922 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001923 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001924 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001925 Width = Target->getShortWidth();
1926 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001927 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001928 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001929 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001930 Width = Target->getIntWidth();
1931 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001932 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001933 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001934 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001935 Width = Target->getLongWidth();
1936 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001937 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001938 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001939 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001940 Width = Target->getLongLongWidth();
1941 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001942 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001943 case BuiltinType::Int128:
1944 case BuiltinType::UInt128:
1945 Width = 128;
1946 Align = 128; // int128_t is 128-bit aligned on all targets.
1947 break;
Leonard Chanf921d852018-06-04 16:07:52 +00001948 case BuiltinType::ShortAccum:
1949 case BuiltinType::UShortAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001950 case BuiltinType::SatShortAccum:
1951 case BuiltinType::SatUShortAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001952 Width = Target->getShortAccumWidth();
1953 Align = Target->getShortAccumAlign();
1954 break;
1955 case BuiltinType::Accum:
1956 case BuiltinType::UAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001957 case BuiltinType::SatAccum:
1958 case BuiltinType::SatUAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001959 Width = Target->getAccumWidth();
1960 Align = Target->getAccumAlign();
1961 break;
1962 case BuiltinType::LongAccum:
1963 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001964 case BuiltinType::SatLongAccum:
1965 case BuiltinType::SatULongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001966 Width = Target->getLongAccumWidth();
1967 Align = Target->getLongAccumAlign();
1968 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00001969 case BuiltinType::ShortFract:
1970 case BuiltinType::UShortFract:
1971 case BuiltinType::SatShortFract:
1972 case BuiltinType::SatUShortFract:
1973 Width = Target->getShortFractWidth();
1974 Align = Target->getShortFractAlign();
1975 break;
1976 case BuiltinType::Fract:
1977 case BuiltinType::UFract:
1978 case BuiltinType::SatFract:
1979 case BuiltinType::SatUFract:
1980 Width = Target->getFractWidth();
1981 Align = Target->getFractAlign();
1982 break;
1983 case BuiltinType::LongFract:
1984 case BuiltinType::ULongFract:
1985 case BuiltinType::SatLongFract:
1986 case BuiltinType::SatULongFract:
1987 Width = Target->getLongFractWidth();
1988 Align = Target->getLongFractAlign();
1989 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001990 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001991 case BuiltinType::Half:
Alexey Bataev123ad192019-02-27 20:29:45 +00001992 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
1993 !getLangOpts().OpenMPIsDevice) {
1994 Width = Target->getHalfWidth();
1995 Align = Target->getHalfAlign();
1996 } else {
1997 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1998 "Expected OpenMP device compilation.");
1999 Width = AuxTarget->getHalfWidth();
2000 Align = AuxTarget->getHalfAlign();
2001 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002002 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00002003 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00002004 Width = Target->getFloatWidth();
2005 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00002006 break;
2007 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00002008 Width = Target->getDoubleWidth();
2009 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00002010 break;
2011 case BuiltinType::LongDouble:
Alexey Bataev8557d1a2019-06-18 18:39:26 +00002012 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2013 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2014 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2015 Width = AuxTarget->getLongDoubleWidth();
2016 Align = AuxTarget->getLongDoubleAlign();
2017 } else {
2018 Width = Target->getLongDoubleWidth();
2019 Align = Target->getLongDoubleAlign();
2020 }
Chris Lattner6a4f7452007-12-19 19:23:28 +00002021 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002022 case BuiltinType::Float128:
Alexey Bataev123ad192019-02-27 20:29:45 +00002023 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2024 !getLangOpts().OpenMPIsDevice) {
2025 Width = Target->getFloat128Width();
2026 Align = Target->getFloat128Align();
2027 } else {
2028 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2029 "Expected OpenMP device compilation.");
2030 Width = AuxTarget->getFloat128Width();
2031 Align = AuxTarget->getFloat128Align();
2032 }
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002033 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002034 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00002035 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
2036 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00002037 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00002038 case BuiltinType::ObjCId:
2039 case BuiltinType::ObjCClass:
2040 case BuiltinType::ObjCSel:
Fangrui Song6907ce22018-07-30 19:24:48 +00002041 Width = Target->getPointerWidth(0);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002042 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00002043 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002044 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002045 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002046 case BuiltinType::OCLClkEvent:
2047 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002048 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00002049#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2050 case BuiltinType::Id:
2051#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00002052#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2053 case BuiltinType::Id:
2054#include "clang/Basic/OpenCLExtensionTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00002055 AS = getTargetAddressSpace(
2056 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002057 Width = Target->getPointerWidth(AS);
2058 Align = Target->getPointerAlign(AS);
2059 break;
Richard Sandifordeb485fb2019-08-09 08:52:54 +00002060 // The SVE types are effectively target-specific. The length of an
2061 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2062 // of 128 bits. There is one predicate bit for each vector byte, so the
2063 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2064 //
2065 // Because the length is only known at runtime, we use a dummy value
2066 // of 0 for the static length. The alignment values are those defined
2067 // by the Procedure Call Standard for the Arm Architecture.
2068#define SVE_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, IsSigned, IsFP)\
2069 case BuiltinType::Id: \
2070 Width = 0; \
2071 Align = 128; \
2072 break;
2073#define SVE_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2074 case BuiltinType::Id: \
2075 Width = 0; \
2076 Align = 16; \
2077 break;
2078#include "clang/Basic/AArch64SVEACLETypes.def"
Chris Lattner983a8bb2007-07-13 22:13:22 +00002079 }
Chris Lattner48f84b82007-07-15 23:46:53 +00002080 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00002081 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00002082 Width = Target->getPointerWidth(0);
2083 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00002084 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002085 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002086 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00002087 Width = Target->getPointerWidth(AS);
2088 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00002089 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002090 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002091 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002092 // alignof and sizeof should never enter this code path here, so we go
2093 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002094 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00002095 Width = Target->getPointerWidth(AS);
2096 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002097 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002098 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002099 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00002100 Width = Target->getPointerWidth(AS);
2101 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00002102 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002103 case Type::MemberPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002104 const auto *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00002105 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2106 Width = MPI.Width;
2107 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00002108 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002109 }
Chris Lattner647fb222007-07-18 18:26:58 +00002110 case Type::Complex: {
2111 // Complex types have the same alignment as their elements, but twice the
2112 // size.
David Majnemer34b57492014-07-30 01:30:47 +00002113 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2114 Width = EltInfo.Width * 2;
2115 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00002116 break;
2117 }
John McCall8b07ec22010-05-15 11:32:37 +00002118 case Type::ObjCObject:
2119 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00002120 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002121 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002122 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00002123 case Type::ObjCInterface: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002124 const auto *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00002125 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00002126 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002127 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00002128 break;
2129 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002130 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002131 case Type::Enum: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002132 const auto *TT = cast<TagType>(T);
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00002133
2134 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00002135 Width = 8;
2136 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00002137 break;
2138 }
Mike Stump11289f42009-09-09 15:08:12 +00002139
Eugene Zelenko7855e772018-04-03 00:11:50 +00002140 if (const auto *ET = dyn_cast<EnumType>(TT)) {
David Majnemer475b25e2015-01-21 10:54:38 +00002141 const EnumDecl *ED = ET->getDecl();
2142 TypeInfo Info =
2143 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2144 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2145 Info.Align = AttrAlign;
2146 Info.AlignIsRequired = true;
2147 }
2148 return Info;
2149 }
Chris Lattner8b23c252008-04-06 22:05:18 +00002150
Eugene Zelenko7855e772018-04-03 00:11:50 +00002151 const auto *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00002152 const RecordDecl *RD = RT->getDecl();
2153 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00002154 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002155 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00002156 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00002157 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00002158 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002159
Chris Lattner63d2b362009-10-22 05:17:15 +00002160 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00002161 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2162 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00002163
Richard Smith600b5262017-01-26 20:40:47 +00002164 case Type::Auto:
2165 case Type::DeducedTemplateSpecialization: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002166 const auto *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00002167 assert(!A->getDeducedType().isNull() &&
2168 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00002169 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00002170 }
2171
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002172 case Type::Paren:
2173 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2174
Leonard Chanc72aaf62019-05-07 03:20:17 +00002175 case Type::MacroQualified:
2176 return getTypeInfo(
2177 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2178
Manman Rene6be26c2016-09-13 17:25:08 +00002179 case Type::ObjCTypeParam:
2180 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2181
Douglas Gregoref462e62009-04-30 17:32:17 +00002182 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00002183 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00002184 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00002185 // If the typedef has an aligned attribute on it, it overrides any computed
2186 // alignment we have. This violates the GCC documentation (which says that
2187 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00002188 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00002189 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00002190 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00002191 } else {
David Majnemer34b57492014-07-30 01:30:47 +00002192 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00002193 AlignIsRequired = Info.AlignIsRequired;
2194 }
David Majnemer34b57492014-07-30 01:30:47 +00002195 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00002196 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00002197 }
Douglas Gregoref462e62009-04-30 17:32:17 +00002198
Abramo Bagnara6150c882010-05-11 21:36:43 +00002199 case Type::Elaborated:
2200 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00002201
John McCall81904512011-01-06 01:58:22 +00002202 case Type::Attributed:
2203 return getTypeInfo(
2204 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2205
Eli Friedman0dfb8892011-10-06 23:00:33 +00002206 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00002207 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00002208 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2209 Width = Info.Width;
2210 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00002211
JF Bastien801fca22018-05-09 03:51:12 +00002212 if (!Width) {
2213 // An otherwise zero-sized type should still generate an
2214 // atomic operation.
2215 Width = Target->getCharWidth();
2216 assert(Align);
2217 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2218 // If the size of the type doesn't exceed the platform's max
2219 // atomic promotion width, make the size and alignment more
2220 // favorable to atomic operations:
2221
John McCalla8ec7eb2013-03-07 21:37:17 +00002222 // Round the size up to a power of 2.
2223 if (!llvm::isPowerOf2_64(Width))
2224 Width = llvm::NextPowerOf2(Width);
2225
2226 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002227 Align = static_cast<unsigned>(Width);
2228 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00002229 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00002230 break;
2231
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002232 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00002233 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2234 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002235 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00002236 }
Mike Stump11289f42009-09-09 15:08:12 +00002237
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002238 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00002239 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00002240}
2241
Momchil Velikov20208cc2018-07-30 17:48:23 +00002242unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2243 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2244 if (I != MemoizedUnadjustedAlign.end())
2245 return I->second;
2246
2247 unsigned UnadjustedAlign;
2248 if (const auto *RT = T->getAs<RecordType>()) {
2249 const RecordDecl *RD = RT->getDecl();
2250 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2251 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2252 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2253 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2254 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2255 } else {
John Brawn6c49f582019-05-22 11:42:54 +00002256 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
Momchil Velikov20208cc2018-07-30 17:48:23 +00002257 }
2258
2259 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2260 return UnadjustedAlign;
2261}
2262
Alexey Bataev00396512015-07-02 03:40:19 +00002263unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2264 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2265 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2266 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2267 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2268 getTargetInfo().getABI() == "elfv1-qpx" &&
2269 T->isSpecificBuiltinType(BuiltinType::Double))
2270 SimdAlign = 256;
2271 return SimdAlign;
2272}
2273
Ken Dyckcc56c542011-01-15 18:38:59 +00002274/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2275CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2276 return CharUnits::fromQuantity(BitSize / getCharWidth());
2277}
2278
Ken Dyckb0fcc592011-02-11 01:54:29 +00002279/// toBits - Convert a size in characters to a size in characters.
2280int64_t ASTContext::toBits(CharUnits CharSize) const {
2281 return CharSize.getQuantity() * getCharWidth();
2282}
2283
Ken Dyck8c89d592009-12-22 14:23:30 +00002284/// getTypeSizeInChars - Return the size of the specified type, in characters.
2285/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002286CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002287 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002288}
Jay Foad39c79802011-01-12 09:06:06 +00002289CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002290 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002291}
2292
Fangrui Song6907ce22018-07-30 19:24:48 +00002293/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002294/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002295CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002296 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002297}
Jay Foad39c79802011-01-12 09:06:06 +00002298CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002299 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002300}
2301
Momchil Velikov20208cc2018-07-30 17:48:23 +00002302/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2303/// type, in characters, before alignment adustments. This method does
2304/// not work on incomplete types.
2305CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2306 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2307}
2308CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2309 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2310}
2311
Chris Lattnera3402cd2009-01-27 18:08:34 +00002312/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2313/// type for the current target in bits. This can be different than the ABI
2314/// alignment in cases where it is beneficial for performance to overalign
2315/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002316unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002317 TypeInfo TI = getTypeInfo(T);
2318 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002319
David Majnemere1544562015-04-24 01:25:05 +00002320 T = T->getBaseElementTypeUnsafe();
2321
2322 // The preferred alignment of member pointers is that of a pointer.
2323 if (T->isMemberPointerType())
2324 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2325
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002326 if (!Target->allowsLargerPreferedTypeAlignment())
2327 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002328
Eli Friedman7ab09572009-05-25 21:27:19 +00002329 // Double and long long should be naturally aligned if possible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002330 if (const auto *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002331 T = CT->getElementType().getTypePtr();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002332 if (const auto *ET = T->getAs<EnumType>())
David Majnemer475b25e2015-01-21 10:54:38 +00002333 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002334 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002335 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2336 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002337 // Don't increase the alignment if an alignment attribute was specified on a
2338 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002339 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002340 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002341
Chris Lattnera3402cd2009-01-27 18:08:34 +00002342 return ABIAlign;
2343}
2344
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002345/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2346/// for __attribute__((aligned)) on this target, to be used if no alignment
2347/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002348unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002349 return getTargetInfo().getDefaultAlignForAttributeAligned();
2350}
2351
Ulrich Weigandfa806422013-05-06 16:23:57 +00002352/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2353/// to a global variable of the specified type.
2354unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
Tom Tanb7c6d952019-05-02 00:38:14 +00002355 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2356 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
Ulrich Weigandfa806422013-05-06 16:23:57 +00002357}
2358
2359/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2360/// should be given to a global variable of the specified type.
2361CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2362 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2363}
2364
David Majnemer08ef2ba2015-06-23 20:34:18 +00002365CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2366 CharUnits Offset = CharUnits::Zero();
2367 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2368 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2369 Offset += Layout->getBaseClassOffset(Base);
2370 Layout = &getASTRecordLayout(Base);
2371 }
2372 return Offset;
2373}
2374
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002375/// DeepCollectObjCIvars -
2376/// This routine first collects all declared, but not synthesized, ivars in
2377/// super class and then collects all ivars, including those synthesized for
2378/// current class. This routine is used for implementation of current class
2379/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002380void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2381 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002382 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002383 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2384 DeepCollectObjCIvars(SuperClass, false, Ivars);
2385 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002386 for (const auto *I : OI->ivars())
2387 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002388 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002389 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Fangrui Song6907ce22018-07-30 19:24:48 +00002390 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002391 Iv= Iv->getNextIvar())
2392 Ivars.push_back(Iv);
2393 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002394}
2395
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002396/// CollectInheritedProtocols - Collect all protocols in current class and
2397/// those inherited by it.
2398void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002399 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002400 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002401 // We can use protocol_iterator here instead of
Fangrui Song6907ce22018-07-30 19:24:48 +00002402 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002403 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002404 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002405 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002406
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002407 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002408 for (const auto *Cat : OI->visible_categories())
2409 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002410
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002411 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2412 while (SD) {
2413 CollectInheritedProtocols(SD, Protocols);
2414 SD = SD->getSuperClass();
2415 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002416 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002417 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002418 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002419 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002420 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002421 // Insert the protocol.
2422 if (!Protocols.insert(
2423 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2424 return;
2425
2426 for (auto *Proto : OP->protocols())
2427 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002428 }
2429}
2430
Erich Keane8a6b7402017-11-30 16:37:02 +00002431static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2432 const RecordDecl *RD) {
2433 assert(RD->isUnion() && "Must be union type");
2434 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2435
2436 for (const auto *Field : RD->fields()) {
2437 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2438 return false;
2439 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2440 if (FieldSize != UnionSize)
2441 return false;
2442 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002443 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002444}
2445
Benjamin Kramer802e6252017-12-24 12:46:22 +00002446static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002447 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2448
2449 if (!RD->field_empty())
2450 return false;
2451
2452 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2453 return ClassDecl->isEmpty();
2454
2455 return true;
2456}
2457
2458static llvm::Optional<int64_t>
2459structHasUniqueObjectRepresentations(const ASTContext &Context,
2460 const RecordDecl *RD) {
2461 assert(!RD->isUnion() && "Must be struct/class type");
2462 const auto &Layout = Context.getASTRecordLayout(RD);
2463
2464 int64_t CurOffsetInBits = 0;
2465 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2466 if (ClassDecl->isDynamicClass())
2467 return llvm::None;
2468
2469 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
Mark de Wever29e78ec2019-12-15 21:17:07 +01002470 for (const auto &Base : ClassDecl->bases()) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002471 // Empty types can be inherited from, and non-empty types can potentially
2472 // have tail padding, so just make sure there isn't an error.
2473 if (!isStructEmpty(Base.getType())) {
2474 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
Simon Pilgrimeed4b122019-10-02 11:48:06 +00002475 Context, Base.getType()->castAs<RecordType>()->getDecl());
Erich Keane8a6b7402017-11-30 16:37:02 +00002476 if (!Size)
2477 return llvm::None;
2478 Bases.emplace_back(Base.getType(), Size.getValue());
2479 }
2480 }
2481
Fangrui Song1d38c132018-09-30 21:41:11 +00002482 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2483 const std::pair<QualType, int64_t> &R) {
2484 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2485 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2486 });
Erich Keane8a6b7402017-11-30 16:37:02 +00002487
Mark de Wever29e78ec2019-12-15 21:17:07 +01002488 for (const auto &Base : Bases) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002489 int64_t BaseOffset = Context.toBits(
2490 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2491 int64_t BaseSize = Base.second;
2492 if (BaseOffset != CurOffsetInBits)
2493 return llvm::None;
2494 CurOffsetInBits = BaseOffset + BaseSize;
2495 }
2496 }
2497
2498 for (const auto *Field : RD->fields()) {
2499 if (!Field->getType()->isReferenceType() &&
2500 !Context.hasUniqueObjectRepresentations(Field->getType()))
2501 return llvm::None;
2502
2503 int64_t FieldSizeInBits =
2504 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2505 if (Field->isBitField()) {
2506 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2507
2508 if (BitfieldSize > FieldSizeInBits)
2509 return llvm::None;
2510 FieldSizeInBits = BitfieldSize;
2511 }
2512
2513 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2514
2515 if (FieldOffsetInBits != CurOffsetInBits)
2516 return llvm::None;
2517
2518 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2519 }
2520
2521 return CurOffsetInBits;
2522}
2523
2524bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2525 // C++17 [meta.unary.prop]:
2526 // The predicate condition for a template specialization
2527 // has_unique_object_representations<T> shall be
2528 // satisfied if and only if:
2529 // (9.1) - T is trivially copyable, and
2530 // (9.2) - any two objects of type T with the same value have the same
2531 // object representation, where two objects
2532 // of array or non-union class type are considered to have the same value
2533 // if their respective sequences of
2534 // direct subobjects have the same values, and two objects of union type
2535 // are considered to have the same
2536 // value if they have the same active member and the corresponding members
2537 // have the same value.
2538 // The set of scalar types for which this condition holds is
2539 // implementation-defined. [ Note: If a type has padding
2540 // bits, the condition does not hold; otherwise, the condition holds true
2541 // for unsigned integral types. -- end note ]
2542 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2543
2544 // Arrays are unique only if their element type is unique.
2545 if (Ty->isArrayType())
2546 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2547
2548 // (9.1) - T is trivially copyable...
2549 if (!Ty.isTriviallyCopyableType(*this))
2550 return false;
2551
2552 // All integrals and enums are unique.
2553 if (Ty->isIntegralOrEnumerationType())
2554 return true;
2555
2556 // All other pointers are unique.
2557 if (Ty->isPointerType())
2558 return true;
2559
2560 if (Ty->isMemberPointerType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002561 const auto *MPT = Ty->getAs<MemberPointerType>();
Erich Keane8a6b7402017-11-30 16:37:02 +00002562 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2563 }
2564
2565 if (Ty->isRecordType()) {
Simon Pilgrimeed4b122019-10-02 11:48:06 +00002566 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
Erich Keane8a6b7402017-11-30 16:37:02 +00002567
Erich Keanebd2197c2017-12-12 16:02:06 +00002568 if (Record->isInvalidDecl())
2569 return false;
2570
Erich Keane8a6b7402017-11-30 16:37:02 +00002571 if (Record->isUnion())
2572 return unionHasUniqueObjectRepresentations(*this, Record);
2573
2574 Optional<int64_t> StructSize =
2575 structHasUniqueObjectRepresentations(*this, Record);
2576
2577 return StructSize &&
2578 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2579 }
2580
2581 // FIXME: More cases to handle here (list by rsmith):
2582 // vectors (careful about, eg, vector of 3 foo)
2583 // _Complex int and friends
2584 // _Atomic T
2585 // Obj-C block pointers
2586 // Obj-C object pointers
2587 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2588 // clk_event_t, queue_t, reserve_id_t)
2589 // There're also Obj-C class types and the Obj-C selector type, but I think it
2590 // makes sense for those to return false here.
2591
2592 return false;
2593}
2594
Jay Foad39c79802011-01-12 09:06:06 +00002595unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002596 unsigned count = 0;
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002597 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002598 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002599 count += Ext->ivar_size();
Fangrui Song6907ce22018-07-30 19:24:48 +00002600
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002601 // Count ivar defined in this class's implementation. This
2602 // includes synthesized ivars.
2603 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002604 count += ImplDecl->ivar_size();
2605
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002606 return count;
2607}
2608
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002609bool ASTContext::isSentinelNullExpr(const Expr *E) {
2610 if (!E)
2611 return false;
2612
2613 // nullptr_t is always treated as null.
2614 if (E->getType()->isNullPtrType()) return true;
2615
2616 if (E->getType()->isAnyPointerType() &&
2617 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2618 Expr::NPC_ValueDependentIsNull))
2619 return true;
2620
2621 // Unfortunately, __null has type 'int'.
2622 if (isa<GNUNullExpr>(E)) return true;
2623
2624 return false;
2625}
2626
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002627/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002628/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002629ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2630 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2631 I = ObjCImpls.find(D);
2632 if (I != ObjCImpls.end())
2633 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002634 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002635}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002636
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002637/// Get the implementation of ObjCCategoryDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002638/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002639ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2640 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2641 I = ObjCImpls.find(D);
2642 if (I != ObjCImpls.end())
2643 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002644 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002645}
2646
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002647/// Set the implementation of ObjCInterfaceDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002648void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2649 ObjCImplementationDecl *ImplD) {
2650 assert(IFaceD && ImplD && "Passed null params");
2651 ObjCImpls[IFaceD] = ImplD;
2652}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002653
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002654/// Set the implementation of ObjCCategoryDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002655void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2656 ObjCCategoryImplDecl *ImplD) {
2657 assert(CatD && ImplD && "Passed null params");
2658 ObjCImpls[CatD] = ImplD;
2659}
2660
Chandler Carruth21c90602015-12-30 03:24:14 +00002661const ObjCMethodDecl *
2662ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2663 return ObjCMethodRedecls.lookup(MD);
2664}
2665
2666void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2667 const ObjCMethodDecl *Redecl) {
2668 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2669 ObjCMethodRedecls[MD] = Redecl;
2670}
2671
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002672const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2673 const NamedDecl *ND) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002674 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002675 return ID;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002676 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002677 return CD->getClassInterface();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002678 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002679 return IMD->getClassInterface();
2680
Craig Topper36250ad2014-05-12 05:36:57 +00002681 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002682}
2683
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002684/// Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002685/// none exists.
Reid Kleckner60573ae2019-11-15 17:31:55 -08002686BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002687 assert(VD && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002688 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002689 "getBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002690 auto I = BlockVarCopyInits.find(VD);
2691 if (I != BlockVarCopyInits.end())
2692 return I->second;
2693 return {nullptr, false};
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002694}
2695
JF Bastien0d702a72019-04-30 00:11:53 +00002696/// Set the copy initialization expression of a block var decl.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002697void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2698 bool CanThrow) {
2699 assert(VD && CopyExpr && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002700 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002701 "setBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002702 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002703}
2704
John McCallbcd03502009-12-07 02:54:59 +00002705TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002706 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002707 if (!DataSize)
2708 DataSize = TypeLoc::getFullDataSizeForType(T);
2709 else
2710 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002711 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002712
Eugene Zelenko7855e772018-04-03 00:11:50 +00002713 auto *TInfo =
John McCallbcd03502009-12-07 02:54:59 +00002714 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2715 new (TInfo) TypeSourceInfo(T);
2716 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002717}
2718
John McCallbcd03502009-12-07 02:54:59 +00002719TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002720 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002721 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002722 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002723 return DI;
2724}
2725
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002726const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002727ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002728 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002729}
2730
2731const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002732ASTContext::getASTObjCImplementationLayout(
2733 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002734 return getObjCLayout(D->getClassInterface(), D);
2735}
2736
Chris Lattner983a8bb2007-07-13 22:13:22 +00002737//===----------------------------------------------------------------------===//
2738// Type creation/memoization methods
2739//===----------------------------------------------------------------------===//
2740
Jay Foad39c79802011-01-12 09:06:06 +00002741QualType
John McCall33ddac02011-01-19 10:06:00 +00002742ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2743 unsigned fastQuals = quals.getFastQualifiers();
2744 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002745
2746 // Check if we've already instantiated this type.
2747 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002748 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002749 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002750 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2751 assert(eq->getQualifiers() == quals);
2752 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002753 }
2754
John McCall33ddac02011-01-19 10:06:00 +00002755 // If the base type is not canonical, make the appropriate canonical type.
2756 QualType canon;
2757 if (!baseType->isCanonicalUnqualified()) {
2758 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002759 canonSplit.Quals.addConsistentQualifiers(quals);
2760 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002761
2762 // Re-find the insert position.
2763 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2764 }
2765
Eugene Zelenko7855e772018-04-03 00:11:50 +00002766 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
John McCall33ddac02011-01-19 10:06:00 +00002767 ExtQualNodes.InsertNode(eq, insertPos);
2768 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002769}
2770
Alexander Richardson6d989432017-10-15 18:48:14 +00002771QualType ASTContext::getAddrSpaceQualType(QualType T,
2772 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002773 QualType CanT = getCanonicalType(T);
2774 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002775 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002776
John McCall8ccfcb52009-09-24 19:53:00 +00002777 // If we are composing extended qualifiers together, merge together
2778 // into one ExtQuals node.
2779 QualifierCollector Quals;
2780 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002781
John McCall8ccfcb52009-09-24 19:53:00 +00002782 // If this type already has an address space specified, it cannot get
2783 // another one.
2784 assert(!Quals.hasAddressSpace() &&
2785 "Type cannot be in multiple addr spaces!");
2786 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002787
John McCall8ccfcb52009-09-24 19:53:00 +00002788 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002789}
2790
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002791QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2792 // If we are composing extended qualifiers together, merge together
2793 // into one ExtQuals node.
2794 QualifierCollector Quals;
2795 const Type *TypeNode = Quals.strip(T);
2796
2797 // If the qualifier doesn't have an address space just return it.
2798 if (!Quals.hasAddressSpace())
2799 return T;
2800
2801 Quals.removeAddressSpace();
2802
2803 // Removal of the address space can mean there are no longer any
2804 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2805 // or required.
2806 if (Quals.hasNonFastQualifiers())
2807 return getExtQualType(TypeNode, Quals);
2808 else
2809 return QualType(TypeNode, Quals.getFastQualifiers());
2810}
2811
Chris Lattnerd60183d2009-02-18 22:53:11 +00002812QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002813 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002814 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002815 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002816 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002817
Eugene Zelenko7855e772018-04-03 00:11:50 +00002818 if (const auto *ptr = T->getAs<PointerType>()) {
John McCall53fa7142010-12-24 02:08:15 +00002819 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002820 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002821 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2822 return getPointerType(ResultType);
2823 }
2824 }
Mike Stump11289f42009-09-09 15:08:12 +00002825
John McCall8ccfcb52009-09-24 19:53:00 +00002826 // If we are composing extended qualifiers together, merge together
2827 // into one ExtQuals node.
2828 QualifierCollector Quals;
2829 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002830
John McCall8ccfcb52009-09-24 19:53:00 +00002831 // If this type already has an ObjCGC specified, it cannot get
2832 // another one.
2833 assert(!Quals.hasObjCGCAttr() &&
2834 "Type cannot have multiple ObjCGCs!");
2835 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002836
John McCall8ccfcb52009-09-24 19:53:00 +00002837 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002838}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002839
Amy Huanga85f5ef2019-10-24 16:34:25 -07002840QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
2841 if (const PointerType *Ptr = T->getAs<PointerType>()) {
2842 QualType Pointee = Ptr->getPointeeType();
2843 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
2844 return getPointerType(removeAddrSpaceQualType(Pointee));
2845 }
2846 }
2847 return T;
2848}
2849
John McCall4f5019e2010-12-19 02:44:49 +00002850const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2851 FunctionType::ExtInfo Info) {
2852 if (T->getExtInfo() == Info)
2853 return T;
2854
2855 QualType Result;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002856 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002857 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002858 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002859 const auto *FPT = cast<FunctionProtoType>(T);
John McCall4f5019e2010-12-19 02:44:49 +00002860 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2861 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002862 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002863 }
2864
2865 return cast<FunctionType>(Result.getTypePtr());
2866}
2867
Richard Smith2a7d4812013-05-04 07:00:32 +00002868void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2869 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002870 FD = FD->getMostRecentDecl();
2871 while (true) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002872 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smith2a7d4812013-05-04 07:00:32 +00002873 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002874 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002875 if (FunctionDecl *Next = FD->getPreviousDecl())
2876 FD = Next;
2877 else
2878 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002879 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002880 if (ASTMutationListener *L = getASTMutationListener())
2881 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002882}
2883
Richard Smith0b3a4622014-11-13 20:01:57 +00002884/// Get a function type and produce the equivalent function type with the
2885/// specified exception specification. Type sugar that can be present on a
2886/// declaration of a function with an exception specification is permitted
2887/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002888QualType ASTContext::getFunctionTypeWithExceptionSpec(
2889 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002890 // Might have some parens.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002891 if (const auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002892 return getParenType(
2893 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002894
Leonard Chandc5d9752019-05-10 18:05:15 +00002895 // Might be wrapped in a macro qualified type.
2896 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
2897 return getMacroQualifiedType(
2898 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
2899 MQT->getMacroIdentifier());
2900
Richard Smith0b3a4622014-11-13 20:01:57 +00002901 // Might have a calling-convention attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002902 if (const auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002903 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002904 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002905 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2906 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002907
2908 // Anything else must be a function type. Rebuild it with the new exception
2909 // specification.
Simon Pilgrim9588ae72019-10-03 21:47:42 +00002910 const auto *Proto = Orig->castAs<FunctionProtoType>();
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002911 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002912 Proto->getReturnType(), Proto->getParamTypes(),
2913 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2914}
2915
Richard Smithdfe85e22016-12-15 02:35:39 +00002916bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2917 QualType U) {
2918 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002919 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002920 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2921 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002922}
2923
Amy Huanga85f5ef2019-10-24 16:34:25 -07002924QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
2925 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
2926 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
2927 SmallVector<QualType, 16> Args(Proto->param_types());
2928 for (unsigned i = 0, n = Args.size(); i != n; ++i)
2929 Args[i] = removePtrSizeAddrSpace(Args[i]);
2930 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
2931 }
2932
2933 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
2934 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
2935 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
2936 }
2937
2938 return T;
2939}
2940
2941bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
2942 return hasSameType(T, U) ||
2943 hasSameType(getFunctionTypeWithoutPtrSizes(T),
2944 getFunctionTypeWithoutPtrSizes(U));
2945}
2946
Richard Smith0b3a4622014-11-13 20:01:57 +00002947void ASTContext::adjustExceptionSpec(
2948 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2949 bool AsWritten) {
2950 // Update the type.
2951 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002952 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002953 FD->setType(Updated);
2954
2955 if (!AsWritten)
2956 return;
2957
2958 // Update the type in the type source information too.
2959 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2960 // If the type and the type-as-written differ, we may need to update
2961 // the type-as-written too.
2962 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002963 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002964
2965 // FIXME: When we get proper type location information for exceptions,
2966 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2967 // up the TypeSourceInfo;
2968 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2969 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2970 "TypeLoc size mismatch from updating exception specification");
2971 TSInfo->overrideType(Updated);
2972 }
2973}
2974
Chris Lattnerc6395932007-06-22 20:56:16 +00002975/// getComplexType - Return the uniqued reference to the type for a complex
2976/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002977QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002978 // Unique pointers, to guarantee there is only one pointer of a particular
2979 // structure.
2980 llvm::FoldingSetNodeID ID;
2981 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002982
Craig Topper36250ad2014-05-12 05:36:57 +00002983 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002984 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2985 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002986
Chris Lattnerc6395932007-06-22 20:56:16 +00002987 // If the pointee type isn't canonical, this won't be a canonical type either,
2988 // so fill in the canonical type field.
2989 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002990 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002991 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002992
Chris Lattnerc6395932007-06-22 20:56:16 +00002993 // Get the new insert position for the node we care about.
2994 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002995 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002996 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002997 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002998 Types.push_back(New);
2999 ComplexTypes.InsertNode(New, InsertPos);
3000 return QualType(New, 0);
3001}
3002
Chris Lattner970e54e2006-11-12 00:37:36 +00003003/// getPointerType - Return the uniqued reference to the type for a pointer to
3004/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00003005QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00003006 // Unique pointers, to guarantee there is only one pointer of a particular
3007 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003008 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00003009 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00003010
Craig Topper36250ad2014-05-12 05:36:57 +00003011 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00003012 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003013 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003014
Chris Lattner7ccecb92006-11-12 08:50:50 +00003015 // If the pointee type isn't canonical, this won't be a canonical type either,
3016 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003017 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00003018 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003019 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00003020
Bob Wilsonc8541f22013-03-15 17:12:43 +00003021 // Get the new insert position for the node we care about.
3022 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003023 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00003024 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003025 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00003026 Types.push_back(New);
3027 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003028 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00003029}
3030
Reid Kleckner0503a872013-12-05 01:23:43 +00003031QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
3032 llvm::FoldingSetNodeID ID;
3033 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00003034 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00003035 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3036 if (AT)
3037 return QualType(AT, 0);
3038
3039 QualType Canonical = getCanonicalType(New);
3040
3041 // Get the new insert position for the node we care about.
3042 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003043 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00003044
3045 AT = new (*this, TypeAlignment)
3046 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3047 Types.push_back(AT);
3048 AdjustedTypes.InsertNode(AT, InsertPos);
3049 return QualType(AT, 0);
3050}
3051
Reid Kleckner8a365022013-06-24 17:51:48 +00003052QualType ASTContext::getDecayedType(QualType T) const {
3053 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3054
Reid Kleckner8a365022013-06-24 17:51:48 +00003055 QualType Decayed;
3056
3057 // C99 6.7.5.3p7:
3058 // A declaration of a parameter as "array of type" shall be
3059 // adjusted to "qualified pointer to type", where the type
3060 // qualifiers (if any) are those specified within the [ and ] of
3061 // the array type derivation.
3062 if (T->isArrayType())
3063 Decayed = getArrayDecayedType(T);
3064
3065 // C99 6.7.5.3p8:
3066 // A declaration of a parameter as "function returning type"
3067 // shall be adjusted to "pointer to function returning type", as
3068 // in 6.3.2.1.
3069 if (T->isFunctionType())
3070 Decayed = getPointerType(T);
3071
Reid Kleckner0503a872013-12-05 01:23:43 +00003072 llvm::FoldingSetNodeID ID;
3073 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00003074 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00003075 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3076 if (AT)
3077 return QualType(AT, 0);
3078
Reid Kleckner8a365022013-06-24 17:51:48 +00003079 QualType Canonical = getCanonicalType(Decayed);
3080
3081 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00003082 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003083 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00003084
Reid Kleckner0503a872013-12-05 01:23:43 +00003085 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
3086 Types.push_back(AT);
3087 AdjustedTypes.InsertNode(AT, InsertPos);
3088 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00003089}
3090
Mike Stump11289f42009-09-09 15:08:12 +00003091/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00003092/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00003093QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00003094 assert(T->isFunctionType() && "block of function types only");
3095 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00003096 // structure.
3097 llvm::FoldingSetNodeID ID;
3098 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00003099
Craig Topper36250ad2014-05-12 05:36:57 +00003100 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00003101 if (BlockPointerType *PT =
3102 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3103 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003104
3105 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00003106 // type either so fill in the canonical type field.
3107 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003108 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00003109 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00003110
Steve Naroffec33ed92008-08-27 16:04:49 +00003111 // Get the new insert position for the node we care about.
3112 BlockPointerType *NewIP =
3113 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003114 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00003115 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003116 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00003117 Types.push_back(New);
3118 BlockPointerTypes.InsertNode(New, InsertPos);
3119 return QualType(New, 0);
3120}
3121
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003122/// getLValueReferenceType - Return the uniqued reference to the type for an
3123/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00003124QualType
3125ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003126 assert(getCanonicalType(T) != OverloadTy &&
Douglas Gregor291e8ee2011-05-21 22:16:50 +00003127 "Unresolved overloaded function type");
Fangrui Song6907ce22018-07-30 19:24:48 +00003128
Bill Wendling3708c182007-05-27 10:15:43 +00003129 // Unique pointers, to guarantee there is only one pointer of a particular
3130 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003131 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00003132 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00003133
Craig Topper36250ad2014-05-12 05:36:57 +00003134 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003135 if (LValueReferenceType *RT =
3136 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00003137 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003138
Eugene Zelenko7855e772018-04-03 00:11:50 +00003139 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003140
Bill Wendling3708c182007-05-27 10:15:43 +00003141 // If the referencee type isn't canonical, this won't be a canonical type
3142 // either, so fill in the canonical type field.
3143 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003144 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3145 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3146 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003147
Bill Wendling3708c182007-05-27 10:15:43 +00003148 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003149 LValueReferenceType *NewIP =
3150 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003151 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00003152 }
3153
Eugene Zelenko7855e772018-04-03 00:11:50 +00003154 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3155 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00003156 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003157 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00003158
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003159 return QualType(New, 0);
3160}
3161
3162/// getRValueReferenceType - Return the uniqued reference to the type for an
3163/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00003164QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003165 // Unique pointers, to guarantee there is only one pointer of a particular
3166 // structure.
3167 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00003168 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003169
Craig Topper36250ad2014-05-12 05:36:57 +00003170 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003171 if (RValueReferenceType *RT =
3172 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3173 return QualType(RT, 0);
3174
Eugene Zelenko7855e772018-04-03 00:11:50 +00003175 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003176
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003177 // If the referencee type isn't canonical, this won't be a canonical type
3178 // either, so fill in the canonical type field.
3179 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003180 if (InnerRef || !T.isCanonical()) {
3181 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3182 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003183
3184 // Get the new insert position for the node we care about.
3185 RValueReferenceType *NewIP =
3186 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003187 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003188 }
3189
Eugene Zelenko7855e772018-04-03 00:11:50 +00003190 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003191 Types.push_back(New);
3192 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00003193 return QualType(New, 0);
3194}
3195
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003196/// getMemberPointerType - Return the uniqued reference to the type for a
3197/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00003198QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003199 // Unique pointers, to guarantee there is only one pointer of a particular
3200 // structure.
3201 llvm::FoldingSetNodeID ID;
3202 MemberPointerType::Profile(ID, T, Cls);
3203
Craig Topper36250ad2014-05-12 05:36:57 +00003204 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003205 if (MemberPointerType *PT =
3206 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3207 return QualType(PT, 0);
3208
3209 // If the pointee or class type isn't canonical, this won't be a canonical
3210 // type either, so fill in the canonical type field.
3211 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00003212 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003213 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3214
3215 // Get the new insert position for the node we care about.
3216 MemberPointerType *NewIP =
3217 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003218 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003219 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003220 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003221 Types.push_back(New);
3222 MemberPointerTypes.InsertNode(New, InsertPos);
3223 return QualType(New, 0);
3224}
3225
Mike Stump11289f42009-09-09 15:08:12 +00003226/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00003227/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00003228QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00003229 const llvm::APInt &ArySizeIn,
Richard Smith772e2662019-10-04 01:25:59 +00003230 const Expr *SizeExpr,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003231 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003232 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00003233 assert((EltTy->isDependentType() ||
3234 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00003235 "Constant array of VLAs is illegal!");
3236
Richard Smith772e2662019-10-04 01:25:59 +00003237 // We only need the size as part of the type if it's instantiation-dependent.
3238 if (SizeExpr && !SizeExpr->isInstantiationDependent())
3239 SizeExpr = nullptr;
3240
Chris Lattnere2df3f92009-05-13 04:12:56 +00003241 // Convert the array size into a canonical width matching the pointer size for
3242 // the target.
3243 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00003244 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00003245
Chris Lattner23b7eb62007-06-15 23:05:46 +00003246 llvm::FoldingSetNodeID ID;
Richard Smith772e2662019-10-04 01:25:59 +00003247 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3248 IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00003249
Craig Topper36250ad2014-05-12 05:36:57 +00003250 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003251 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003252 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003253 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003254
Richard Smith772e2662019-10-04 01:25:59 +00003255 // If the element type isn't canonical or has qualifiers, or the array bound
3256 // is instantiation-dependent, this won't be a canonical type either, so fill
3257 // in the canonical type field.
John McCall33ddac02011-01-19 10:06:00 +00003258 QualType Canon;
Richard Smith772e2662019-10-04 01:25:59 +00003259 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
John McCall33ddac02011-01-19 10:06:00 +00003260 SplitQualType canonSplit = getCanonicalType(EltTy).split();
Richard Smith772e2662019-10-04 01:25:59 +00003261 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003262 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003263 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003264
Chris Lattner36f8e652007-01-27 08:31:04 +00003265 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00003266 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003267 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003268 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00003269 }
Mike Stump11289f42009-09-09 15:08:12 +00003270
Richard Smith772e2662019-10-04 01:25:59 +00003271 void *Mem = Allocate(
3272 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
3273 TypeAlignment);
3274 auto *New = new (Mem)
3275 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00003276 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00003277 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003278 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00003279}
3280
John McCall06549462011-01-18 08:40:38 +00003281/// getVariableArrayDecayedType - Turns the given type, which may be
3282/// variably-modified, into the corresponding type with all the known
3283/// sizes replaced with [*].
3284QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3285 // Vastly most common case.
3286 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003287
John McCall06549462011-01-18 08:40:38 +00003288 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003289
John McCall06549462011-01-18 08:40:38 +00003290 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003291 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00003292 switch (ty->getTypeClass()) {
3293#define TYPE(Class, Base)
3294#define ABSTRACT_TYPE(Class, Base)
3295#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
John McCall36b12a82019-10-02 06:35:23 +00003296#include "clang/AST/TypeNodes.inc"
John McCall06549462011-01-18 08:40:38 +00003297 llvm_unreachable("didn't desugar past all non-canonical types?");
3298
3299 // These types should never be variably-modified.
3300 case Type::Builtin:
3301 case Type::Complex:
3302 case Type::Vector:
Erich Keanef702b022018-07-13 19:46:04 +00003303 case Type::DependentVector:
John McCall06549462011-01-18 08:40:38 +00003304 case Type::ExtVector:
3305 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003306 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00003307 case Type::ObjCObject:
3308 case Type::ObjCInterface:
3309 case Type::ObjCObjectPointer:
3310 case Type::Record:
3311 case Type::Enum:
3312 case Type::UnresolvedUsing:
3313 case Type::TypeOfExpr:
3314 case Type::TypeOf:
3315 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00003316 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00003317 case Type::DependentName:
3318 case Type::InjectedClassName:
3319 case Type::TemplateSpecialization:
3320 case Type::DependentTemplateSpecialization:
3321 case Type::TemplateTypeParm:
3322 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00003323 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003324 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00003325 case Type::PackExpansion:
3326 llvm_unreachable("type should never be variably-modified");
3327
3328 // These types can be variably-modified but should never need to
3329 // further decay.
3330 case Type::FunctionNoProto:
3331 case Type::FunctionProto:
3332 case Type::BlockPointer:
3333 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00003334 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00003335 return type;
3336
3337 // These types can be variably-modified. All these modifications
3338 // preserve structure except as noted by comments.
3339 // TODO: if we ever care about optimizing VLAs, there are no-op
3340 // optimizations available here.
3341 case Type::Pointer:
3342 result = getPointerType(getVariableArrayDecayedType(
3343 cast<PointerType>(ty)->getPointeeType()));
3344 break;
3345
3346 case Type::LValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003347 const auto *lv = cast<LValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003348 result = getLValueReferenceType(
3349 getVariableArrayDecayedType(lv->getPointeeType()),
3350 lv->isSpelledAsLValue());
3351 break;
3352 }
3353
3354 case Type::RValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003355 const auto *lv = cast<RValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003356 result = getRValueReferenceType(
3357 getVariableArrayDecayedType(lv->getPointeeType()));
3358 break;
3359 }
3360
Eli Friedman0dfb8892011-10-06 23:00:33 +00003361 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003362 const auto *at = cast<AtomicType>(ty);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003363 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3364 break;
3365 }
3366
John McCall06549462011-01-18 08:40:38 +00003367 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003368 const auto *cat = cast<ConstantArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003369 result = getConstantArrayType(
3370 getVariableArrayDecayedType(cat->getElementType()),
3371 cat->getSize(),
Richard Smith772e2662019-10-04 01:25:59 +00003372 cat->getSizeExpr(),
John McCall06549462011-01-18 08:40:38 +00003373 cat->getSizeModifier(),
3374 cat->getIndexTypeCVRQualifiers());
3375 break;
3376 }
3377
3378 case Type::DependentSizedArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003379 const auto *dat = cast<DependentSizedArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003380 result = getDependentSizedArrayType(
3381 getVariableArrayDecayedType(dat->getElementType()),
3382 dat->getSizeExpr(),
3383 dat->getSizeModifier(),
3384 dat->getIndexTypeCVRQualifiers(),
3385 dat->getBracketsRange());
3386 break;
3387 }
3388
3389 // Turn incomplete types into [*] types.
3390 case Type::IncompleteArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003391 const auto *iat = cast<IncompleteArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003392 result = getVariableArrayType(
3393 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003394 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003395 ArrayType::Normal,
3396 iat->getIndexTypeCVRQualifiers(),
3397 SourceRange());
3398 break;
3399 }
3400
3401 // Turn VLA types into [*] types.
3402 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003403 const auto *vat = cast<VariableArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003404 result = getVariableArrayType(
3405 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003406 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003407 ArrayType::Star,
3408 vat->getIndexTypeCVRQualifiers(),
3409 vat->getBracketsRange());
3410 break;
3411 }
3412 }
3413
3414 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003415 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003416}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003417
Steve Naroffcadebd02007-08-30 18:14:25 +00003418/// getVariableArrayType - Returns a non-unique reference to the type for a
3419/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003420QualType ASTContext::getVariableArrayType(QualType EltTy,
3421 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003422 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003423 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003424 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003425 // Since we don't unique expressions, it isn't possible to unique VLA's
3426 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003427 QualType Canon;
Fangrui Song6907ce22018-07-30 19:24:48 +00003428
John McCall33ddac02011-01-19 10:06:00 +00003429 // Be sure to pull qualifiers off the element type.
3430 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3431 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003432 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003433 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003434 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003435 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003436
Eugene Zelenko7855e772018-04-03 00:11:50 +00003437 auto *New = new (*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003438 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003439
3440 VariableArrayTypes.push_back(New);
3441 Types.push_back(New);
3442 return QualType(New, 0);
3443}
3444
Douglas Gregor4619e432008-12-05 23:32:09 +00003445/// getDependentSizedArrayType - Returns a non-unique reference to
3446/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003447/// type.
John McCall33ddac02011-01-19 10:06:00 +00003448QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3449 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003450 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003451 unsigned elementTypeQuals,
3452 SourceRange brackets) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003453 assert((!numElements || numElements->isTypeDependent() ||
John McCall33ddac02011-01-19 10:06:00 +00003454 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003455 "Size must be type- or value-dependent!");
3456
John McCall33ddac02011-01-19 10:06:00 +00003457 // Dependently-sized array types that do not have a specified number
3458 // of elements will have their sizes deduced from a dependent
3459 // initializer. We do no canonicalization here at all, which is okay
3460 // because they can't be used in most locations.
3461 if (!numElements) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003462 auto *newType
John McCall33ddac02011-01-19 10:06:00 +00003463 = new (*this, TypeAlignment)
3464 DependentSizedArrayType(*this, elementType, QualType(),
3465 numElements, ASM, elementTypeQuals,
3466 brackets);
3467 Types.push_back(newType);
3468 return QualType(newType, 0);
3469 }
3470
3471 // Otherwise, we actually build a new type every time, but we
3472 // also build a canonical type.
3473
3474 SplitQualType canonElementType = getCanonicalType(elementType).split();
3475
Craig Topper36250ad2014-05-12 05:36:57 +00003476 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003477 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003478 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003479 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003480 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003481
John McCall33ddac02011-01-19 10:06:00 +00003482 // Look for an existing type with these properties.
3483 DependentSizedArrayType *canonTy =
3484 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003485
John McCall33ddac02011-01-19 10:06:00 +00003486 // If we don't have one, build one.
3487 if (!canonTy) {
3488 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003489 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003490 QualType(), numElements, ASM, elementTypeQuals,
3491 brackets);
3492 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3493 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003494 }
3495
John McCall33ddac02011-01-19 10:06:00 +00003496 // Apply qualifiers from the element type to the array.
3497 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003498 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003499
David Majnemer16a74702015-07-24 05:54:19 +00003500 // If we didn't need extra canonicalization for the element type or the size
3501 // expression, then just use that as our result.
3502 if (QualType(canonElementType.Ty, 0) == elementType &&
3503 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003504 return canon;
3505
3506 // Otherwise, we need to build a type which follows the spelling
3507 // of the element type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00003508 auto *sugaredType
John McCall33ddac02011-01-19 10:06:00 +00003509 = new (*this, TypeAlignment)
3510 DependentSizedArrayType(*this, elementType, canon, numElements,
3511 ASM, elementTypeQuals, brackets);
3512 Types.push_back(sugaredType);
3513 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003514}
3515
John McCall33ddac02011-01-19 10:06:00 +00003516QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003517 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003518 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003519 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003520 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003521
Craig Topper36250ad2014-05-12 05:36:57 +00003522 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003523 if (IncompleteArrayType *iat =
3524 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3525 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003526
3527 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003528 // either, so fill in the canonical type field. We also have to pull
3529 // qualifiers off the element type.
3530 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003531
John McCall33ddac02011-01-19 10:06:00 +00003532 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3533 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003534 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003535 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003536 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003537
3538 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003539 IncompleteArrayType *existing =
3540 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3541 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003542 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003543
Eugene Zelenko7855e772018-04-03 00:11:50 +00003544 auto *newType = new (*this, TypeAlignment)
John McCall33ddac02011-01-19 10:06:00 +00003545 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003546
John McCall33ddac02011-01-19 10:06:00 +00003547 IncompleteArrayTypes.InsertNode(newType, insertPos);
3548 Types.push_back(newType);
3549 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003550}
3551
Steve Naroff91fcddb2007-07-18 18:00:27 +00003552/// getVectorType - Return the unique reference to a vector type of
3553/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003554QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003555 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003556 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003557
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003558 // Check if we've already instantiated a vector of this type.
3559 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003560 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003561
Craig Topper36250ad2014-05-12 05:36:57 +00003562 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003563 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3564 return QualType(VTP, 0);
3565
3566 // If the element type isn't canonical, this won't be a canonical type either,
3567 // so fill in the canonical type field.
3568 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003569 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003570 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003571
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003572 // Get the new insert position for the node we care about.
3573 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003574 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003575 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003576 auto *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003577 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003578 VectorTypes.InsertNode(New, InsertPos);
3579 Types.push_back(New);
3580 return QualType(New, 0);
3581}
3582
Erich Keanef702b022018-07-13 19:46:04 +00003583QualType
3584ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3585 SourceLocation AttrLoc,
3586 VectorType::VectorKind VecKind) const {
3587 llvm::FoldingSetNodeID ID;
3588 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3589 VecKind);
3590 void *InsertPos = nullptr;
3591 DependentVectorType *Canon =
3592 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3593 DependentVectorType *New;
3594
3595 if (Canon) {
3596 New = new (*this, TypeAlignment) DependentVectorType(
3597 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3598 } else {
3599 QualType CanonVecTy = getCanonicalType(VecType);
3600 if (CanonVecTy == VecType) {
3601 New = new (*this, TypeAlignment) DependentVectorType(
3602 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3603
3604 DependentVectorType *CanonCheck =
3605 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3606 assert(!CanonCheck &&
3607 "Dependent-sized vector_size canonical type broken");
3608 (void)CanonCheck;
3609 DependentVectorTypes.InsertNode(New, InsertPos);
3610 } else {
3611 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3612 SourceLocation());
3613 New = new (*this, TypeAlignment) DependentVectorType(
3614 *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
3615 }
3616 }
3617
3618 Types.push_back(New);
3619 return QualType(New, 0);
3620}
3621
Nate Begemance4d7fc2008-04-18 23:10:10 +00003622/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003623/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003624QualType
3625ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003626 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003627
Steve Naroff91fcddb2007-07-18 18:00:27 +00003628 // Check if we've already instantiated a vector of this type.
3629 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003630 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003631 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003632 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003633 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3634 return QualType(VTP, 0);
3635
3636 // If the element type isn't canonical, this won't be a canonical type either,
3637 // so fill in the canonical type field.
3638 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003639 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003640 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003641
Steve Naroff91fcddb2007-07-18 18:00:27 +00003642 // Get the new insert position for the node we care about.
3643 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003644 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003645 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003646 auto *New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003647 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003648 VectorTypes.InsertNode(New, InsertPos);
3649 Types.push_back(New);
3650 return QualType(New, 0);
3651}
3652
Jay Foad39c79802011-01-12 09:06:06 +00003653QualType
3654ASTContext::getDependentSizedExtVectorType(QualType vecType,
3655 Expr *SizeExpr,
3656 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003657 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003658 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003659 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003660
Craig Topper36250ad2014-05-12 05:36:57 +00003661 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003662 DependentSizedExtVectorType *Canon
3663 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3664 DependentSizedExtVectorType *New;
3665 if (Canon) {
3666 // We already have a canonical version of this array type; use it as
3667 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003668 New = new (*this, TypeAlignment)
3669 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3670 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003671 } else {
3672 QualType CanonVecTy = getCanonicalType(vecType);
3673 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003674 New = new (*this, TypeAlignment)
3675 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3676 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003677
3678 DependentSizedExtVectorType *CanonCheck
3679 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3680 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3681 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003682 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3683 } else {
3684 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3685 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003686 New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003687 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003688 }
3689 }
Mike Stump11289f42009-09-09 15:08:12 +00003690
Douglas Gregor758a8692009-06-17 21:51:59 +00003691 Types.push_back(New);
3692 return QualType(New, 0);
3693}
3694
Fangrui Song6907ce22018-07-30 19:24:48 +00003695QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3696 Expr *AddrSpaceExpr,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003697 SourceLocation AttrLoc) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003698 assert(AddrSpaceExpr->isInstantiationDependent());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003699
3700 QualType canonPointeeType = getCanonicalType(PointeeType);
3701
3702 void *insertPos = nullptr;
3703 llvm::FoldingSetNodeID ID;
3704 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3705 AddrSpaceExpr);
3706
3707 DependentAddressSpaceType *canonTy =
3708 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3709
3710 if (!canonTy) {
3711 canonTy = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003712 DependentAddressSpaceType(*this, canonPointeeType,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003713 QualType(), AddrSpaceExpr, AttrLoc);
3714 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3715 Types.push_back(canonTy);
3716 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003717
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003718 if (canonPointeeType == PointeeType &&
3719 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
Fangrui Song6907ce22018-07-30 19:24:48 +00003720 return QualType(canonTy, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003721
Eugene Zelenko7855e772018-04-03 00:11:50 +00003722 auto *sugaredType
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003723 = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003724 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003725 AddrSpaceExpr, AttrLoc);
3726 Types.push_back(sugaredType);
Fangrui Song6907ce22018-07-30 19:24:48 +00003727 return QualType(sugaredType, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003728}
3729
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003730/// Determine whether \p T is canonical as the result type of a function.
John McCall18afab72016-03-01 00:49:02 +00003731static bool isCanonicalResultType(QualType T) {
3732 return T.isCanonical() &&
3733 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3734 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3735}
3736
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003737/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003738QualType
3739ASTContext::getFunctionNoProtoType(QualType ResultTy,
3740 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003741 // Unique functions, to guarantee there is only one function of a particular
3742 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003743 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003744 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003745
Craig Topper36250ad2014-05-12 05:36:57 +00003746 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003747 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003748 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003749 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003750
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003751 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003752 if (!isCanonicalResultType(ResultTy)) {
3753 Canonical =
3754 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003755
Chris Lattner47955de2007-01-27 08:37:20 +00003756 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003757 FunctionNoProtoType *NewIP =
3758 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003759 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003760 }
Mike Stump11289f42009-09-09 15:08:12 +00003761
Eugene Zelenko7855e772018-04-03 00:11:50 +00003762 auto *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003763 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003764 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003765 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003766 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003767}
3768
Douglas Gregora602a152015-10-01 20:20:47 +00003769CanQualType
3770ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3771 CanQualType CanResultType = getCanonicalType(ResultType);
3772
3773 // Canonical result types do not have ARC lifetime qualifiers.
3774 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3775 Qualifiers Qs = CanResultType.getQualifiers();
3776 Qs.removeObjCLifetime();
3777 return CanQualType::CreateUnsafe(
3778 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3779 }
3780
3781 return CanResultType;
3782}
3783
Richard Smith3c4f8d22016-10-16 17:54:23 +00003784static bool isCanonicalExceptionSpecification(
3785 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3786 if (ESI.Type == EST_None)
3787 return true;
3788 if (!NoexceptInType)
3789 return false;
3790
3791 // C++17 onwards: exception specification is part of the type, as a simple
3792 // boolean "can this function type throw".
3793 if (ESI.Type == EST_BasicNoexcept)
3794 return true;
3795
Richard Smitheaf11ad2018-05-03 03:58:32 +00003796 // A noexcept(expr) specification is (possibly) canonical if expr is
3797 // value-dependent.
3798 if (ESI.Type == EST_DependentNoexcept)
3799 return true;
3800
Richard Smith3c4f8d22016-10-16 17:54:23 +00003801 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003802 // expansions (so we can't tell whether it's non-throwing) and all its
3803 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003804 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003805 bool AnyPackExpansions = false;
3806 for (QualType ET : ESI.Exceptions) {
3807 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003808 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003809 if (ET->getAs<PackExpansionType>())
3810 AnyPackExpansions = true;
3811 }
3812 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003813 }
3814
Richard Smith3c4f8d22016-10-16 17:54:23 +00003815 return false;
3816}
3817
Richard Smith304b1242016-10-18 20:13:25 +00003818QualType ASTContext::getFunctionTypeInternal(
3819 QualType ResultTy, ArrayRef<QualType> ArgArray,
3820 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003821 size_t NumArgs = ArgArray.size();
3822
Richard Smith2a2cda52016-10-18 19:29:18 +00003823 // Unique functions, to guarantee there is only one function of a particular
3824 // structure.
3825 llvm::FoldingSetNodeID ID;
3826 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3827 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003828
Richard Smith2a2cda52016-10-18 19:29:18 +00003829 QualType Canonical;
3830 bool Unique = false;
3831
3832 void *InsertPos = nullptr;
3833 if (FunctionProtoType *FPT =
3834 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3835 QualType Existing = QualType(FPT, 0);
3836
3837 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3838 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003839 // noexcept expression, or we're just looking for a canonical type.
3840 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003841 // sugar node to hold the concrete expression.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003842 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003843 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3844 return Existing;
3845
3846 // We need a new type sugar node for this one, to hold the new noexcept
3847 // expression. We do no canonicalization here, but that's OK since we don't
3848 // expect to see the same noexcept expression much more than once.
3849 Canonical = getCanonicalType(Existing);
3850 Unique = true;
3851 }
3852
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003853 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003854 bool IsCanonicalExceptionSpec =
3855 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3856
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003857 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003858 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003859 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003860 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003861 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003862 isCanonical = false;
3863
Richard Smith304b1242016-10-18 20:13:25 +00003864 if (OnlyWantCanonical)
3865 assert(isCanonical &&
3866 "given non-canonical parameters constructing canonical type");
3867
Richard Smith2a2cda52016-10-18 19:29:18 +00003868 // If this type isn't canonical, get the canonical version of it if we don't
3869 // already have it. The exception spec is only partially part of the
3870 // canonical type, and only in C++17 onwards.
3871 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003872 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003873 CanonicalArgs.reserve(NumArgs);
3874 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003875 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003876
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003877 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003878 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003879 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003880
3881 if (IsCanonicalExceptionSpec) {
3882 // Exception spec is already OK.
3883 } else if (NoexceptInType) {
3884 switch (EPI.ExceptionSpec.Type) {
3885 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3886 // We don't know yet. It shouldn't matter what we pick here; no-one
3887 // should ever look at this.
3888 LLVM_FALLTHROUGH;
Richard Smitheaf11ad2018-05-03 03:58:32 +00003889 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003890 CanonicalEPI.ExceptionSpec.Type = EST_None;
3891 break;
3892
Richard Smith2a2cda52016-10-18 19:29:18 +00003893 // A dynamic exception specification is almost always "not noexcept",
3894 // with the exception that a pack expansion might expand to no types.
3895 case EST_Dynamic: {
3896 bool AnyPacks = false;
3897 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3898 if (ET->getAs<PackExpansionType>())
3899 AnyPacks = true;
3900 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3901 }
3902 if (!AnyPacks)
3903 CanonicalEPI.ExceptionSpec.Type = EST_None;
3904 else {
3905 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3906 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3907 }
3908 break;
3909 }
3910
Erich Keaned02f4a12019-05-30 17:31:54 +00003911 case EST_DynamicNone:
3912 case EST_BasicNoexcept:
3913 case EST_NoexceptTrue:
3914 case EST_NoThrow:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003915 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3916 break;
3917
Richard Smitheaf11ad2018-05-03 03:58:32 +00003918 case EST_DependentNoexcept:
3919 llvm_unreachable("dependent noexcept is already canonical");
Richard Smith3c4f8d22016-10-16 17:54:23 +00003920 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003921 } else {
3922 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3923 }
John McCalldb40c7f2010-12-14 08:05:40 +00003924
Douglas Gregora602a152015-10-01 20:20:47 +00003925 // Adjust the canonical function result type.
3926 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003927 Canonical =
3928 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003929
Chris Lattnerfd4de792007-01-27 01:15:32 +00003930 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003931 FunctionProtoType *NewIP =
3932 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003933 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003934 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003935
Bruno Ricci26a25362018-10-02 11:46:38 +00003936 // Compute the needed size to hold this FunctionProtoType and the
3937 // various trailing objects.
3938 auto ESH = FunctionProtoType::getExceptionSpecSize(
3939 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
3940 size_t Size = FunctionProtoType::totalSizeToAlloc<
Nicolas Manichoncc3c9352019-12-03 08:21:55 -05003941 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
Bruno Ricci26a25362018-10-02 11:46:38 +00003942 FunctionType::ExceptionType, Expr *, FunctionDecl *,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003943 FunctionProtoType::ExtParameterInfo, Qualifiers>(
Nicolas Manichoncc3c9352019-12-03 08:21:55 -05003944 NumArgs, EPI.Variadic,
3945 FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
Bruno Ricci26a25362018-10-02 11:46:38 +00003946 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003947 EPI.ExtParameterInfos ? NumArgs : 0,
3948 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
John McCall18afab72016-03-01 00:49:02 +00003949
Bruno Ricci26a25362018-10-02 11:46:38 +00003950 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003951 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003952 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003953 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003954 if (!Unique)
3955 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003956 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003957}
Chris Lattneref51c202006-11-10 07:17:23 +00003958
Joey Goulye3c85de2016-12-01 11:30:49 +00003959QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003960 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003961 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003962
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00003963 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00003964 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003965 return QualType(PT, 0);
3966
3967 // If the pipe element type isn't canonical, this won't be a canonical type
3968 // either, so fill in the canonical type field.
3969 QualType Canonical;
3970 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003971 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003972
3973 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003974 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003975 assert(!NewIP && "Shouldn't be in the map!");
3976 (void)NewIP;
3977 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003978 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003979 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003980 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003981 return QualType(New, 0);
3982}
3983
Anastasia Stulova59055b92018-05-09 13:23:26 +00003984QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
3985 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3986 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3987 : Ty;
3988}
3989
Joey Goulye3c85de2016-12-01 11:30:49 +00003990QualType ASTContext::getReadPipeType(QualType T) const {
3991 return getPipeType(T, true);
3992}
3993
Joey Gouly5788b782016-11-18 14:10:54 +00003994QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003995 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003996}
3997
John McCalle78aac42010-03-10 03:28:59 +00003998#ifndef NDEBUG
3999static bool NeedsInjectedClassNameType(const RecordDecl *D) {
4000 if (!isa<CXXRecordDecl>(D)) return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004001 const auto *RD = cast<CXXRecordDecl>(D);
John McCalle78aac42010-03-10 03:28:59 +00004002 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4003 return true;
4004 if (RD->getDescribedClassTemplate() &&
4005 !isa<ClassTemplateSpecializationDecl>(RD))
4006 return true;
4007 return false;
4008}
4009#endif
4010
4011/// getInjectedClassNameType - Return the unique reference to the
4012/// injected class name type for the specified templated declaration.
4013QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00004014 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00004015 assert(NeedsInjectedClassNameType(Decl));
4016 if (Decl->TypeForDecl) {
4017 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00004018 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00004019 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
4020 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4021 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4022 } else {
John McCall424cec92011-01-19 06:33:43 +00004023 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00004024 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00004025 Decl->TypeForDecl = newType;
4026 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00004027 }
4028 return QualType(Decl->TypeForDecl, 0);
4029}
4030
Douglas Gregor83a586e2008-04-13 21:07:44 +00004031/// getTypeDeclType - Return the unique reference to the type for the
4032/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00004033QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00004034 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00004035 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00004036
Eugene Zelenko7855e772018-04-03 00:11:50 +00004037 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00004038 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00004039
John McCall96f0b5f2010-03-10 06:48:02 +00004040 assert(!isa<TemplateTypeParmDecl>(Decl) &&
4041 "Template type parameter types are always available.");
4042
Eugene Zelenko7855e772018-04-03 00:11:50 +00004043 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00004044 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00004045 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004046 return getRecordType(Record);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004047 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00004048 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004049 return getEnumType(Enum);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004050 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00004051 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
4052 Decl->TypeForDecl = newType;
4053 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004054 } else
John McCall96f0b5f2010-03-10 06:48:02 +00004055 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00004056
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00004057 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00004058}
4059
Chris Lattner32d920b2007-01-26 02:01:53 +00004060/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00004061/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004062QualType
Richard Smithdda56e42011-04-15 14:24:37 +00004063ASTContext::getTypedefType(const TypedefNameDecl *Decl,
4064 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00004065 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004066
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004067 if (Canonical.isNull())
4068 Canonical = getCanonicalType(Decl->getUnderlyingType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00004069 auto *newType = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00004070 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00004071 Decl->TypeForDecl = newType;
4072 Types.push_back(newType);
4073 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00004074}
4075
Jay Foad39c79802011-01-12 09:06:06 +00004076QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004077 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4078
Douglas Gregorec9fd132012-01-14 16:38:05 +00004079 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004080 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00004081 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004082
Eugene Zelenko7855e772018-04-03 00:11:50 +00004083 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
John McCall424cec92011-01-19 06:33:43 +00004084 Decl->TypeForDecl = newType;
4085 Types.push_back(newType);
4086 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004087}
4088
Jay Foad39c79802011-01-12 09:06:06 +00004089QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004090 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4091
Douglas Gregorec9fd132012-01-14 16:38:05 +00004092 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004093 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00004094 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004095
Eugene Zelenko7855e772018-04-03 00:11:50 +00004096 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
John McCall424cec92011-01-19 06:33:43 +00004097 Decl->TypeForDecl = newType;
4098 Types.push_back(newType);
4099 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004100}
4101
Richard Smithe43e2b32018-08-20 21:47:29 +00004102QualType ASTContext::getAttributedType(attr::Kind attrKind,
John McCall81904512011-01-06 01:58:22 +00004103 QualType modifiedType,
4104 QualType equivalentType) {
4105 llvm::FoldingSetNodeID id;
4106 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4107
Craig Topper36250ad2014-05-12 05:36:57 +00004108 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00004109 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4110 if (type) return QualType(type, 0);
4111
4112 QualType canon = getCanonicalType(equivalentType);
4113 type = new (*this, TypeAlignment)
Leonard Chanc72aaf62019-05-07 03:20:17 +00004114 AttributedType(canon, attrKind, modifiedType, equivalentType);
John McCall81904512011-01-06 01:58:22 +00004115
4116 Types.push_back(type);
4117 AttributedTypes.InsertNode(type, insertPos);
4118
4119 return QualType(type, 0);
4120}
4121
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004122/// Retrieve a substitution-result type.
John McCallcebee162009-10-18 09:09:24 +00004123QualType
4124ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00004125 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00004126 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00004127 && "replacement types must always be canonical");
4128
4129 llvm::FoldingSetNodeID ID;
4130 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00004131 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00004132 SubstTemplateTypeParmType *SubstParm
4133 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4134
4135 if (!SubstParm) {
4136 SubstParm = new (*this, TypeAlignment)
4137 SubstTemplateTypeParmType(Parm, Replacement);
4138 Types.push_back(SubstParm);
4139 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4140 }
4141
4142 return QualType(SubstParm, 0);
4143}
4144
Fangrui Song6907ce22018-07-30 19:24:48 +00004145/// Retrieve a
Douglas Gregorada4b792011-01-14 02:55:32 +00004146QualType ASTContext::getSubstTemplateTypeParmPackType(
4147 const TemplateTypeParmType *Parm,
4148 const TemplateArgument &ArgPack) {
4149#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00004150 for (const auto &P : ArgPack.pack_elements()) {
4151 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4152 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00004153 }
4154#endif
Fangrui Song6907ce22018-07-30 19:24:48 +00004155
Douglas Gregorada4b792011-01-14 02:55:32 +00004156 llvm::FoldingSetNodeID ID;
4157 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00004158 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00004159 if (SubstTemplateTypeParmPackType *SubstParm
4160 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4161 return QualType(SubstParm, 0);
Fangrui Song6907ce22018-07-30 19:24:48 +00004162
Douglas Gregorada4b792011-01-14 02:55:32 +00004163 QualType Canon;
4164 if (!Parm->isCanonicalUnqualified()) {
4165 Canon = getCanonicalType(QualType(Parm, 0));
4166 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4167 ArgPack);
4168 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4169 }
4170
Eugene Zelenko7855e772018-04-03 00:11:50 +00004171 auto *SubstParm
Douglas Gregorada4b792011-01-14 02:55:32 +00004172 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4173 ArgPack);
4174 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00004175 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00004176 return QualType(SubstParm, 0);
Douglas Gregorada4b792011-01-14 02:55:32 +00004177}
4178
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004179/// Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00004180/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00004181/// name.
Mike Stump11289f42009-09-09 15:08:12 +00004182QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00004183 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00004184 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00004185 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00004186 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00004187 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004188 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00004189 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4190
4191 if (TypeParm)
4192 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004193
Chandler Carruth08836322011-05-01 00:51:33 +00004194 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00004195 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00004196 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004197
Fangrui Song6907ce22018-07-30 19:24:48 +00004198 TemplateTypeParmType *TypeCheck
Douglas Gregorc42075a2010-02-04 18:10:26 +00004199 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4200 assert(!TypeCheck && "Template type parameter canonical type broken");
4201 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00004202 } else
John McCall90d1c2d2009-09-24 23:30:46 +00004203 TypeParm = new (*this, TypeAlignment)
4204 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00004205
4206 Types.push_back(TypeParm);
4207 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4208
4209 return QualType(TypeParm, 0);
4210}
4211
John McCalle78aac42010-03-10 03:28:59 +00004212TypeSourceInfo *
4213ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4214 SourceLocation NameLoc,
4215 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004216 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004217 assert(!Name.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004218 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004219 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00004220
4221 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00004222 TemplateSpecializationTypeLoc TL =
4223 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00004224 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00004225 TL.setTemplateNameLoc(NameLoc);
4226 TL.setLAngleLoc(Args.getLAngleLoc());
4227 TL.setRAngleLoc(Args.getRAngleLoc());
4228 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4229 TL.setArgLocInfo(i, Args[i].getLocInfo());
4230 return DI;
4231}
4232
Mike Stump11289f42009-09-09 15:08:12 +00004233QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00004234ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00004235 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004236 QualType Underlying) 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!");
John McCall6b51f282009-11-23 01:53:49 +00004239
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004240 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004241 ArgVec.reserve(Args.size());
4242 for (const TemplateArgumentLoc &Arg : Args.arguments())
4243 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00004244
David Majnemer6fbeee32016-07-07 04:43:07 +00004245 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00004246}
4247
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004248#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00004249static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4250 for (const TemplateArgument &Arg : Args)
4251 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004252 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004253
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004254 return true;
4255}
4256#endif
4257
John McCall0ad16662009-10-29 08:12:44 +00004258QualType
4259ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00004260 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004261 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004262 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004263 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00004264 // Look through qualified template names.
4265 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4266 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004267
4268 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00004269 Template.getAsTemplateDecl() &&
4270 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004271 QualType CanonType;
4272 if (!Underlying.isNull())
4273 CanonType = getCanonicalType(Underlying);
4274 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004275 // We can get here with an alias template when the specialization contains
4276 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00004277 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004278 "Caller must compute aliased type");
4279 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004280 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00004281 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00004282
Douglas Gregora8e02e72009-07-28 23:00:59 +00004283 // Allocate the (non-canonical) template specialization type, but don't
4284 // try to unique it: these types typically have location information that
4285 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004286 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00004287 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004288 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00004289 TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004290 auto *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00004291 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004292 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00004293
Douglas Gregor8bf42052009-02-09 18:46:07 +00004294 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00004295 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00004296}
4297
David Majnemer6fbeee32016-07-07 04:43:07 +00004298QualType ASTContext::getCanonicalTemplateSpecializationType(
4299 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004300 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004301 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004302
Douglas Gregore29139c2011-03-03 17:04:51 +00004303 // Look through qualified template names.
4304 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4305 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004306
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004307 // Build the canonical template specialization type.
4308 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004309 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00004310 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004311 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00004312 for (const TemplateArgument &Arg : Args)
4313 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004314
4315 // Determine whether this canonical template specialization type already
4316 // exists.
4317 llvm::FoldingSetNodeID ID;
4318 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004319 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004320
Craig Topper36250ad2014-05-12 05:36:57 +00004321 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004322 TemplateSpecializationType *Spec
4323 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4324
4325 if (!Spec) {
4326 // Allocate a new canonical template specialization type.
4327 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4328 sizeof(TemplateArgument) * NumArgs),
4329 TypeAlignment);
4330 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004331 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004332 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004333 Types.push_back(Spec);
4334 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4335 }
4336
4337 assert(Spec->isDependentType() &&
4338 "Non-dependent template-id type must have a canonical type");
4339 return QualType(Spec, 0);
4340}
4341
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004342QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4343 NestedNameSpecifier *NNS,
4344 QualType NamedType,
4345 TagDecl *OwnedTagDecl) const {
Douglas Gregor52537682009-03-19 00:18:19 +00004346 llvm::FoldingSetNodeID ID;
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004347 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
Douglas Gregor52537682009-03-19 00:18:19 +00004348
Craig Topper36250ad2014-05-12 05:36:57 +00004349 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00004350 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004351 if (T)
4352 return QualType(T, 0);
4353
Douglas Gregorc42075a2010-02-04 18:10:26 +00004354 QualType Canon = NamedType;
4355 if (!Canon.isCanonical()) {
4356 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004357 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4358 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004359 (void)CheckT;
4360 }
4361
Bruno Riccid6bd5982018-08-16 10:48:16 +00004362 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4363 TypeAlignment);
4364 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4365
Douglas Gregor52537682009-03-19 00:18:19 +00004366 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004367 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004368 return QualType(T, 0);
4369}
4370
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004371QualType
Jay Foad39c79802011-01-12 09:06:06 +00004372ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004373 llvm::FoldingSetNodeID ID;
4374 ParenType::Profile(ID, InnerType);
4375
Craig Topper36250ad2014-05-12 05:36:57 +00004376 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004377 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4378 if (T)
4379 return QualType(T, 0);
4380
4381 QualType Canon = InnerType;
4382 if (!Canon.isCanonical()) {
4383 Canon = getCanonicalType(InnerType);
4384 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4385 assert(!CheckT && "Paren canonical type broken");
4386 (void)CheckT;
4387 }
4388
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004389 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004390 Types.push_back(T);
4391 ParenTypes.InsertNode(T, InsertPos);
4392 return QualType(T, 0);
4393}
4394
Leonard Chanc72aaf62019-05-07 03:20:17 +00004395QualType
4396ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
4397 const IdentifierInfo *MacroII) const {
4398 QualType Canon = UnderlyingTy;
4399 if (!Canon.isCanonical())
4400 Canon = getCanonicalType(UnderlyingTy);
4401
4402 auto *newType = new (*this, TypeAlignment)
4403 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4404 Types.push_back(newType);
4405 return QualType(newType, 0);
4406}
4407
Douglas Gregor02085352010-03-31 20:19:30 +00004408QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4409 NestedNameSpecifier *NNS,
4410 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004411 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004412 if (Canon.isNull()) {
4413 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004414 if (CanonNNS != NNS)
4415 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004416 }
4417
4418 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004419 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004420
Craig Topper36250ad2014-05-12 05:36:57 +00004421 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004422 DependentNameType *T
4423 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004424 if (T)
4425 return QualType(T, 0);
4426
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004427 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004428 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004429 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004430 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004431}
4432
Mike Stump11289f42009-09-09 15:08:12 +00004433QualType
John McCallc392f372010-06-11 00:33:02 +00004434ASTContext::getDependentTemplateSpecializationType(
4435 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004436 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004437 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004438 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004439 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004440 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004441 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4442 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004443 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004444}
4445
4446QualType
4447ASTContext::getDependentTemplateSpecializationType(
4448 ElaboratedTypeKeyword Keyword,
4449 NestedNameSpecifier *NNS,
4450 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004451 ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004452 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor6e068012011-02-28 00:04:36 +00004453 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004454
Douglas Gregorc42075a2010-02-04 18:10:26 +00004455 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004456 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004457 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004458
Craig Topper36250ad2014-05-12 05:36:57 +00004459 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004460 DependentTemplateSpecializationType *T
4461 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004462 if (T)
4463 return QualType(T, 0);
4464
John McCallc392f372010-06-11 00:33:02 +00004465 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004466
John McCallc392f372010-06-11 00:33:02 +00004467 ElaboratedTypeKeyword CanonKeyword = Keyword;
4468 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4469
4470 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004471 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004472 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004473 for (unsigned I = 0; I != NumArgs; ++I) {
4474 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4475 if (!CanonArgs[I].structurallyEquals(Args[I]))
4476 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004477 }
4478
John McCallc392f372010-06-11 00:33:02 +00004479 QualType Canon;
4480 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4481 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004482 Name,
4483 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004484
4485 // Find the insert position again.
4486 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4487 }
4488
4489 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4490 sizeof(TemplateArgument) * NumArgs),
4491 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004492 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004493 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004494 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004495 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004496 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004497}
4498
Richard Smith32918772017-02-14 00:25:28 +00004499TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4500 TemplateArgument Arg;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004501 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith32918772017-02-14 00:25:28 +00004502 QualType ArgType = getTypeDeclType(TTP);
4503 if (TTP->isParameterPack())
4504 ArgType = getPackExpansionType(ArgType, None);
4505
4506 Arg = TemplateArgument(ArgType);
4507 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4508 Expr *E = new (*this) DeclRefExpr(
Bruno Ricci5fc4db72018-12-21 14:10:18 +00004509 *this, NTTP, /*enclosing*/ false,
Richard Smith32918772017-02-14 00:25:28 +00004510 NTTP->getType().getNonLValueExprType(*this),
4511 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4512
4513 if (NTTP->isParameterPack())
4514 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4515 None);
4516 Arg = TemplateArgument(E);
4517 } else {
4518 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4519 if (TTP->isParameterPack())
4520 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4521 else
4522 Arg = TemplateArgument(TemplateName(TTP));
4523 }
4524
4525 if (Param->isTemplateParameterPack())
4526 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4527
4528 return Arg;
4529}
4530
Richard Smith43e14d22016-12-23 02:10:11 +00004531void
4532ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4533 SmallVectorImpl<TemplateArgument> &Args) {
4534 Args.reserve(Args.size() + Params->size());
4535
Richard Smith32918772017-02-14 00:25:28 +00004536 for (NamedDecl *Param : *Params)
4537 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004538}
4539
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004540QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004541 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004542 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004543 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004544
Richard Smithb2997f52019-05-21 20:10:50 +00004545 // A deduced type can deduce to a pack, eg
4546 // auto ...x = some_pack;
4547 // That declaration isn't (yet) valid, but is created as part of building an
4548 // init-capture pack:
4549 // [...x = some_pack] {}
4550 assert((Pattern->containsUnexpandedParameterPack() ||
4551 Pattern->getContainedDeducedType()) &&
Douglas Gregord2fa7662010-12-20 02:24:11 +00004552 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004553 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004554 PackExpansionType *T
4555 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4556 if (T)
4557 return QualType(T, 0);
4558
4559 QualType Canon;
4560 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004561 Canon = getCanonicalType(Pattern);
4562 // The canonical type might not contain an unexpanded parameter pack, if it
4563 // contains an alias template specialization which ignores one of its
4564 // parameters.
4565 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004566 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004567
Richard Smith68eea502012-07-16 00:20:35 +00004568 // Find the insert position again, in case we inserted an element into
4569 // PackExpansionTypes and invalidated our insert position.
4570 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4571 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004572 }
4573
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004574 T = new (*this, TypeAlignment)
4575 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004576 Types.push_back(T);
4577 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004578 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004579}
4580
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004581/// CmpProtocolNames - Comparison predicate for sorting protocols
4582/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004583static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4584 ObjCProtocolDecl *const *RHS) {
4585 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004586}
4587
Craig Topper1f26d5b2016-01-03 19:43:23 +00004588static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4589 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004590
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004591 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4592 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004593
Craig Topper1f26d5b2016-01-03 19:43:23 +00004594 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004595 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004596 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004597 return false;
4598 return true;
4599}
4600
Craig Topper6a8c1512015-10-22 01:56:18 +00004601static void
4602SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004603 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004604 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004605
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004606 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004607 for (ObjCProtocolDecl *&P : Protocols)
4608 P = P->getCanonicalDecl();
4609
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004610 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004611 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4612 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004613}
4614
John McCall8b07ec22010-05-15 11:32:37 +00004615QualType ASTContext::getObjCObjectType(QualType BaseType,
4616 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004617 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004618 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004619 llvm::makeArrayRef(Protocols, NumProtocols),
4620 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004621}
4622
4623QualType ASTContext::getObjCObjectType(
4624 QualType baseType,
4625 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004626 ArrayRef<ObjCProtocolDecl *> protocols,
4627 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004628 // If the base type is an interface and there aren't any protocols or
4629 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004630 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4631 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004632 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004633
4634 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004635 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004636 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004637 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004638 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4639 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004640
Douglas Gregore9d95f12015-07-07 03:57:35 +00004641 // Determine the type arguments to be used for canonicalization,
4642 // which may be explicitly specified here or written on the base
4643 // type.
4644 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4645 if (effectiveTypeArgs.empty()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004646 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
Douglas Gregore9d95f12015-07-07 03:57:35 +00004647 effectiveTypeArgs = baseObject->getTypeArgs();
4648 }
John McCallfc93cf92009-10-22 22:37:11 +00004649
Douglas Gregore9d95f12015-07-07 03:57:35 +00004650 // Build the canonical type, which has the canonical base type and a
4651 // sorted-and-uniqued list of protocols and the type arguments
4652 // canonicalized.
4653 QualType canonical;
4654 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4655 effectiveTypeArgs.end(),
4656 [&](QualType type) {
4657 return type.isCanonical();
4658 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004659 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004660 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4661 // Determine the canonical type arguments.
4662 ArrayRef<QualType> canonTypeArgs;
4663 SmallVector<QualType, 4> canonTypeArgsVec;
4664 if (!typeArgsAreCanonical) {
4665 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4666 for (auto typeArg : effectiveTypeArgs)
4667 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4668 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004669 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004670 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004671 }
4672
Douglas Gregore9d95f12015-07-07 03:57:35 +00004673 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4674 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4675 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004676 canonProtocolsVec.append(protocols.begin(), protocols.end());
4677 SortAndUniqueProtocols(canonProtocolsVec);
4678 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004679 } else {
4680 canonProtocols = protocols;
4681 }
4682
4683 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004684 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004685
John McCallfc93cf92009-10-22 22:37:11 +00004686 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004687 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4688 }
4689
Douglas Gregore9d95f12015-07-07 03:57:35 +00004690 unsigned size = sizeof(ObjCObjectTypeImpl);
4691 size += typeArgs.size() * sizeof(QualType);
4692 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4693 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004694 auto *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004695 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4696 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004697
4698 Types.push_back(T);
4699 ObjCObjectTypes.InsertNode(T, InsertPos);
4700 return QualType(T, 0);
4701}
4702
Manman Ren3569eb52016-09-13 17:03:12 +00004703/// Apply Objective-C protocol qualifiers to the given type.
4704/// If this is for the canonical type of a type parameter, we can apply
4705/// protocol qualifiers on the ObjCObjectPointerType.
4706QualType
4707ASTContext::applyObjCProtocolQualifiers(QualType type,
4708 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4709 bool allowOnPointerType) const {
4710 hasError = false;
4711
Eugene Zelenko7855e772018-04-03 00:11:50 +00004712 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
Manman Renc5705ba2016-09-13 17:41:05 +00004713 return getObjCTypeParamType(objT->getDecl(), protocols);
4714 }
4715
Manman Ren3569eb52016-09-13 17:03:12 +00004716 // Apply protocol qualifiers to ObjCObjectPointerType.
4717 if (allowOnPointerType) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004718 if (const auto *objPtr =
4719 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
Manman Ren3569eb52016-09-13 17:03:12 +00004720 const ObjCObjectType *objT = objPtr->getObjectType();
4721 // Merge protocol lists and construct ObjCObjectType.
4722 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4723 protocolsVec.append(objT->qual_begin(),
4724 objT->qual_end());
4725 protocolsVec.append(protocols.begin(), protocols.end());
4726 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4727 type = getObjCObjectType(
4728 objT->getBaseType(),
4729 objT->getTypeArgsAsWritten(),
4730 protocols,
4731 objT->isKindOfTypeAsWritten());
4732 return getObjCObjectPointerType(type);
4733 }
4734 }
4735
4736 // Apply protocol qualifiers to ObjCObjectType.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004737 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
Manman Ren3569eb52016-09-13 17:03:12 +00004738 // FIXME: Check for protocols to which the class type is already
4739 // known to conform.
4740
4741 return getObjCObjectType(objT->getBaseType(),
4742 objT->getTypeArgsAsWritten(),
4743 protocols,
4744 objT->isKindOfTypeAsWritten());
4745 }
4746
4747 // If the canonical type is ObjCObjectType, ...
4748 if (type->isObjCObjectType()) {
4749 // Silently overwrite any existing protocol qualifiers.
4750 // TODO: determine whether that's the right thing to do.
4751
4752 // FIXME: Check for protocols to which the class type is already
4753 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004754 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004755 }
4756
4757 // id<protocol-list>
4758 if (type->isObjCIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004759 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004760 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004761 objPtr->isKindOfType());
4762 return getObjCObjectPointerType(type);
4763 }
4764
4765 // Class<protocol-list>
4766 if (type->isObjCClassType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004767 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004768 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004769 objPtr->isKindOfType());
4770 return getObjCObjectPointerType(type);
4771 }
4772
4773 hasError = true;
4774 return type;
4775}
4776
Manman Rene6be26c2016-09-13 17:25:08 +00004777QualType
4778ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
Volodymyr Sapsaib95d4c32019-10-11 21:21:02 +00004779 ArrayRef<ObjCProtocolDecl *> protocols) const {
Manman Rene6be26c2016-09-13 17:25:08 +00004780 // Look in the folding set for an existing type.
4781 llvm::FoldingSetNodeID ID;
4782 ObjCTypeParamType::Profile(ID, Decl, protocols);
4783 void *InsertPos = nullptr;
4784 if (ObjCTypeParamType *TypeParam =
4785 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4786 return QualType(TypeParam, 0);
4787
Volodymyr Sapsaib95d4c32019-10-11 21:21:02 +00004788 // We canonicalize to the underlying type.
4789 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
4790 if (!protocols.empty()) {
4791 // Apply the protocol qualifers.
4792 bool hasError;
4793 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
4794 Canonical, protocols, hasError, true /*allowOnPointerType*/));
4795 assert(!hasError && "Error when apply protocol qualifier to bound type");
Manman Rene6be26c2016-09-13 17:25:08 +00004796 }
4797
4798 unsigned size = sizeof(ObjCTypeParamType);
4799 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4800 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004801 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
Manman Rene6be26c2016-09-13 17:25:08 +00004802
4803 Types.push_back(newType);
4804 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4805 return QualType(newType, 0);
4806}
4807
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004808/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4809/// protocol list adopt all protocols in QT's qualified-id protocol
4810/// list.
4811bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4812 ObjCInterfaceDecl *IC) {
4813 if (!QT->isObjCQualifiedIdType())
4814 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004815
Eugene Zelenko7855e772018-04-03 00:11:50 +00004816 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004817 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004818 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004819 if (!IC->ClassImplementsProtocol(Proto, false))
4820 return false;
4821 }
4822 return true;
4823 }
4824 return false;
4825}
4826
4827/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4828/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4829/// of protocols.
4830bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4831 ObjCInterfaceDecl *IDecl) {
4832 if (!QT->isObjCQualifiedIdType())
4833 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004834 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004835 if (!OPT)
4836 return false;
4837 if (!IDecl->hasDefinition())
4838 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004839 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4840 CollectInheritedProtocols(IDecl, InheritedProtocols);
4841 if (InheritedProtocols.empty())
4842 return false;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004843 // Check that if every protocol in list of id<plist> conforms to a protocol
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004844 // of IDecl's, then bridge casting is ok.
4845 bool Conforms = false;
4846 for (auto *Proto : OPT->quals()) {
4847 Conforms = false;
4848 for (auto *PI : InheritedProtocols) {
4849 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4850 Conforms = true;
4851 break;
4852 }
4853 }
4854 if (!Conforms)
4855 break;
4856 }
4857 if (Conforms)
4858 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004859
Aaron Ballman83731462014-03-17 16:14:00 +00004860 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004861 // If both the right and left sides have qualifiers.
4862 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004863 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004864 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004865 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004866 break;
4867 }
4868 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004869 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004870 }
4871 return true;
4872}
4873
John McCall8b07ec22010-05-15 11:32:37 +00004874/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4875/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004876QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004877 llvm::FoldingSetNodeID ID;
4878 ObjCObjectPointerType::Profile(ID, ObjectT);
4879
Craig Topper36250ad2014-05-12 05:36:57 +00004880 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004881 if (ObjCObjectPointerType *QT =
4882 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4883 return QualType(QT, 0);
4884
4885 // Find the canonical object type.
4886 QualType Canonical;
4887 if (!ObjectT.isCanonical()) {
4888 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4889
4890 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004891 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4892 }
4893
Douglas Gregorf85bee62010-02-08 22:59:26 +00004894 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004895 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004896 auto *QType =
John McCall8b07ec22010-05-15 11:32:37 +00004897 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004898
Steve Narofffb4330f2009-06-17 22:40:22 +00004899 Types.push_back(QType);
4900 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004901 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004902}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004903
Douglas Gregor1c283312010-08-11 12:19:30 +00004904/// getObjCInterfaceType - Return the unique reference to the type for the
4905/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004906QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4907 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004908 if (Decl->TypeForDecl)
4909 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004910
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004911 if (PrevDecl) {
4912 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4913 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4914 return QualType(PrevDecl->TypeForDecl, 0);
4915 }
4916
Douglas Gregor7671e532011-12-16 16:34:57 +00004917 // Prefer the definition, if there is one.
4918 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4919 Decl = Def;
Fangrui Song6907ce22018-07-30 19:24:48 +00004920
Douglas Gregor1c283312010-08-11 12:19:30 +00004921 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004922 auto *T = new (Mem) ObjCInterfaceType(Decl);
Douglas Gregor1c283312010-08-11 12:19:30 +00004923 Decl->TypeForDecl = T;
4924 Types.push_back(T);
4925 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004926}
4927
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004928/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4929/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004930/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004931/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004932/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004933QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004934 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004935 if (tofExpr->isTypeDependent()) {
4936 llvm::FoldingSetNodeID ID;
4937 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004938
Craig Topper36250ad2014-05-12 05:36:57 +00004939 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004940 DependentTypeOfExprType *Canon
4941 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4942 if (Canon) {
4943 // We already have a "canonical" version of an identical, dependent
4944 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004945 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004946 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004947 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004948 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004949 Canon
4950 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004951 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4952 toe = Canon;
4953 }
4954 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004955 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004956 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004957 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004958 Types.push_back(toe);
4959 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004960}
4961
Steve Naroffa773cd52007-08-01 18:02:17 +00004962/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004963/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004964/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004965/// an issue. This doesn't affect the type checker, since it operates
4966/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004967QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004968 QualType Canonical = getCanonicalType(tofType);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004969 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004970 Types.push_back(tot);
4971 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004972}
4973
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004974/// Unlike many "get<Type>" functions, we don't unique DecltypeType
Richard Smith8eb1d322014-06-05 20:13:13 +00004975/// nodes. This would never be helpful, since each such type has its own
4976/// expression, and would not give a significant memory saving, since there
4977/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004978QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004979 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004980
4981 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004982 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004983 // unique dependent type. Two such decltype-specifiers refer to the same
4984 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004985 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004986 llvm::FoldingSetNodeID ID;
4987 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004988
Craig Topper36250ad2014-05-12 05:36:57 +00004989 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004990 DependentDecltypeType *Canon
4991 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004992 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004993 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004994 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004995 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004996 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004997 dt = new (*this, TypeAlignment)
4998 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004999 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00005000 dt = new (*this, TypeAlignment)
5001 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00005002 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00005003 Types.push_back(dt);
5004 return QualType(dt, 0);
5005}
5006
Alexis Hunte852b102011-05-24 22:41:36 +00005007/// getUnaryTransformationType - We don't unique these, since the memory
5008/// savings are minimal and these are rare.
5009QualType ASTContext::getUnaryTransformType(QualType BaseType,
5010 QualType UnderlyingType,
5011 UnaryTransformType::UTTKind Kind)
5012 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00005013 UnaryTransformType *ut = nullptr;
5014
5015 if (BaseType->isDependentType()) {
5016 // Look in the folding set for an existing type.
5017 llvm::FoldingSetNodeID ID;
5018 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
5019
5020 void *InsertPos = nullptr;
5021 DependentUnaryTransformType *Canon
5022 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
5023
5024 if (!Canon) {
5025 // Build a new, canonical __underlying_type(type) type.
5026 Canon = new (*this, TypeAlignment)
5027 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
5028 Kind);
5029 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
5030 }
5031 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5032 QualType(), Kind,
5033 QualType(Canon, 0));
5034 } else {
5035 QualType CanonType = getCanonicalType(UnderlyingType);
5036 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5037 UnderlyingType, Kind,
5038 CanonType);
5039 }
5040 Types.push_back(ut);
5041 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00005042}
5043
Richard Smith2a7d4812013-05-04 07:00:32 +00005044/// getAutoType - Return the uniqued reference to the 'auto' type which has been
5045/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
5046/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00005047QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Richard Smithb2997f52019-05-21 20:10:50 +00005048 bool IsDependent, bool IsPack) const {
5049 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
Richard Smithe301ba22015-11-11 02:02:15 +00005050 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00005051 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005052
Richard Smith2a7d4812013-05-04 07:00:32 +00005053 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00005054 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00005055 llvm::FoldingSetNodeID ID;
Richard Smithb2997f52019-05-21 20:10:50 +00005056 AutoType::Profile(ID, DeducedType, Keyword, IsDependent, IsPack);
Richard Smith2a7d4812013-05-04 07:00:32 +00005057 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
5058 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00005059
Eugene Zelenko7855e772018-04-03 00:11:50 +00005060 auto *AT = new (*this, TypeAlignment)
Richard Smithb2997f52019-05-21 20:10:50 +00005061 AutoType(DeducedType, Keyword, IsDependent, IsPack);
Richard Smithb2bc2e62011-02-21 20:05:19 +00005062 Types.push_back(AT);
5063 if (InsertPos)
5064 AutoTypes.InsertNode(AT, InsertPos);
5065 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00005066}
5067
Richard Smith600b5262017-01-26 20:40:47 +00005068/// Return the uniqued reference to the deduced template specialization type
5069/// which has been deduced to the given type, or to the canonical undeduced
5070/// such type, or the canonical deduced-but-dependent such type.
5071QualType ASTContext::getDeducedTemplateSpecializationType(
5072 TemplateName Template, QualType DeducedType, bool IsDependent) const {
5073 // Look in the folding set for an existing type.
5074 void *InsertPos = nullptr;
5075 llvm::FoldingSetNodeID ID;
5076 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
5077 IsDependent);
5078 if (DeducedTemplateSpecializationType *DTST =
5079 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5080 return QualType(DTST, 0);
5081
Eugene Zelenko7855e772018-04-03 00:11:50 +00005082 auto *DTST = new (*this, TypeAlignment)
Richard Smith600b5262017-01-26 20:40:47 +00005083 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5084 Types.push_back(DTST);
5085 if (InsertPos)
5086 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5087 return QualType(DTST, 0);
5088}
5089
Eli Friedman0dfb8892011-10-06 23:00:33 +00005090/// getAtomicType - Return the uniqued reference to the atomic type for
5091/// the given value type.
5092QualType ASTContext::getAtomicType(QualType T) const {
5093 // Unique pointers, to guarantee there is only one pointer of a particular
5094 // structure.
5095 llvm::FoldingSetNodeID ID;
5096 AtomicType::Profile(ID, T);
5097
Craig Topper36250ad2014-05-12 05:36:57 +00005098 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00005099 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5100 return QualType(AT, 0);
5101
5102 // If the atomic value type isn't canonical, this won't be a canonical type
5103 // either, so fill in the canonical type field.
5104 QualType Canonical;
5105 if (!T.isCanonical()) {
5106 Canonical = getAtomicType(getCanonicalType(T));
5107
5108 // Get the new insert position for the node we care about.
5109 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00005110 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00005111 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00005112 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
Eli Friedman0dfb8892011-10-06 23:00:33 +00005113 Types.push_back(New);
5114 AtomicTypes.InsertNode(New, InsertPos);
5115 return QualType(New, 0);
5116}
5117
Richard Smith02e85f32011-04-14 22:09:26 +00005118/// getAutoDeductType - Get type pattern for deducing against 'auto'.
5119QualType ASTContext::getAutoDeductType() const {
5120 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00005121 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00005122 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Richard Smithb2997f52019-05-21 20:10:50 +00005123 /*dependent*/false, /*pack*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00005124 0);
Richard Smith02e85f32011-04-14 22:09:26 +00005125 return AutoDeductTy;
5126}
5127
5128/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5129QualType ASTContext::getAutoRRefDeductType() const {
5130 if (AutoRRefDeductTy.isNull())
5131 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
5132 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5133 return AutoRRefDeductTy;
5134}
5135
Chris Lattnerfb072462007-01-23 05:45:31 +00005136/// getTagDeclType - Return the unique reference to the type for the
5137/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00005138QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00005139 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00005140 // FIXME: What is the design on getTagDeclType when it requires casting
5141 // away const? mutable?
5142 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00005143}
5144
Mike Stump11289f42009-09-09 15:08:12 +00005145/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5146/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5147/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00005148CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00005149 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00005150}
Chris Lattnerfb072462007-01-23 05:45:31 +00005151
Fangrui Song6907ce22018-07-30 19:24:48 +00005152/// Return the unique signed counterpart of the integer type
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00005153/// corresponding to size_t.
5154CanQualType ASTContext::getSignedSizeType() const {
5155 return getFromTargetType(Target->getSignedSizeType());
5156}
5157
Hans Wennborg27541db2011-10-27 08:29:09 +00005158/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5159CanQualType ASTContext::getIntMaxType() const {
5160 return getFromTargetType(Target->getIntMaxType());
5161}
5162
5163/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5164CanQualType ASTContext::getUIntMaxType() const {
5165 return getFromTargetType(Target->getUIntMaxType());
5166}
5167
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00005168/// getSignedWCharType - Return the type of "signed wchar_t".
5169/// Used when in C++, as a GCC extension.
5170QualType ASTContext::getSignedWCharType() const {
5171 // FIXME: derive from "Target" ?
5172 return WCharTy;
5173}
5174
5175/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5176/// Used when in C++, as a GCC extension.
5177QualType ASTContext::getUnsignedWCharType() const {
5178 // FIXME: derive from "Target" ?
5179 return UnsignedIntTy;
5180}
5181
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00005182QualType ASTContext::getIntPtrType() const {
5183 return getFromTargetType(Target->getIntPtrType());
5184}
5185
5186QualType ASTContext::getUIntPtrType() const {
5187 return getCorrespondingUnsignedType(getIntPtrType());
5188}
5189
Hans Wennborg27541db2011-10-27 08:29:09 +00005190/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005191/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5192QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00005193 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005194}
5195
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005196/// Return the unique unsigned counterpart of "ptrdiff_t"
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00005197/// integer type. The standard (C11 7.21.6.1p7) refers to this type
5198/// in the definition of %tu format specifier.
5199QualType ASTContext::getUnsignedPointerDiffType() const {
5200 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5201}
5202
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005203/// Return the unique type for "pid_t" defined in
Eli Friedman4e91899e2012-11-27 02:58:24 +00005204/// <sys/types.h>. We need this to compute the correct type for vfork().
5205QualType ASTContext::getProcessIDType() const {
5206 return getFromTargetType(Target->getProcessIDType());
5207}
5208
Chris Lattnera21ad802008-04-02 05:18:44 +00005209//===----------------------------------------------------------------------===//
5210// Type Operators
5211//===----------------------------------------------------------------------===//
5212
Jay Foad39c79802011-01-12 09:06:06 +00005213CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00005214 // Push qualifiers into arrays, and then discard any remaining
5215 // qualifiers.
5216 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00005217 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00005218 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00005219 QualType Result;
5220 if (isa<ArrayType>(Ty)) {
5221 Result = getArrayDecayedType(QualType(Ty,0));
5222 } else if (isa<FunctionType>(Ty)) {
5223 Result = getPointerType(QualType(Ty, 0));
5224 } else {
5225 Result = QualType(Ty, 0);
5226 }
5227
5228 return CanQualType::CreateUnsafe(Result);
5229}
5230
John McCall6c9dd522011-01-18 07:41:22 +00005231QualType ASTContext::getUnqualifiedArrayType(QualType type,
5232 Qualifiers &quals) {
5233 SplitQualType splitType = type.getSplitUnqualifiedType();
5234
5235 // FIXME: getSplitUnqualifiedType() actually walks all the way to
5236 // the unqualified desugared type and then drops it on the floor.
5237 // We then have to strip that sugar back off with
5238 // getUnqualifiedDesugaredType(), which is silly.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005239 const auto *AT =
5240 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00005241
5242 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005243 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00005244 quals = splitType.Quals;
5245 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005246 }
5247
John McCall6c9dd522011-01-18 07:41:22 +00005248 // Otherwise, recurse on the array's element type.
5249 QualType elementType = AT->getElementType();
5250 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5251
5252 // If that didn't change the element type, AT has no qualifiers, so we
5253 // can just use the results in splitType.
5254 if (elementType == unqualElementType) {
5255 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00005256 quals = splitType.Quals;
5257 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00005258 }
5259
5260 // Otherwise, add in the qualifiers from the outermost type, then
5261 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00005262 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005263
Eugene Zelenko7855e772018-04-03 00:11:50 +00005264 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005265 return getConstantArrayType(unqualElementType, CAT->getSize(),
Richard Smith772e2662019-10-04 01:25:59 +00005266 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005267 }
5268
Eugene Zelenko7855e772018-04-03 00:11:50 +00005269 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005270 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005271 }
5272
Eugene Zelenko7855e772018-04-03 00:11:50 +00005273 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005274 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00005275 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005276 VAT->getSizeModifier(),
5277 VAT->getIndexTypeCVRQualifiers(),
5278 VAT->getBracketsRange());
5279 }
5280
Eugene Zelenko7855e772018-04-03 00:11:50 +00005281 const auto *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00005282 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005283 DSAT->getSizeModifier(), 0,
5284 SourceRange());
5285}
5286
Richard Smitha3405ff2018-07-11 00:19:19 +00005287/// Attempt to unwrap two types that may both be array types with the same bound
5288/// (or both be array types of unknown bound) for the purpose of comparing the
5289/// cv-decomposition of two types per C++ [conv.qual].
Richard Smith5407d4f2018-07-18 20:13:36 +00005290bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5291 bool UnwrappedAny = false;
Richard Smitha3405ff2018-07-11 00:19:19 +00005292 while (true) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005293 auto *AT1 = getAsArrayType(T1);
5294 if (!AT1) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005295
Richard Smith5407d4f2018-07-18 20:13:36 +00005296 auto *AT2 = getAsArrayType(T2);
5297 if (!AT2) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005298
5299 // If we don't have two array types with the same constant bound nor two
5300 // incomplete array types, we've unwrapped everything we can.
5301 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5302 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5303 if (!CAT2 || CAT1->getSize() != CAT2->getSize())
Richard Smith5407d4f2018-07-18 20:13:36 +00005304 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005305 } else if (!isa<IncompleteArrayType>(AT1) ||
5306 !isa<IncompleteArrayType>(AT2)) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005307 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005308 }
5309
5310 T1 = AT1->getElementType();
5311 T2 = AT2->getElementType();
Richard Smith5407d4f2018-07-18 20:13:36 +00005312 UnwrappedAny = true;
Richard Smitha3405ff2018-07-11 00:19:19 +00005313 }
5314}
5315
5316/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5317///
5318/// If T1 and T2 are both pointer types of the same kind, or both array types
5319/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5320/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5321///
5322/// This function will typically be called in a loop that successively
5323/// "unwraps" pointer and pointer-to-member types to compare them at each
5324/// level.
5325///
5326/// \return \c true if a pointer type was unwrapped, \c false if we reached a
5327/// pair of types that can't be unwrapped further.
5328bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005329 UnwrapSimilarArrayTypes(T1, T2);
Richard Smitha3405ff2018-07-11 00:19:19 +00005330
Eugene Zelenko7855e772018-04-03 00:11:50 +00005331 const auto *T1PtrType = T1->getAs<PointerType>();
5332 const auto *T2PtrType = T2->getAs<PointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005333 if (T1PtrType && T2PtrType) {
5334 T1 = T1PtrType->getPointeeType();
5335 T2 = T2PtrType->getPointeeType();
5336 return true;
5337 }
Richard Smith5407d4f2018-07-18 20:13:36 +00005338
Eugene Zelenko7855e772018-04-03 00:11:50 +00005339 const auto *T1MPType = T1->getAs<MemberPointerType>();
5340 const auto *T2MPType = T2->getAs<MemberPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00005341 if (T1MPType && T2MPType &&
5342 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005343 QualType(T2MPType->getClass(), 0))) {
5344 T1 = T1MPType->getPointeeType();
5345 T2 = T2MPType->getPointeeType();
5346 return true;
5347 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005348
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005349 if (getLangOpts().ObjC) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005350 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5351 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005352 if (T1OPType && T2OPType) {
5353 T1 = T1OPType->getPointeeType();
5354 T2 = T2OPType->getPointeeType();
5355 return true;
5356 }
5357 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005358
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005359 // FIXME: Block pointers, too?
Fangrui Song6907ce22018-07-30 19:24:48 +00005360
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005361 return false;
5362}
5363
Richard Smitha3405ff2018-07-11 00:19:19 +00005364bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5365 while (true) {
5366 Qualifiers Quals;
5367 T1 = getUnqualifiedArrayType(T1, Quals);
5368 T2 = getUnqualifiedArrayType(T2, Quals);
5369 if (hasSameType(T1, T2))
5370 return true;
5371 if (!UnwrapSimilarTypes(T1, T2))
5372 return false;
5373 }
5374}
5375
5376bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5377 while (true) {
5378 Qualifiers Quals1, Quals2;
5379 T1 = getUnqualifiedArrayType(T1, Quals1);
5380 T2 = getUnqualifiedArrayType(T2, Quals2);
5381
5382 Quals1.removeCVRQualifiers();
5383 Quals2.removeCVRQualifiers();
5384 if (Quals1 != Quals2)
5385 return false;
5386
5387 if (hasSameType(T1, T2))
5388 return true;
5389
5390 if (!UnwrapSimilarTypes(T1, T2))
5391 return false;
5392 }
5393}
5394
Jay Foad39c79802011-01-12 09:06:06 +00005395DeclarationNameInfo
5396ASTContext::getNameForTemplate(TemplateName Name,
5397 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005398 switch (Name.getKind()) {
5399 case TemplateName::QualifiedTemplate:
5400 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005401 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00005402 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5403 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005404
John McCalld9dfe3a2011-06-30 08:33:18 +00005405 case TemplateName::OverloadedTemplate: {
5406 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5407 // DNInfo work in progress: CHECKME: what about DNLoc?
5408 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5409 }
5410
Richard Smithb23c5e82019-05-09 03:31:27 +00005411 case TemplateName::AssumedTemplate: {
5412 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5413 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5414 }
5415
John McCalld9dfe3a2011-06-30 08:33:18 +00005416 case TemplateName::DependentTemplate: {
5417 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005418 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00005419 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005420 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5421 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00005422 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005423 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5424 // DNInfo work in progress: FIXME: source locations?
5425 DeclarationNameLoc DNLoc;
5426 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5427 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5428 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00005429 }
5430 }
5431
John McCalld9dfe3a2011-06-30 08:33:18 +00005432 case TemplateName::SubstTemplateTemplateParm: {
5433 SubstTemplateTemplateParmStorage *subst
5434 = Name.getAsSubstTemplateTemplateParm();
5435 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5436 NameLoc);
5437 }
5438
5439 case TemplateName::SubstTemplateTemplateParmPack: {
5440 SubstTemplateTemplateParmPackStorage *subst
5441 = Name.getAsSubstTemplateTemplateParmPack();
5442 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5443 NameLoc);
5444 }
5445 }
5446
5447 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005448}
5449
Jay Foad39c79802011-01-12 09:06:06 +00005450TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005451 switch (Name.getKind()) {
5452 case TemplateName::QualifiedTemplate:
5453 case TemplateName::Template: {
5454 TemplateDecl *Template = Name.getAsTemplateDecl();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005455 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005456 Template = getCanonicalTemplateTemplateParmDecl(TTP);
Fangrui Song6907ce22018-07-30 19:24:48 +00005457
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005458 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005459 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005460 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005461
John McCalld9dfe3a2011-06-30 08:33:18 +00005462 case TemplateName::OverloadedTemplate:
Richard Smithb23c5e82019-05-09 03:31:27 +00005463 case TemplateName::AssumedTemplate:
5464 llvm_unreachable("cannot canonicalize unresolved template");
Mike Stump11289f42009-09-09 15:08:12 +00005465
John McCalld9dfe3a2011-06-30 08:33:18 +00005466 case TemplateName::DependentTemplate: {
5467 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5468 assert(DTN && "Non-dependent template names must refer to template decls.");
5469 return DTN->CanonicalTemplateName;
5470 }
5471
5472 case TemplateName::SubstTemplateTemplateParm: {
5473 SubstTemplateTemplateParmStorage *subst
5474 = Name.getAsSubstTemplateTemplateParm();
5475 return getCanonicalTemplateName(subst->getReplacement());
5476 }
5477
5478 case TemplateName::SubstTemplateTemplateParmPack: {
5479 SubstTemplateTemplateParmPackStorage *subst
5480 = Name.getAsSubstTemplateTemplateParmPack();
5481 TemplateTemplateParmDecl *canonParameter
5482 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5483 TemplateArgument canonArgPack
5484 = getCanonicalTemplateArgument(subst->getArgumentPack());
5485 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5486 }
5487 }
5488
5489 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005490}
5491
Douglas Gregoradee3e32009-11-11 23:06:43 +00005492bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5493 X = getCanonicalTemplateName(X);
5494 Y = getCanonicalTemplateName(Y);
5495 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5496}
5497
Mike Stump11289f42009-09-09 15:08:12 +00005498TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005499ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005500 switch (Arg.getKind()) {
5501 case TemplateArgument::Null:
5502 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005503
Douglas Gregora8e02e72009-07-28 23:00:59 +00005504 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005505 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005506
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005507 case TemplateArgument::Declaration: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005508 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005509 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005510 }
Mike Stump11289f42009-09-09 15:08:12 +00005511
Eli Friedmanb826a002012-09-26 02:36:12 +00005512 case TemplateArgument::NullPtr:
5513 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5514 /*isNullPtr*/true);
5515
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005516 case TemplateArgument::Template:
5517 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005518
5519 case TemplateArgument::TemplateExpansion:
5520 return TemplateArgument(getCanonicalTemplateName(
5521 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005522 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005523
Douglas Gregora8e02e72009-07-28 23:00:59 +00005524 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005525 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005526
Douglas Gregora8e02e72009-07-28 23:00:59 +00005527 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005528 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005529
Douglas Gregora8e02e72009-07-28 23:00:59 +00005530 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005531 if (Arg.pack_size() == 0)
5532 return Arg;
Fangrui Song6907ce22018-07-30 19:24:48 +00005533
Eugene Zelenko7855e772018-04-03 00:11:50 +00005534 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005535 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005536 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005537 AEnd = Arg.pack_end();
5538 A != AEnd; (void)++A, ++Idx)
5539 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005540
Benjamin Kramercce63472015-08-05 09:40:22 +00005541 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005542 }
5543 }
5544
5545 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005546 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005547}
5548
Douglas Gregor333489b2009-03-27 23:10:48 +00005549NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005550ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005551 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005552 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005553
5554 switch (NNS->getKind()) {
5555 case NestedNameSpecifier::Identifier:
5556 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005557 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005558 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5559 NNS->getAsIdentifier());
5560
5561 case NestedNameSpecifier::Namespace:
5562 // A namespace is canonical; build a nested-name-specifier with
5563 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005564 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005565 NNS->getAsNamespace()->getOriginalNamespace());
5566
5567 case NestedNameSpecifier::NamespaceAlias:
5568 // A namespace is canonical; build a nested-name-specifier with
5569 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005570 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005571 NNS->getAsNamespaceAlias()->getNamespace()
5572 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005573
5574 case NestedNameSpecifier::TypeSpec:
5575 case NestedNameSpecifier::TypeSpecWithTemplate: {
5576 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Fangrui Song6907ce22018-07-30 19:24:48 +00005577
Douglas Gregor3ade5702010-11-04 00:09:33 +00005578 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5579 // break it apart into its prefix and identifier, then reconsititute those
5580 // as the canonical nested-name-specifier. This is required to canonicalize
5581 // a dependent nested-name-specifier involving typedefs of dependent-name
5582 // types, e.g.,
5583 // typedef typename T::type T1;
5584 // typedef typename T1::type T2;
Eugene Zelenko7855e772018-04-03 00:11:50 +00005585 if (const auto *DNT = T->getAs<DependentNameType>())
Fangrui Song6907ce22018-07-30 19:24:48 +00005586 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005587 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005588
Eli Friedman5358a0a2012-03-03 04:09:56 +00005589 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5590 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5591 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005592 return NestedNameSpecifier::Create(*this, nullptr, false,
5593 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005594 }
5595
5596 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005597 case NestedNameSpecifier::Super:
5598 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005599 return NNS;
5600 }
5601
David Blaikie8a40f702012-01-17 06:56:22 +00005602 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005603}
5604
Jay Foad39c79802011-01-12 09:06:06 +00005605const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005606 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005607 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005608 // Handle the common positive case fast.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005609 if (const auto *AT = dyn_cast<ArrayType>(T))
Chris Lattner7adf0762008-08-04 07:31:14 +00005610 return AT;
5611 }
Mike Stump11289f42009-09-09 15:08:12 +00005612
John McCall8ccfcb52009-09-24 19:53:00 +00005613 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005614 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005615 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005616
John McCall8ccfcb52009-09-24 19:53:00 +00005617 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005618 // implements C99 6.7.3p8: "If the specification of an array type includes
5619 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005620
Chris Lattner7adf0762008-08-04 07:31:14 +00005621 // If we get here, we either have type qualifiers on the type, or we have
5622 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005623 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005624
John McCall33ddac02011-01-19 10:06:00 +00005625 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005626 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005627
Chris Lattner7adf0762008-08-04 07:31:14 +00005628 // If we have a simple case, just return now.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005629 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005630 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005631 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005632
Chris Lattner7adf0762008-08-04 07:31:14 +00005633 // Otherwise, we have an array and we have qualifiers on it. Push the
5634 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005635 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005636
Eugene Zelenko7855e772018-04-03 00:11:50 +00005637 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005638 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
Richard Smith772e2662019-10-04 01:25:59 +00005639 CAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005640 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005641 CAT->getIndexTypeCVRQualifiers()));
Eugene Zelenko7855e772018-04-03 00:11:50 +00005642 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005643 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5644 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005645 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005646
Eugene Zelenko7855e772018-04-03 00:11:50 +00005647 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
Douglas Gregor4619e432008-12-05 23:32:09 +00005648 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005649 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005650 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005651 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005652 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005653 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005654
Eugene Zelenko7855e772018-04-03 00:11:50 +00005655 const auto *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005656 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005657 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005658 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005659 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005660 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005661}
5662
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005663QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005664 if (T->isArrayType() || T->isFunctionType())
5665 return getDecayedType(T);
5666 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005667}
5668
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005669QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005670 T = getVariableArrayDecayedType(T);
5671 T = getAdjustedParameterType(T);
5672 return T.getUnqualifiedType();
5673}
5674
David Majnemerd09a51c2015-03-03 01:50:05 +00005675QualType ASTContext::getExceptionObjectType(QualType T) const {
5676 // C++ [except.throw]p3:
5677 // A throw-expression initializes a temporary object, called the exception
5678 // object, the type of which is determined by removing any top-level
5679 // cv-qualifiers from the static type of the operand of throw and adjusting
5680 // the type from "array of T" or "function returning T" to "pointer to T"
5681 // or "pointer to function returning T", [...]
5682 T = getVariableArrayDecayedType(T);
5683 if (T->isArrayType() || T->isFunctionType())
5684 T = getDecayedType(T);
5685 return T.getUnqualifiedType();
5686}
5687
Chris Lattnera21ad802008-04-02 05:18:44 +00005688/// getArrayDecayedType - Return the properly qualified result of decaying the
5689/// specified array type to a pointer. This operation is non-trivial when
5690/// handling typedefs etc. The canonical type of "T" must be an array type,
5691/// this returns a pointer to a properly qualified element of the array.
5692///
5693/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005694QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005695 // Get the element type with 'getAsArrayType' so that we don't lose any
5696 // typedefs in the element type of the array. This also handles propagation
5697 // of type qualifiers from the array type into the element type if present
5698 // (C99 6.7.3p8).
5699 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5700 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005701
Chris Lattner7adf0762008-08-04 07:31:14 +00005702 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005703
5704 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005705 QualType Result = getQualifiedType(PtrTy,
5706 PrettyArrayType->getIndexTypeQualifiers());
5707
5708 // int x[_Nullable] -> int * _Nullable
5709 if (auto Nullability = Ty->getNullability(*this)) {
5710 Result = const_cast<ASTContext *>(this)->getAttributedType(
5711 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5712 }
5713 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005714}
5715
John McCall33ddac02011-01-19 10:06:00 +00005716QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5717 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005718}
5719
John McCall33ddac02011-01-19 10:06:00 +00005720QualType ASTContext::getBaseElementType(QualType type) const {
5721 Qualifiers qs;
5722 while (true) {
5723 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005724 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005725 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005726
John McCall33ddac02011-01-19 10:06:00 +00005727 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005728 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005729 }
Mike Stump11289f42009-09-09 15:08:12 +00005730
John McCall33ddac02011-01-19 10:06:00 +00005731 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005732}
5733
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005734/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005735uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005736ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5737 uint64_t ElementCount = 1;
5738 do {
5739 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005740 CA = dyn_cast_or_null<ConstantArrayType>(
5741 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005742 } while (CA);
5743 return ElementCount;
5744}
5745
Steve Naroff0af91202007-04-27 21:51:21 +00005746/// getFloatingRank - Return a relative rank for floating point types.
5747/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005748static FloatingRank getFloatingRank(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005749 if (const auto *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005750 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005751
Simon Pilgrimeed4b122019-10-02 11:48:06 +00005752 switch (T->castAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005753 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005754 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005755 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005756 case BuiltinType::Float: return FloatRank;
5757 case BuiltinType::Double: return DoubleRank;
5758 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005759 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005760 }
5761}
5762
Mike Stump11289f42009-09-09 15:08:12 +00005763/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5764/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005765/// 'typeDomain' is a real floating point or complex type.
5766/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005767QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5768 QualType Domain) const {
5769 FloatingRank EltRank = getFloatingRank(Size);
5770 if (Domain->isComplexType()) {
5771 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005772 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005773 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005774 case FloatRank: return FloatComplexTy;
5775 case DoubleRank: return DoubleComplexTy;
5776 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005777 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005778 }
Steve Naroff0af91202007-04-27 21:51:21 +00005779 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005780
5781 assert(Domain->isRealFloatingType() && "Unknown domain!");
5782 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005783 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005784 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005785 case FloatRank: return FloatTy;
5786 case DoubleRank: return DoubleTy;
5787 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005788 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005789 }
David Blaikief47fa302012-01-17 02:30:50 +00005790 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005791}
5792
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005793/// getFloatingTypeOrder - Compare the rank of the two specified floating
5794/// point types, ignoring the domain of the type (i.e. 'double' ==
5795/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005796/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005797int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005798 FloatingRank LHSR = getFloatingRank(LHS);
5799 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005800
Chris Lattnerb90739d2008-04-06 23:38:49 +00005801 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005802 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005803 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005804 return 1;
5805 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005806}
5807
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +00005808int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
5809 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
5810 return 0;
5811 return getFloatingTypeOrder(LHS, RHS);
5812}
5813
Chris Lattner76a00cf2008-04-06 22:59:24 +00005814/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5815/// routine will assert if passed a built-in type that isn't an integer or enum,
5816/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005817unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005818 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005819
Chris Lattner76a00cf2008-04-06 22:59:24 +00005820 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005821 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005822 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005823 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005824 case BuiltinType::Char_S:
5825 case BuiltinType::Char_U:
5826 case BuiltinType::SChar:
5827 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005828 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005829 case BuiltinType::Short:
5830 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005831 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005832 case BuiltinType::Int:
5833 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005834 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005835 case BuiltinType::Long:
5836 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005837 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005838 case BuiltinType::LongLong:
5839 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005840 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005841 case BuiltinType::Int128:
5842 case BuiltinType::UInt128:
5843 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005844 }
5845}
5846
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005847/// Whether this is a promotable bitfield reference according
Eli Friedman629ffb92009-08-20 04:21:42 +00005848/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5849///
5850/// \returns the type this bit-field will promote to, or NULL if no
5851/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005852QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005853 if (E->isTypeDependent() || E->isValueDependent())
Eugene Zelenko7855e772018-04-03 00:11:50 +00005854 return {};
Richard Smith5b571672014-09-24 23:55:00 +00005855
Richard Smithaadb2542018-06-28 21:17:55 +00005856 // C++ [conv.prom]p5:
5857 // If the bit-field has an enumerated type, it is treated as any other
5858 // value of that type for promotion purposes.
5859 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5860 return {};
5861
Richard Smith5b571672014-09-24 23:55:00 +00005862 // FIXME: We should not do this unless E->refersToBitField() is true. This
5863 // matters in C where getSourceBitField() will find bit-fields for various
5864 // cases where the source expression is not a bit-field designator.
5865
John McCalld25db7e2013-05-06 21:39:12 +00005866 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005867 if (!Field)
Eugene Zelenko7855e772018-04-03 00:11:50 +00005868 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005869
5870 QualType FT = Field->getType();
5871
Richard Smithcaf33902011-10-10 18:28:20 +00005872 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005873 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005874 // C++ [conv.prom]p5:
5875 // A prvalue for an integral bit-field can be converted to a prvalue of type
5876 // int if int can represent all the values of the bit-field; otherwise, it
5877 // can be converted to unsigned int if unsigned int can represent all the
5878 // values of the bit-field. If the bit-field is larger yet, no integral
5879 // promotion applies to it.
5880 // C11 6.3.1.1/2:
5881 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5882 // If an int can represent all values of the original type (as restricted by
5883 // the width, for a bit-field), the value is converted to an int; otherwise,
5884 // it is converted to an unsigned int.
5885 //
5886 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5887 // We perform that promotion here to match GCC and C++.
Richard Smithaadb2542018-06-28 21:17:55 +00005888 // FIXME: C does not permit promotion of an enum bit-field whose rank is
5889 // greater than that of 'int'. We perform that promotion to match GCC.
Eli Friedman629ffb92009-08-20 04:21:42 +00005890 if (BitWidth < IntSize)
5891 return IntTy;
5892
5893 if (BitWidth == IntSize)
5894 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5895
Richard Smithaadb2542018-06-28 21:17:55 +00005896 // Bit-fields wider than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005897 // like the base type. GCC has some weird bugs in this area that we
5898 // deliberately do not follow (GCC follows a pre-standard resolution to
5899 // C's DR315 which treats bit-width as being part of the type, and this leaks
5900 // into their semantics in some cases).
Eugene Zelenko7855e772018-04-03 00:11:50 +00005901 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005902}
5903
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005904/// getPromotedIntegerType - Returns the type that Promotable will
5905/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5906/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005907QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005908 assert(!Promotable.isNull());
5909 assert(Promotable->isPromotableIntegerType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005910 if (const auto *ET = Promotable->getAs<EnumType>())
John McCall56774992009-12-09 09:09:27 +00005911 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005912
Eugene Zelenko7855e772018-04-03 00:11:50 +00005913 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005914 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5915 // (3.9.1) can be converted to a prvalue of the first of the following
5916 // types that can represent all the values of its underlying type:
5917 // int, unsigned int, long int, unsigned long int, long long int, or
5918 // unsigned long long int [...]
5919 // FIXME: Is there some better way to compute this?
5920 if (BT->getKind() == BuiltinType::WChar_S ||
5921 BT->getKind() == BuiltinType::WChar_U ||
Richard Smith3a8244d2018-05-01 05:02:45 +00005922 BT->getKind() == BuiltinType::Char8 ||
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005923 BT->getKind() == BuiltinType::Char16 ||
5924 BT->getKind() == BuiltinType::Char32) {
5925 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5926 uint64_t FromSize = getTypeSize(BT);
5927 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5928 LongLongTy, UnsignedLongLongTy };
5929 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5930 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5931 if (FromSize < ToSize ||
5932 (FromSize == ToSize &&
5933 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5934 return PromoteTypes[Idx];
5935 }
5936 llvm_unreachable("char type should fit into long long");
5937 }
5938 }
5939
5940 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005941 if (Promotable->isSignedIntegerType())
5942 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005943 uint64_t PromotableSize = getIntWidth(Promotable);
5944 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005945 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5946 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5947}
5948
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005949/// Recurses in pointer/array types until it finds an objc retainable
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005950/// type and returns its ownership.
5951Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5952 while (!T.isNull()) {
5953 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5954 return T.getObjCLifetime();
5955 if (T->isArrayType())
5956 T = getBaseElementType(T);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005957 else if (const auto *PT = T->getAs<PointerType>())
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005958 T = PT->getPointeeType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005959 else if (const auto *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005960 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005961 else
5962 break;
5963 }
5964
5965 return Qualifiers::OCL_None;
5966}
5967
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005968static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5969 // Incomplete enum types are not treated as integer types.
5970 // FIXME: In C++, enum types are never integer types.
5971 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5972 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005973 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005974}
5975
Mike Stump11289f42009-09-09 15:08:12 +00005976/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005977/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005978/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005979int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005980 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5981 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005982
5983 // Unwrap enums to their underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005984 if (const auto *ET = dyn_cast<EnumType>(LHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005985 LHSC = getIntegerTypeForEnum(ET);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005986 if (const auto *ET = dyn_cast<EnumType>(RHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005987 RHSC = getIntegerTypeForEnum(ET);
5988
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005989 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005990
Chris Lattner76a00cf2008-04-06 22:59:24 +00005991 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5992 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005993
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005994 unsigned LHSRank = getIntegerRank(LHSC);
5995 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005996
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005997 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5998 if (LHSRank == RHSRank) return 0;
5999 return LHSRank > RHSRank ? 1 : -1;
6000 }
Mike Stump11289f42009-09-09 15:08:12 +00006001
Chris Lattnerd4bacd62008-04-06 23:55:33 +00006002 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
6003 if (LHSUnsigned) {
6004 // If the unsigned [LHS] type is larger, return it.
6005 if (LHSRank >= RHSRank)
6006 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00006007
Chris Lattnerd4bacd62008-04-06 23:55:33 +00006008 // If the signed type can represent all values of the unsigned type, it
6009 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00006010 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00006011 return -1;
6012 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00006013
Chris Lattnerd4bacd62008-04-06 23:55:33 +00006014 // If the unsigned [RHS] type is larger, return it.
6015 if (RHSRank >= LHSRank)
6016 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00006017
Chris Lattnerd4bacd62008-04-06 23:55:33 +00006018 // If the signed type can represent all values of the unsigned type, it
6019 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00006020 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00006021 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00006022}
Anders Carlsson98f07902007-08-17 05:31:46 +00006023
Ben Langmuirf5416742016-02-04 00:55:24 +00006024TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006025 if (CFConstantStringTypeDecl)
6026 return CFConstantStringTypeDecl;
Anders Carlsson6d417272009-11-14 21:45:58 +00006027
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006028 assert(!CFConstantStringTagDecl &&
6029 "tag and typedef should be initialized together");
6030 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
6031 CFConstantStringTagDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00006032
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00006033 struct {
6034 QualType Type;
6035 const char *Name;
6036 } Fields[5];
6037 unsigned Count = 0;
Mike Stump11289f42009-09-09 15:08:12 +00006038
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00006039 /// Objective-C ABI
6040 ///
6041 /// typedef struct __NSConstantString_tag {
Saleem Abdulrasool1f6c41f2018-10-27 06:12:52 +00006042 /// const int *isa;
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00006043 /// int flags;
6044 /// const char *str;
6045 /// long length;
6046 /// } __NSConstantString;
6047 ///
6048 /// Swift ABI (4.1, 4.2)
6049 ///
6050 /// typedef struct __NSConstantString_tag {
6051 /// uintptr_t _cfisa;
6052 /// uintptr_t _swift_rc;
6053 /// _Atomic(uint64_t) _cfinfoa;
6054 /// const char *_ptr;
6055 /// uint32_t _length;
6056 /// } __NSConstantString;
6057 ///
6058 /// Swift ABI (5.0)
6059 ///
6060 /// typedef struct __NSConstantString_tag {
6061 /// uintptr_t _cfisa;
6062 /// uintptr_t _swift_rc;
6063 /// _Atomic(uint64_t) _cfinfoa;
6064 /// const char *_ptr;
6065 /// uintptr_t _length;
6066 /// } __NSConstantString;
6067
6068 const auto CFRuntime = getLangOpts().CFRuntime;
6069 if (static_cast<unsigned>(CFRuntime) <
6070 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
6071 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
6072 Fields[Count++] = { IntTy, "flags" };
6073 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
6074 Fields[Count++] = { LongTy, "length" };
6075 } else {
6076 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
6077 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
6078 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
6079 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
6080 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
6081 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
6082 Fields[Count++] = { IntTy, "_ptr" };
6083 else
6084 Fields[Count++] = { getUIntPtrType(), "_ptr" };
6085 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006086
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006087 // Create fields
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00006088 for (unsigned i = 0; i < Count; ++i) {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006089 FieldDecl *Field =
6090 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00006091 SourceLocation(), &Idents.get(Fields[i].Name),
6092 Fields[i].Type, /*TInfo=*/nullptr,
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006093 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6094 Field->setAccess(AS_public);
6095 CFConstantStringTagDecl->addDecl(Field);
Anders Carlsson98f07902007-08-17 05:31:46 +00006096 }
Mike Stump11289f42009-09-09 15:08:12 +00006097
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006098 CFConstantStringTagDecl->completeDefinition();
6099 // This type is designed to be compatible with NSConstantString, but cannot
6100 // use the same name, since NSConstantString is an interface.
6101 auto tagType = getTagDeclType(CFConstantStringTagDecl);
6102 CFConstantStringTypeDecl =
6103 buildImplicitTypedef(tagType, "__NSConstantString");
6104
Quentin Colombet043406b2016-02-03 22:41:00 +00006105 return CFConstantStringTypeDecl;
6106}
6107
Ben Langmuirf5416742016-02-04 00:55:24 +00006108RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
6109 if (!CFConstantStringTagDecl)
6110 getCFConstantStringDecl(); // Build the tag and the typedef.
6111 return CFConstantStringTagDecl;
6112}
6113
Quentin Colombet043406b2016-02-03 22:41:00 +00006114// getCFConstantStringType - Return the type used for constant CFStrings.
6115QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00006116 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00006117}
Anders Carlsson87c149b2007-10-11 01:00:40 +00006118
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00006119QualType ASTContext::getObjCSuperType() const {
6120 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006121 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00006122 TUDecl->addDecl(ObjCSuperTypeDecl);
6123 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
6124 }
6125 return ObjCSuperType;
6126}
6127
Douglas Gregor512b0772009-04-23 22:29:11 +00006128void ASTContext::setCFConstantStringType(QualType T) {
Simon Pilgrim9588ae72019-10-03 21:47:42 +00006129 const auto *TD = T->castAs<TypedefType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00006130 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
Eugene Zelenko7855e772018-04-03 00:11:50 +00006131 const auto *TagType =
Simon Pilgrim9588ae72019-10-03 21:47:42 +00006132 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00006133 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00006134}
6135
Jay Foad39c79802011-01-12 09:06:06 +00006136QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00006137 if (BlockDescriptorType)
6138 return getTagDeclType(BlockDescriptorType);
6139
Alp Toker2dea15b2013-12-17 01:22:38 +00006140 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00006141 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00006142 RD = buildImplicitRecord("__block_descriptor");
6143 RD->startDefinition();
6144
Mike Stumpd0153282009-10-20 02:12:22 +00006145 QualType FieldTypes[] = {
6146 UnsignedLongTy,
6147 UnsignedLongTy,
6148 };
6149
Craig Topperd6d31ac2013-07-15 08:24:27 +00006150 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00006151 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006152 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00006153 };
6154
6155 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006156 FieldDecl *Field = FieldDecl::Create(
6157 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00006158 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6159 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00006160 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006161 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00006162 }
6163
Alp Toker2dea15b2013-12-17 01:22:38 +00006164 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00006165
Alp Toker2dea15b2013-12-17 01:22:38 +00006166 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00006167
6168 return getTagDeclType(BlockDescriptorType);
6169}
6170
Jay Foad39c79802011-01-12 09:06:06 +00006171QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006172 if (BlockDescriptorExtendedType)
6173 return getTagDeclType(BlockDescriptorExtendedType);
6174
Alp Toker2dea15b2013-12-17 01:22:38 +00006175 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006176 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00006177 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6178 RD->startDefinition();
6179
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006180 QualType FieldTypes[] = {
6181 UnsignedLongTy,
6182 UnsignedLongTy,
6183 getPointerType(VoidPtrTy),
6184 getPointerType(VoidPtrTy)
6185 };
6186
Craig Topperd6d31ac2013-07-15 08:24:27 +00006187 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006188 "reserved",
6189 "Size",
6190 "CopyFuncPtr",
6191 "DestroyFuncPtr"
6192 };
6193
6194 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006195 FieldDecl *Field = FieldDecl::Create(
6196 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00006197 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6198 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00006199 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00006200 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006201 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006202 }
6203
Alp Toker2dea15b2013-12-17 01:22:38 +00006204 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006205
Alp Toker2dea15b2013-12-17 01:22:38 +00006206 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006207 return getTagDeclType(BlockDescriptorExtendedType);
6208}
6209
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006210TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006211 const auto *BT = dyn_cast<BuiltinType>(T);
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006212
6213 if (!BT) {
6214 if (isa<PipeType>(T))
6215 return TargetInfo::OCLTK_Pipe;
6216
6217 return TargetInfo::OCLTK_Default;
6218 }
6219
6220 switch (BT->getKind()) {
6221#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6222 case BuiltinType::Id: \
6223 return TargetInfo::OCLTK_Image;
6224#include "clang/Basic/OpenCLImageTypes.def"
6225
6226 case BuiltinType::OCLClkEvent:
6227 return TargetInfo::OCLTK_ClkEvent;
6228
6229 case BuiltinType::OCLEvent:
6230 return TargetInfo::OCLTK_Event;
6231
6232 case BuiltinType::OCLQueue:
6233 return TargetInfo::OCLTK_Queue;
6234
6235 case BuiltinType::OCLReserveID:
6236 return TargetInfo::OCLTK_ReserveID;
6237
6238 case BuiltinType::OCLSampler:
6239 return TargetInfo::OCLTK_Sampler;
6240
6241 default:
6242 return TargetInfo::OCLTK_Default;
6243 }
6244}
6245
6246LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6247 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6248}
6249
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006250/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6251/// requires copy/dispose. Note that this must match the logic
6252/// in buildByrefHelpers.
6253bool ASTContext::BlockRequiresCopying(QualType Ty,
6254 const VarDecl *D) {
6255 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00006256 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006257 if (!copyExpr && record->hasTrivialDestructor()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006258
Mike Stump94967902009-10-21 18:16:27 +00006259 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00006260 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006261
Akira Hatanaka7275da02018-02-28 07:15:55 +00006262 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6263 // move or destroy.
6264 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6265 return true;
6266
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006267 if (!Ty->isObjCRetainableType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006268
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006269 Qualifiers qs = Ty.getQualifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00006270
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006271 // If we have lifetime, that dominates.
6272 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006273 switch (lifetime) {
6274 case Qualifiers::OCL_None: llvm_unreachable("impossible");
Fangrui Song6907ce22018-07-30 19:24:48 +00006275
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006276 // These are just bits as far as the runtime is concerned.
6277 case Qualifiers::OCL_ExplicitNone:
6278 case Qualifiers::OCL_Autoreleasing:
6279 return false;
Akira Hatanaka7275da02018-02-28 07:15:55 +00006280
6281 // These cases should have been taken care of when checking the type's
6282 // non-triviality.
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006283 case Qualifiers::OCL_Weak:
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006284 case Qualifiers::OCL_Strong:
Akira Hatanaka7275da02018-02-28 07:15:55 +00006285 llvm_unreachable("impossible");
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006286 }
6287 llvm_unreachable("fell out of lifetime switch!");
6288 }
6289 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6290 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00006291}
6292
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006293bool ASTContext::getByrefLifetime(QualType Ty,
6294 Qualifiers::ObjCLifetime &LifeTime,
6295 bool &HasByrefExtendedLayout) const {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00006296 if (!getLangOpts().ObjC ||
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006297 getLangOpts().getGC() != LangOptions::NonGC)
6298 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006299
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006300 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00006301 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006302 HasByrefExtendedLayout = true;
6303 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006304 } else if ((LifeTime = Ty.getObjCLifetime())) {
6305 // Honor the ARC qualifiers.
6306 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6307 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006308 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00006309 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006310 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006311 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006312 return true;
6313}
6314
Douglas Gregorbab8a962011-09-08 01:46:34 +00006315TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6316 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00006317 ObjCInstanceTypeDecl =
6318 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00006319 return ObjCInstanceTypeDecl;
6320}
6321
Anders Carlsson18acd442007-10-29 06:33:42 +00006322// This returns true if a type has been typedefed to BOOL:
6323// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00006324static bool isTypeTypedefedAsBOOL(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006325 if (const auto *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00006326 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6327 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00006328
Anders Carlssond8499822007-10-29 05:01:08 +00006329 return false;
6330}
6331
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006332/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006333/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00006334CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00006335 if (!type->isIncompleteArrayType() && type->isIncompleteType())
6336 return CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +00006337
Ken Dyck40775002010-01-11 17:06:35 +00006338 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00006339
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006340 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00006341 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00006342 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006343 // Treat arrays as pointers, since that's how they're passed in.
6344 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00006345 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00006346 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00006347}
6348
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006349bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00006350 return getTargetInfo().getCXXABI().isMicrosoft() &&
6351 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00006352 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00006353 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006354}
6355
Richard Smithd9b90092016-07-02 01:32:16 +00006356ASTContext::InlineVariableDefinitionKind
6357ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6358 if (!VD->isInline())
6359 return InlineVariableDefinitionKind::None;
6360
6361 // In almost all cases, it's a weak definition.
6362 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00006363 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00006364 return InlineVariableDefinitionKind::Weak;
6365
6366 // If there's a file-context declaration in this translation unit, it's a
6367 // non-discardable definition.
6368 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00006369 if (D->getLexicalDeclContext()->isFileContext() &&
6370 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00006371 return InlineVariableDefinitionKind::Strong;
6372
6373 // If we've not seen one yet, we don't know.
6374 return InlineVariableDefinitionKind::WeakUnknown;
6375}
6376
Eugene Zelenko7855e772018-04-03 00:11:50 +00006377static std::string charUnitsToString(const CharUnits &CU) {
Ken Dyck40775002010-01-11 17:06:35 +00006378 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006379}
6380
John McCall351762c2011-02-07 10:33:21 +00006381/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00006382/// declaration.
John McCall351762c2011-02-07 10:33:21 +00006383std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6384 std::string S;
6385
David Chisnall950a9512009-11-17 19:33:30 +00006386 const BlockDecl *Decl = Expr->getBlockDecl();
6387 QualType BlockTy =
Simon Pilgrimeed4b122019-10-02 11:48:06 +00006388 Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
6389 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
David Chisnall950a9512009-11-17 19:33:30 +00006390 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006391 if (getLangOpts().EncodeExtendedBlockSig)
Simon Pilgrimeed4b122019-10-02 11:48:06 +00006392 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
6393 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006394 else
Simon Pilgrimeed4b122019-10-02 11:48:06 +00006395 getObjCEncodingForType(BlockReturnTy, S);
David Chisnall950a9512009-11-17 19:33:30 +00006396 // Compute size of all parameters.
6397 // Start with computing size of a pointer in number of bytes.
6398 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006399 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6400 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006401 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00006402 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006403 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00006404 if (sz.isZero())
6405 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006406 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00006407 ParmOffset += sz;
6408 }
6409 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00006410 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00006411 // Block pointer and offset.
6412 S += "@?0";
Fangrui Song6907ce22018-07-30 19:24:48 +00006413
David Chisnall950a9512009-11-17 19:33:30 +00006414 // Argument types.
6415 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006416 for (auto PVDecl : Decl->parameters()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006417 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006418 if (const auto *AT =
6419 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall950a9512009-11-17 19:33:30 +00006420 // Use array's original type only if it has known number of
6421 // elements.
6422 if (!isa<ConstantArrayType>(AT))
6423 PType = PVDecl->getType();
6424 } else if (PType->isFunctionType())
6425 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006426 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006427 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6428 S, true /*Extended*/);
6429 else
6430 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00006431 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006432 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00006433 }
John McCall351762c2011-02-07 10:33:21 +00006434
6435 return S;
David Chisnall950a9512009-11-17 19:33:30 +00006436}
6437
John McCall843dfcc2016-11-29 21:57:00 +00006438std::string
6439ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6440 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006441 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00006442 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00006443 CharUnits ParmOffset;
6444 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00006445 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00006446 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00006447 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006448 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006449 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006450
6451 assert(sz.isPositive() &&
John McCall843dfcc2016-11-29 21:57:00 +00006452 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00006453 ParmOffset += sz;
6454 }
6455 S += charUnitsToString(ParmOffset);
6456 ParmOffset = CharUnits::Zero();
6457
6458 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00006459 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006460 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006461 if (const auto *AT =
6462 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006463 // Use array's original type only if it has known number of
6464 // elements.
6465 if (!isa<ConstantArrayType>(AT))
6466 PType = PVDecl->getType();
6467 } else if (PType->isFunctionType())
6468 PType = PVDecl->getType();
6469 getObjCEncodingForType(PType, S);
6470 S += charUnitsToString(ParmOffset);
6471 ParmOffset += getObjCEncodingTypeSize(PType);
6472 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006473
John McCall843dfcc2016-11-29 21:57:00 +00006474 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006475}
6476
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006477/// getObjCEncodingForMethodParameter - Return the encoded type for a single
Fangrui Song6907ce22018-07-30 19:24:48 +00006478/// method parameter or return type. If Extended, include class names and
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006479/// block object types.
6480void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6481 QualType T, std::string& S,
6482 bool Extended) const {
6483 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6484 getObjCEncodingForTypeQualifier(QT, S);
6485 // Encode parameter type.
Nico Weber2e9591c2019-05-14 12:32:37 +00006486 ObjCEncOptions Options = ObjCEncOptions()
6487 .setExpandPointedToStructures()
6488 .setExpandStructures()
6489 .setIsOutermostType();
6490 if (Extended)
6491 Options.setEncodeBlockParameters().setEncodeClassNames();
6492 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006493}
6494
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006495/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006496/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00006497std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6498 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006499 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006500 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006501 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006502 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6503 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006504 // Compute size of all parameters.
6505 // Start with computing size of a pointer in number of bytes.
6506 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006507 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006508 // The first two arguments (self and _cmd) are pointers; account for
6509 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006510 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006511 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006512 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006513 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006514 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006515 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006516 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006517
6518 assert(sz.isPositive() &&
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006519 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006520 ParmOffset += sz;
6521 }
Ken Dyck40775002010-01-11 17:06:35 +00006522 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006523 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006524 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006525
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006526 // Argument types.
6527 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006528 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006529 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006530 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006531 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006532 if (const auto *AT =
6533 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
Steve Naroffe4e55d22009-04-14 00:03:58 +00006534 // Use array's original type only if it has known number of
6535 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006536 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006537 PType = PVDecl->getType();
6538 } else if (PType->isFunctionType())
6539 PType = PVDecl->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00006540 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006541 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006542 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006543 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006544 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006545
John McCall843dfcc2016-11-29 21:57:00 +00006546 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006547}
6548
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006549ObjCPropertyImplDecl *
6550ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6551 const ObjCPropertyDecl *PD,
6552 const Decl *Container) const {
6553 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006554 return nullptr;
Eugene Zelenko7855e772018-04-03 00:11:50 +00006555 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006556 for (auto *PID : CID->property_impls())
6557 if (PID->getPropertyDecl() == PD)
6558 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006559 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006560 const auto *OID = cast<ObjCImplementationDecl>(Container);
Craig Topper36250ad2014-05-12 05:36:57 +00006561 for (auto *PID : OID->property_impls())
6562 if (PID->getPropertyDecl() == PD)
6563 return PID;
6564 }
6565 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006566}
6567
Daniel Dunbar4932b362008-08-28 04:38:10 +00006568/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006569/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006570/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6571/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006572/// Property attributes are stored as a comma-delimited C string. The simple
6573/// attributes readonly and bycopy are encoded as single characters. The
6574/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6575/// encoded as single characters, followed by an identifier. Property types
6576/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006577/// these attributes are defined by the following enumeration:
6578/// @code
6579/// enum PropertyAttributes {
6580/// kPropertyReadOnly = 'R', // property is read-only.
6581/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6582/// kPropertyByref = '&', // property is a reference to the value last assigned
6583/// kPropertyDynamic = 'D', // property is dynamic
6584/// kPropertyGetter = 'G', // followed by getter selector name
6585/// kPropertySetter = 'S', // followed by setter selector name
6586/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006587/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006588/// kPropertyWeak = 'W' // 'weak' property
6589/// kPropertyStrong = 'P' // property GC'able
6590/// kPropertyNonAtomic = 'N' // property non-atomic
6591/// };
6592/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006593std::string
6594ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6595 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006596 // Collect information from the property implementation decl(s).
6597 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006598 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006599
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006600 if (ObjCPropertyImplDecl *PropertyImpDecl =
6601 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6602 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6603 Dynamic = true;
6604 else
6605 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006606 }
6607
6608 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006609 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006610
6611 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006612 // GCC has some special rules regarding encoding of properties which
6613 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006614 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006615
6616 if (PD->isReadOnly()) {
6617 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006618 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6619 S += ",C";
6620 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6621 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006622 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6623 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006624 } else {
6625 switch (PD->getSetterKind()) {
6626 case ObjCPropertyDecl::Assign: break;
6627 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006628 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006629 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006630 }
6631 }
6632
6633 // It really isn't clear at all what this means, since properties
6634 // are "dynamic by default".
6635 if (Dynamic)
6636 S += ",D";
6637
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006638 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6639 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006640
Daniel Dunbar4932b362008-08-28 04:38:10 +00006641 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6642 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006643 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006644 }
6645
6646 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6647 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006648 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006649 }
6650
6651 if (SynthesizePID) {
6652 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6653 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006654 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006655 }
6656
6657 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006658 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006659}
6660
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006661/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006662/// Another legacy compatibility encoding: 32-bit longs are encoded as
6663/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006664/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006665void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006666 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006667 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006668 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006669 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006670 else
Jay Foad39c79802011-01-12 09:06:06 +00006671 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006672 PointeeTy = IntTy;
6673 }
6674 }
6675}
6676
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006677void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006678 const FieldDecl *Field,
6679 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006680 // We follow the behavior of gcc, expanding structures which are
6681 // directly pointed to, and expanding embedded structures. Note that
6682 // these rules are sufficient to prevent recursive encoding of the
6683 // same type.
Nico Weber2e9591c2019-05-14 12:32:37 +00006684 getObjCEncodingForTypeImpl(T, S,
6685 ObjCEncOptions()
6686 .setExpandPointedToStructures()
6687 .setExpandStructures()
6688 .setIsOutermostType(),
6689 Field, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006690}
6691
Joe Groff98ac7d22014-07-07 22:25:15 +00006692void ASTContext::getObjCEncodingForPropertyType(QualType T,
6693 std::string& S) const {
6694 // Encode result type.
6695 // GCC has some special rules regarding encoding of properties which
6696 // closely resembles encoding of ivars.
Nico Weber2e9591c2019-05-14 12:32:37 +00006697 getObjCEncodingForTypeImpl(T, S,
6698 ObjCEncOptions()
6699 .setExpandPointedToStructures()
6700 .setExpandStructures()
6701 .setIsOutermostType()
6702 .setEncodingProperty(),
6703 /*Field=*/nullptr);
Joe Groff98ac7d22014-07-07 22:25:15 +00006704}
6705
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006706static char getObjCEncodingForPrimitiveType(const ASTContext *C,
6707 const BuiltinType *BT) {
6708 BuiltinType::Kind kind = BT->getKind();
John McCall393a78d2012-12-20 02:45:14 +00006709 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006710 case BuiltinType::Void: return 'v';
6711 case BuiltinType::Bool: return 'B';
Richard Smith3a8244d2018-05-01 05:02:45 +00006712 case BuiltinType::Char8:
David Chisnallb190a2c2010-06-04 01:10:52 +00006713 case BuiltinType::Char_U:
6714 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006715 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006716 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006717 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006718 case BuiltinType::UInt: return 'I';
6719 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006720 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006721 case BuiltinType::UInt128: return 'T';
6722 case BuiltinType::ULongLong: return 'Q';
6723 case BuiltinType::Char_S:
6724 case BuiltinType::SChar: return 'c';
6725 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006726 case BuiltinType::WChar_S:
6727 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006728 case BuiltinType::Int: return 'i';
6729 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006730 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006731 case BuiltinType::LongLong: return 'q';
6732 case BuiltinType::Int128: return 't';
6733 case BuiltinType::Float: return 'f';
6734 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006735 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006736 case BuiltinType::NullPtr: return '*'; // like char*
6737
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006738 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006739 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006740 case BuiltinType::Half:
Leonard Chanf921d852018-06-04 16:07:52 +00006741 case BuiltinType::ShortAccum:
6742 case BuiltinType::Accum:
6743 case BuiltinType::LongAccum:
6744 case BuiltinType::UShortAccum:
6745 case BuiltinType::UAccum:
6746 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00006747 case BuiltinType::ShortFract:
6748 case BuiltinType::Fract:
6749 case BuiltinType::LongFract:
6750 case BuiltinType::UShortFract:
6751 case BuiltinType::UFract:
6752 case BuiltinType::ULongFract:
6753 case BuiltinType::SatShortAccum:
6754 case BuiltinType::SatAccum:
6755 case BuiltinType::SatLongAccum:
6756 case BuiltinType::SatUShortAccum:
6757 case BuiltinType::SatUAccum:
6758 case BuiltinType::SatULongAccum:
6759 case BuiltinType::SatShortFract:
6760 case BuiltinType::SatFract:
6761 case BuiltinType::SatLongFract:
6762 case BuiltinType::SatUShortFract:
6763 case BuiltinType::SatUFract:
6764 case BuiltinType::SatULongFract:
John McCall393a78d2012-12-20 02:45:14 +00006765 // FIXME: potentially need @encodes for these!
6766 return ' ';
6767
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006768#define SVE_TYPE(Name, Id, SingletonId) \
6769 case BuiltinType::Id:
6770#include "clang/Basic/AArch64SVEACLETypes.def"
6771 {
6772 DiagnosticsEngine &Diags = C->getDiagnostics();
6773 unsigned DiagID = Diags.getCustomDiagID(
6774 DiagnosticsEngine::Error, "cannot yet @encode type %0");
6775 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
6776 return ' ';
6777 }
6778
John McCall393a78d2012-12-20 02:45:14 +00006779 case BuiltinType::ObjCId:
6780 case BuiltinType::ObjCClass:
6781 case BuiltinType::ObjCSel:
6782 llvm_unreachable("@encoding ObjC primitive type");
6783
6784 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006785#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6786 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006787#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00006788#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6789 case BuiltinType::Id:
6790#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006791 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006792 case BuiltinType::OCLClkEvent:
6793 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006794 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006795 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006796 case BuiltinType::Dependent:
6797#define BUILTIN_TYPE(KIND, ID)
6798#define PLACEHOLDER_TYPE(KIND, ID) \
6799 case BuiltinType::KIND:
6800#include "clang/AST/BuiltinTypes.def"
6801 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006802 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006803 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006804}
6805
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006806static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6807 EnumDecl *Enum = ET->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00006808
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006809 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6810 if (!Enum->isFixed())
6811 return 'i';
Fangrui Song6907ce22018-07-30 19:24:48 +00006812
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006813 // The encoding of a fixed enum type matches its fixed underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00006814 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006815 return getObjCEncodingForPrimitiveType(C, BT);
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006816}
6817
Jay Foad39c79802011-01-12 09:06:06 +00006818static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006819 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006820 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006821 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006822 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6823 // The GNU runtime requires more information; bitfields are encoded as b,
6824 // then the offset (in bits) of the first element, then the type of the
6825 // bitfield, then the size in bits. For example, in this structure:
6826 //
6827 // struct
6828 // {
6829 // int integer;
6830 // int flags:2;
6831 // };
6832 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6833 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6834 // information is not especially sensible, but we're stuck with it for
6835 // compatibility with GCC, although providing it breaks anything that
6836 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006837 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006838 uint64_t Offset;
6839
6840 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6841 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6842 IVD);
6843 } else {
6844 const RecordDecl *RD = FD->getParent();
6845 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6846 Offset = RL.getFieldOffset(FD->getFieldIndex());
6847 }
6848
6849 S += llvm::utostr(Offset);
6850
Eugene Zelenko7855e772018-04-03 00:11:50 +00006851 if (const auto *ET = T->getAs<EnumType>())
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006852 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006853 else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006854 const auto *BT = T->castAs<BuiltinType>();
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006855 S += getObjCEncodingForPrimitiveType(Ctx, BT);
John McCall393a78d2012-12-20 02:45:14 +00006856 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006857 }
Richard Smithcaf33902011-10-10 18:28:20 +00006858 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006859}
6860
Daniel Dunbar07d07852009-10-18 21:17:35 +00006861// FIXME: Use SmallString for accumulating string.
Nico Weber2e9591c2019-05-14 12:32:37 +00006862void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
6863 const ObjCEncOptions Options,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006864 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006865 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006866 CanQualType CT = getCanonicalType(T);
6867 switch (CT->getTypeClass()) {
6868 case Type::Builtin:
6869 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006870 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006871 return EncodeBitField(this, S, T, FD);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006872 if (const auto *BT = dyn_cast<BuiltinType>(CT))
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006873 S += getObjCEncodingForPrimitiveType(this, BT);
John McCall393a78d2012-12-20 02:45:14 +00006874 else
6875 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006876 return;
Mike Stump11289f42009-09-09 15:08:12 +00006877
John McCall393a78d2012-12-20 02:45:14 +00006878 case Type::Complex: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006879 const auto *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006880 S += 'j';
Nico Weber2e9591c2019-05-14 12:32:37 +00006881 getObjCEncodingForTypeImpl(CT->getElementType(), S, ObjCEncOptions(),
6882 /*Field=*/nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006883 return;
6884 }
John McCall393a78d2012-12-20 02:45:14 +00006885
6886 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006887 const auto *AT = T->castAs<AtomicType>();
John McCall393a78d2012-12-20 02:45:14 +00006888 S += 'A';
Nico Weber2e9591c2019-05-14 12:32:37 +00006889 getObjCEncodingForTypeImpl(AT->getValueType(), S, ObjCEncOptions(),
6890 /*Field=*/nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006891 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006892 }
John McCall393a78d2012-12-20 02:45:14 +00006893
6894 // encoding for pointer or reference types.
6895 case Type::Pointer:
6896 case Type::LValueReference:
6897 case Type::RValueReference: {
6898 QualType PointeeTy;
6899 if (isa<PointerType>(CT)) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006900 const auto *PT = T->castAs<PointerType>();
John McCall393a78d2012-12-20 02:45:14 +00006901 if (PT->isObjCSelType()) {
6902 S += ':';
6903 return;
6904 }
6905 PointeeTy = PT->getPointeeType();
6906 } else {
6907 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6908 }
6909
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006910 bool isReadOnly = false;
6911 // For historical/compatibility reasons, the read-only qualifier of the
6912 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6913 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006914 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006915 if (isa<TypedefType>(T.getTypePtr())) {
Nico Weber2e9591c2019-05-14 12:32:37 +00006916 if (Options.IsOutermostType() && T.isConstQualified()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006917 isReadOnly = true;
6918 S += 'r';
6919 }
Nico Weber2e9591c2019-05-14 12:32:37 +00006920 } else if (Options.IsOutermostType()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006921 QualType P = PointeeTy;
Simon Pilgrimd834f1f2019-10-03 15:08:20 +00006922 while (auto PT = P->getAs<PointerType>())
6923 P = PT->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006924 if (P.isConstQualified()) {
6925 isReadOnly = true;
6926 S += 'r';
6927 }
6928 }
6929 if (isReadOnly) {
6930 // Another legacy compatibility encoding. Some ObjC qualifier and type
6931 // combinations need to be rearranged.
6932 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006933 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006934 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006935 }
Mike Stump11289f42009-09-09 15:08:12 +00006936
Anders Carlssond8499822007-10-29 05:01:08 +00006937 if (PointeeTy->isCharType()) {
6938 // char pointer types should be encoded as '*' unless it is a
6939 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006940 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006941 S += '*';
6942 return;
6943 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00006944 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006945 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6946 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6947 S += '#';
6948 return;
6949 }
6950 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6951 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6952 S += '@';
6953 return;
6954 }
6955 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006956 }
Anders Carlssond8499822007-10-29 05:01:08 +00006957 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006958 getLegacyIntegralTypeEncoding(PointeeTy);
6959
Nico Weber2e9591c2019-05-14 12:32:37 +00006960 ObjCEncOptions NewOptions;
6961 if (Options.ExpandPointedToStructures())
6962 NewOptions.setExpandStructures();
6963 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
6964 /*Field=*/nullptr, NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006965 return;
6966 }
John McCall393a78d2012-12-20 02:45:14 +00006967
6968 case Type::ConstantArray:
6969 case Type::IncompleteArray:
6970 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006971 const auto *AT = cast<ArrayType>(CT);
John McCall393a78d2012-12-20 02:45:14 +00006972
Nico Weber2e9591c2019-05-14 12:32:37 +00006973 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006974 // Incomplete arrays are encoded as a pointer to the array element.
6975 S += '^';
6976
Nico Weber2e9591c2019-05-14 12:32:37 +00006977 getObjCEncodingForTypeImpl(
6978 AT->getElementType(), S,
6979 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006980 } else {
6981 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006982
Eugene Zelenko7855e772018-04-03 00:11:50 +00006983 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006984 S += llvm::utostr(CAT->getSize().getZExtValue());
6985 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006986 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006987 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6988 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006989 S += '0';
6990 }
Mike Stump11289f42009-09-09 15:08:12 +00006991
Nico Weberdf129332019-05-10 13:56:56 +00006992 getObjCEncodingForTypeImpl(
6993 AT->getElementType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00006994 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
6995 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006996 S += ']';
6997 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006998 return;
6999 }
Mike Stump11289f42009-09-09 15:08:12 +00007000
John McCall393a78d2012-12-20 02:45:14 +00007001 case Type::FunctionNoProto:
7002 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00007003 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00007004 return;
Mike Stump11289f42009-09-09 15:08:12 +00007005
John McCall393a78d2012-12-20 02:45:14 +00007006 case Type::Record: {
7007 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00007008 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00007009 // Anonymous structures print as '?'
7010 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
7011 S += II->getName();
Eugene Zelenko7855e772018-04-03 00:11:50 +00007012 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
Fariborz Jahanianc5158202010-05-07 00:28:49 +00007013 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00007014 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00007015 printTemplateArgumentList(OS, TemplateArgs.asArray(),
7016 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00007017 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00007018 } else {
7019 S += '?';
7020 }
Nico Weber2e9591c2019-05-14 12:32:37 +00007021 if (Options.ExpandStructures()) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00007022 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007023 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007024 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007025 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007026 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007027 if (FD) {
7028 S += '"';
7029 S += Field->getNameAsString();
7030 S += '"';
7031 }
Mike Stump11289f42009-09-09 15:08:12 +00007032
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007033 // Special case bit-fields.
7034 if (Field->isBitField()) {
Nico Weberdf129332019-05-10 13:56:56 +00007035 getObjCEncodingForTypeImpl(Field->getType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00007036 ObjCEncOptions().setExpandStructures(),
7037 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007038 } else {
7039 QualType qt = Field->getType();
7040 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00007041 getObjCEncodingForTypeImpl(
Nico Weber2e9591c2019-05-14 12:32:37 +00007042 qt, S,
7043 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
7044 NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007045 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00007046 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00007047 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00007048 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00007049 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00007050 return;
7051 }
Mike Stump11289f42009-09-09 15:08:12 +00007052
John McCall393a78d2012-12-20 02:45:14 +00007053 case Type::BlockPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007054 const auto *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00007055 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Nico Weber2e9591c2019-05-14 12:32:37 +00007056 if (Options.EncodeBlockParameters()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007057 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00007058
Bob Wilson5f4e3a72011-11-30 01:57:58 +00007059 S += '<';
7060 // Block return type
Nico Weber2e9591c2019-05-14 12:32:37 +00007061 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
7062 Options.forComponentType(), FD, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00007063 // Block self
7064 S += "@?";
7065 // Block parameters
Eugene Zelenko7855e772018-04-03 00:11:50 +00007066 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00007067 for (const auto &I : FPT->param_types())
Nico Weber2e9591c2019-05-14 12:32:37 +00007068 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
7069 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00007070 }
7071 S += '>';
7072 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00007073 return;
7074 }
Mike Stump11289f42009-09-09 15:08:12 +00007075
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00007076 case Type::ObjCObject: {
7077 // hack to match legacy encoding of *id and *Class
7078 QualType Ty = getObjCObjectPointerType(CT);
7079 if (Ty->isObjCIdType()) {
7080 S += "{objc_object=}";
7081 return;
7082 }
7083 else if (Ty->isObjCClassType()) {
7084 S += "{objc_class=}";
7085 return;
7086 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007087 // TODO: Double check to make sure this intentionally falls through.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00007088 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00007089 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007090
John McCall393a78d2012-12-20 02:45:14 +00007091 case Type::ObjCInterface: {
7092 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007093 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007094 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007095 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007096 S += OI->getObjCRuntimeNameAsString();
Nico Weber2e9591c2019-05-14 12:32:37 +00007097 if (Options.ExpandStructures()) {
Akira Hatanakafd0fb202016-08-17 19:42:22 +00007098 S += '=';
7099 SmallVector<const ObjCIvarDecl*, 32> Ivars;
7100 DeepCollectObjCIvars(OI, true, Ivars);
7101 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00007102 const FieldDecl *Field = Ivars[i];
Akira Hatanakafd0fb202016-08-17 19:42:22 +00007103 if (Field->isBitField())
Nico Weberdf129332019-05-10 13:56:56 +00007104 getObjCEncodingForTypeImpl(Field->getType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00007105 ObjCEncOptions().setExpandStructures(),
7106 Field);
Akira Hatanakaf3c89b12019-05-29 21:23:30 +00007107 else
7108 getObjCEncodingForTypeImpl(Field->getType(), S,
7109 ObjCEncOptions().setExpandStructures(), FD,
Nico Weber2e9591c2019-05-14 12:32:37 +00007110 NotEncodedT);
Akira Hatanakafd0fb202016-08-17 19:42:22 +00007111 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007112 }
7113 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00007114 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007115 }
Mike Stump11289f42009-09-09 15:08:12 +00007116
John McCall393a78d2012-12-20 02:45:14 +00007117 case Type::ObjCObjectPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007118 const auto *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007119 if (OPT->isObjCIdType()) {
7120 S += '@';
7121 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00007122 }
Mike Stump11289f42009-09-09 15:08:12 +00007123
Steve Narofff0c86112009-10-28 22:03:49 +00007124 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
7125 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
Nico Weberdf129332019-05-10 13:56:56 +00007126 // Since this is a binary compatibility issue, need to consult with
7127 // runtime folks. Fortunately, this is a *very* obscure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007128 S += '#';
7129 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00007130 }
Mike Stump11289f42009-09-09 15:08:12 +00007131
Chris Lattnere7cabb92009-07-13 00:10:46 +00007132 if (OPT->isObjCQualifiedIdType()) {
Nico Weber2e9591c2019-05-14 12:32:37 +00007133 getObjCEncodingForTypeImpl(
7134 getObjCIdType(), S,
7135 Options.keepingOnly(ObjCEncOptions()
7136 .setExpandPointedToStructures()
7137 .setExpandStructures()),
7138 FD);
7139 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00007140 // Note that we do extended encoding of protocol qualifer list
7141 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007142 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00007143 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00007144 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007145 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007146 S += '>';
7147 }
7148 S += '"';
7149 }
7150 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00007151 }
Mike Stump11289f42009-09-09 15:08:12 +00007152
Chris Lattnere7cabb92009-07-13 00:10:46 +00007153 S += '@';
Fangrui Song6907ce22018-07-30 19:24:48 +00007154 if (OPT->getInterfaceDecl() &&
Nico Weber2e9591c2019-05-14 12:32:37 +00007155 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00007156 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007157 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00007158 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00007159 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007160 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00007161 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00007162 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00007163 S += '"';
7164 }
7165 return;
7166 }
Mike Stump11289f42009-09-09 15:08:12 +00007167
John McCalla9e6e8d2010-05-17 23:56:34 +00007168 // gcc just blithely ignores member pointers.
Nico Weber2e9591c2019-05-14 12:32:37 +00007169 // FIXME: we should do better than that. 'M' is available.
John McCall393a78d2012-12-20 02:45:14 +00007170 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007171 // This matches gcc's encoding, even though technically it is insufficient.
7172 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00007173 case Type::Vector:
7174 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007175 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007176 if (NotEncodedT)
7177 *NotEncodedT = T;
7178 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00007179
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007180 // We could see an undeduced auto type here during error recovery.
7181 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00007182 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007183 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00007184 return;
7185
Xiuli Pan9c14e282016-01-09 12:53:17 +00007186 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00007187#define ABSTRACT_TYPE(KIND, BASE)
7188#define TYPE(KIND, BASE)
7189#define DEPENDENT_TYPE(KIND, BASE) \
7190 case Type::KIND:
7191#define NON_CANONICAL_TYPE(KIND, BASE) \
7192 case Type::KIND:
7193#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7194 case Type::KIND:
John McCall36b12a82019-10-02 06:35:23 +00007195#include "clang/AST/TypeNodes.inc"
John McCall393a78d2012-12-20 02:45:14 +00007196 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00007197 }
John McCall393a78d2012-12-20 02:45:14 +00007198 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00007199}
7200
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007201void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7202 std::string &S,
7203 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007204 bool includeVBases,
7205 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007206 assert(RDecl && "Expected non-null RecordDecl");
7207 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00007208 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007209 return;
7210
Eugene Zelenko7855e772018-04-03 00:11:50 +00007211 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007212 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7213 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7214
7215 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00007216 for (const auto &BI : CXXRec->bases()) {
7217 if (!BI.isVirtual()) {
7218 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007219 if (base->isEmpty())
7220 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007221 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007222 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7223 std::make_pair(offs, base));
7224 }
7225 }
7226 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007227
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007228 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00007229 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007230 uint64_t offs = layout.getFieldOffset(i);
7231 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00007232 std::make_pair(offs, Field));
7233 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007234 }
7235
7236 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00007237 for (const auto &BI : CXXRec->vbases()) {
7238 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007239 if (base->isEmpty())
7240 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007241 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00007242 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7243 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00007244 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7245 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007246 }
7247 }
7248
7249 CharUnits size;
7250 if (CXXRec) {
7251 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7252 } else {
7253 size = layout.getSize();
7254 }
7255
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007256#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007257 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007258#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007259 std::multimap<uint64_t, NamedDecl *>::iterator
7260 CurLayObj = FieldOrBaseOffsets.begin();
7261
Douglas Gregorf5d6c742012-04-27 22:30:01 +00007262 if (CXXRec && CXXRec->isDynamicClass() &&
7263 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007264 if (FD) {
7265 S += "\"_vptr$";
7266 std::string recname = CXXRec->getNameAsString();
7267 if (recname.empty()) recname = "?";
7268 S += recname;
7269 S += '"';
7270 }
7271 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007272#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007273 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007274#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007275 }
7276
7277 if (!RDecl->hasFlexibleArrayMember()) {
7278 // Mark the end of the structure.
7279 uint64_t offs = toBits(size);
7280 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00007281 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007282 }
7283
7284 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007285#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007286 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007287 if (CurOffs < CurLayObj->first) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007288 uint64_t padding = CurLayObj->first - CurOffs;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007289 // FIXME: There doesn't seem to be a way to indicate in the encoding that
7290 // packing/alignment of members is different that normal, in which case
7291 // the encoding will be out-of-sync with the real layout.
7292 // If the runtime switches to just consider the size of types without
7293 // taking into account alignment, we could make padding explicit in the
7294 // encoding (e.g. using arrays of chars). The encoding strings would be
7295 // longer then though.
7296 CurOffs += padding;
7297 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007298#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007299
7300 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00007301 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007302 break; // reached end of structure.
7303
Eugene Zelenko7855e772018-04-03 00:11:50 +00007304 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007305 // We expand the bases without their virtual bases since those are going
7306 // in the initial structure. Note that this differs from gcc which
7307 // expands virtual bases each time one is encountered in the hierarchy,
7308 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007309 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7310 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007311 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007312#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007313 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007314#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007315 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007316 const auto *field = cast<FieldDecl>(dcl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007317 if (FD) {
7318 S += '"';
7319 S += field->getNameAsString();
7320 S += '"';
7321 }
7322
7323 if (field->isBitField()) {
7324 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007325#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00007326 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007327#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007328 } else {
7329 QualType qt = field->getType();
7330 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00007331 getObjCEncodingForTypeImpl(
Nico Weber2e9591c2019-05-14 12:32:37 +00007332 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7333 FD, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007334#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007335 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007336#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007337 }
7338 }
7339 }
7340}
7341
Mike Stump11289f42009-09-09 15:08:12 +00007342void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00007343 std::string& S) const {
7344 if (QT & Decl::OBJC_TQ_In)
7345 S += 'n';
7346 if (QT & Decl::OBJC_TQ_Inout)
7347 S += 'N';
7348 if (QT & Decl::OBJC_TQ_Out)
7349 S += 'o';
7350 if (QT & Decl::OBJC_TQ_Bycopy)
7351 S += 'O';
7352 if (QT & Decl::OBJC_TQ_Byref)
7353 S += 'R';
7354 if (QT & Decl::OBJC_TQ_Oneway)
7355 S += 'V';
7356}
7357
Douglas Gregor3ea72692011-08-12 05:46:01 +00007358TypedefDecl *ASTContext::getObjCIdDecl() const {
7359 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007360 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00007361 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007362 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00007363 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00007364 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00007365}
7366
Douglas Gregor52e02802011-08-12 06:17:30 +00007367TypedefDecl *ASTContext::getObjCSelDecl() const {
7368 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007369 QualType T = getPointerType(ObjCBuiltinSelTy);
7370 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00007371 }
7372 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00007373}
7374
Douglas Gregor0a586182011-08-12 05:59:41 +00007375TypedefDecl *ASTContext::getObjCClassDecl() const {
7376 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007377 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00007378 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007379 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00007380 }
Douglas Gregor0a586182011-08-12 05:59:41 +00007381 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00007382}
7383
Douglas Gregord53ae832012-01-17 18:09:05 +00007384ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7385 if (!ObjCProtocolClassDecl) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007386 ObjCProtocolClassDecl
7387 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregord53ae832012-01-17 18:09:05 +00007388 SourceLocation(),
7389 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00007390 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00007391 /*PrevDecl=*/nullptr,
Fangrui Song6907ce22018-07-30 19:24:48 +00007392 SourceLocation(), true);
Douglas Gregord53ae832012-01-17 18:09:05 +00007393 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007394
Douglas Gregord53ae832012-01-17 18:09:05 +00007395 return ObjCProtocolClassDecl;
7396}
7397
Meador Inge5d3fb222012-06-16 03:34:49 +00007398//===----------------------------------------------------------------------===//
7399// __builtin_va_list Construction Functions
7400//===----------------------------------------------------------------------===//
7401
Charles Davisc7d5c942015-09-17 20:55:33 +00007402static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7403 StringRef Name) {
7404 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007405 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00007406 return Context->buildImplicitTypedef(T, Name);
7407}
7408
7409static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7410 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7411}
7412
7413static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7414 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007415}
7416
7417static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7418 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007419 QualType T = Context->getPointerType(Context->VoidTy);
7420 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007421}
7422
Tim Northover9bb857a2013-01-31 12:13:10 +00007423static TypedefDecl *
7424CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007425 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007426 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007427 if (Context->getLangOpts().CPlusPlus) {
7428 // namespace std { struct __va_list {
7429 NamespaceDecl *NS;
7430 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7431 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00007432 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00007433 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007434 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007435 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00007436 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00007437 }
7438
7439 VaListTagDecl->startDefinition();
7440
7441 const size_t NumFields = 5;
7442 QualType FieldTypes[NumFields];
7443 const char *FieldNames[NumFields];
7444
7445 // void *__stack;
7446 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7447 FieldNames[0] = "__stack";
7448
7449 // void *__gr_top;
7450 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7451 FieldNames[1] = "__gr_top";
7452
7453 // void *__vr_top;
7454 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7455 FieldNames[2] = "__vr_top";
7456
7457 // int __gr_offs;
7458 FieldTypes[3] = Context->IntTy;
7459 FieldNames[3] = "__gr_offs";
7460
7461 // int __vr_offs;
7462 FieldTypes[4] = Context->IntTy;
7463 FieldNames[4] = "__vr_offs";
7464
7465 // Create fields
7466 for (unsigned i = 0; i < NumFields; ++i) {
7467 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7468 VaListTagDecl,
7469 SourceLocation(),
7470 SourceLocation(),
7471 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007472 FieldTypes[i], /*TInfo=*/nullptr,
7473 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00007474 /*Mutable=*/false,
7475 ICIS_NoInit);
7476 Field->setAccess(AS_public);
7477 VaListTagDecl->addDecl(Field);
7478 }
7479 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007480 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00007481 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00007482
7483 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007484 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007485}
7486
Meador Inge5d3fb222012-06-16 03:34:49 +00007487static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7488 // typedef struct __va_list_tag {
7489 RecordDecl *VaListTagDecl;
7490
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 = 5;
7495 QualType FieldTypes[NumFields];
7496 const char *FieldNames[NumFields];
7497
7498 // unsigned char gpr;
7499 FieldTypes[0] = Context->UnsignedCharTy;
7500 FieldNames[0] = "gpr";
7501
7502 // unsigned char fpr;
7503 FieldTypes[1] = Context->UnsignedCharTy;
7504 FieldNames[1] = "fpr";
7505
7506 // unsigned short reserved;
7507 FieldTypes[2] = Context->UnsignedShortTy;
7508 FieldNames[2] = "reserved";
7509
7510 // void* overflow_arg_area;
7511 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7512 FieldNames[3] = "overflow_arg_area";
7513
7514 // void* reg_save_area;
7515 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7516 FieldNames[4] = "reg_save_area";
7517
7518 // Create fields
7519 for (unsigned i = 0; i < NumFields; ++i) {
7520 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7521 SourceLocation(),
7522 SourceLocation(),
7523 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007524 FieldTypes[i], /*TInfo=*/nullptr,
7525 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007526 /*Mutable=*/false,
7527 ICIS_NoInit);
7528 Field->setAccess(AS_public);
7529 VaListTagDecl->addDecl(Field);
7530 }
7531 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007532 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007533 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7534
7535 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007536 TypedefDecl *VaListTagTypedefDecl =
7537 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7538
Meador Inge5d3fb222012-06-16 03:34:49 +00007539 QualType VaListTagTypedefType =
7540 Context->getTypedefType(VaListTagTypedefDecl);
7541
7542 // typedef __va_list_tag __builtin_va_list[1];
7543 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7544 QualType VaListTagArrayType
7545 = Context->getConstantArrayType(VaListTagTypedefType,
Richard Smith772e2662019-10-04 01:25:59 +00007546 Size, nullptr, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007547 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007548}
7549
7550static TypedefDecl *
7551CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007552 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007553 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007554 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007555 VaListTagDecl->startDefinition();
7556
7557 const size_t NumFields = 4;
7558 QualType FieldTypes[NumFields];
7559 const char *FieldNames[NumFields];
7560
7561 // unsigned gp_offset;
7562 FieldTypes[0] = Context->UnsignedIntTy;
7563 FieldNames[0] = "gp_offset";
7564
7565 // unsigned fp_offset;
7566 FieldTypes[1] = Context->UnsignedIntTy;
7567 FieldNames[1] = "fp_offset";
7568
7569 // void* overflow_arg_area;
7570 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7571 FieldNames[2] = "overflow_arg_area";
7572
7573 // void* reg_save_area;
7574 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7575 FieldNames[3] = "reg_save_area";
7576
7577 // Create fields
7578 for (unsigned i = 0; i < NumFields; ++i) {
7579 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7580 VaListTagDecl,
7581 SourceLocation(),
7582 SourceLocation(),
7583 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007584 FieldTypes[i], /*TInfo=*/nullptr,
7585 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007586 /*Mutable=*/false,
7587 ICIS_NoInit);
7588 Field->setAccess(AS_public);
7589 VaListTagDecl->addDecl(Field);
7590 }
7591 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007592 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007593 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7594
Richard Smith9b88a4c2015-07-27 05:40:23 +00007595 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007596
Richard Smith9b88a4c2015-07-27 05:40:23 +00007597 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007598 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith772e2662019-10-04 01:25:59 +00007599 QualType VaListTagArrayType = Context->getConstantArrayType(
7600 VaListTagType, Size, nullptr, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007601 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007602}
7603
7604static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7605 // typedef int __builtin_va_list[4];
7606 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Richard Smith772e2662019-10-04 01:25:59 +00007607 QualType IntArrayType = Context->getConstantArrayType(
7608 Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007609 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007610}
7611
Logan Chien57086ce2012-10-10 06:56:20 +00007612static TypedefDecl *
7613CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007614 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007615 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007616 if (Context->getLangOpts().CPlusPlus) {
7617 // namespace std { struct __va_list {
7618 NamespaceDecl *NS;
7619 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7620 Context->getTranslationUnitDecl(),
7621 /*Inline*/false, SourceLocation(),
7622 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007623 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007624 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007625 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007626 }
7627
7628 VaListDecl->startDefinition();
7629
7630 // void * __ap;
7631 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7632 VaListDecl,
7633 SourceLocation(),
7634 SourceLocation(),
7635 &Context->Idents.get("__ap"),
7636 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007637 /*TInfo=*/nullptr,
7638 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007639 /*Mutable=*/false,
7640 ICIS_NoInit);
7641 Field->setAccess(AS_public);
7642 VaListDecl->addDecl(Field);
7643
7644 // };
7645 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007646 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007647
7648 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007649 QualType T = Context->getRecordType(VaListDecl);
7650 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007651}
7652
Ulrich Weigand47445072013-05-06 16:26:41 +00007653static TypedefDecl *
7654CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007655 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007656 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007657 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007658 VaListTagDecl->startDefinition();
7659
7660 const size_t NumFields = 4;
7661 QualType FieldTypes[NumFields];
7662 const char *FieldNames[NumFields];
7663
7664 // long __gpr;
7665 FieldTypes[0] = Context->LongTy;
7666 FieldNames[0] = "__gpr";
7667
7668 // long __fpr;
7669 FieldTypes[1] = Context->LongTy;
7670 FieldNames[1] = "__fpr";
7671
7672 // void *__overflow_arg_area;
7673 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7674 FieldNames[2] = "__overflow_arg_area";
7675
7676 // void *__reg_save_area;
7677 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7678 FieldNames[3] = "__reg_save_area";
7679
7680 // Create fields
7681 for (unsigned i = 0; i < NumFields; ++i) {
7682 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7683 VaListTagDecl,
7684 SourceLocation(),
7685 SourceLocation(),
7686 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007687 FieldTypes[i], /*TInfo=*/nullptr,
7688 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007689 /*Mutable=*/false,
7690 ICIS_NoInit);
7691 Field->setAccess(AS_public);
7692 VaListTagDecl->addDecl(Field);
7693 }
7694 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007695 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007696 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007697
Richard Smith9b88a4c2015-07-27 05:40:23 +00007698 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007699
7700 // typedef __va_list_tag __builtin_va_list[1];
7701 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith772e2662019-10-04 01:25:59 +00007702 QualType VaListTagArrayType = Context->getConstantArrayType(
7703 VaListTagType, Size, nullptr, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007704
Alp Toker56b5cc92013-12-15 10:36:26 +00007705 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007706}
7707
Meador Inge5d3fb222012-06-16 03:34:49 +00007708static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7709 TargetInfo::BuiltinVaListKind Kind) {
7710 switch (Kind) {
7711 case TargetInfo::CharPtrBuiltinVaList:
7712 return CreateCharPtrBuiltinVaListDecl(Context);
7713 case TargetInfo::VoidPtrBuiltinVaList:
7714 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007715 case TargetInfo::AArch64ABIBuiltinVaList:
7716 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007717 case TargetInfo::PowerABIBuiltinVaList:
7718 return CreatePowerABIBuiltinVaListDecl(Context);
7719 case TargetInfo::X86_64ABIBuiltinVaList:
7720 return CreateX86_64ABIBuiltinVaListDecl(Context);
7721 case TargetInfo::PNaClABIBuiltinVaList:
7722 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007723 case TargetInfo::AAPCSABIBuiltinVaList:
7724 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007725 case TargetInfo::SystemZBuiltinVaList:
7726 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007727 }
7728
7729 llvm_unreachable("Unhandled __builtin_va_list type kind");
7730}
7731
7732TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007733 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007734 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007735 assert(BuiltinVaListDecl->isImplicit());
7736 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007737
7738 return BuiltinVaListDecl;
7739}
7740
Richard Smith9b88a4c2015-07-27 05:40:23 +00007741Decl *ASTContext::getVaListTagDecl() const {
7742 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007743 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007744 if (!VaListTagDecl)
7745 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007746
Richard Smith9b88a4c2015-07-27 05:40:23 +00007747 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007748}
7749
Charles Davisc7d5c942015-09-17 20:55:33 +00007750TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7751 if (!BuiltinMSVaListDecl)
7752 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7753
7754 return BuiltinMSVaListDecl;
7755}
7756
Erich Keane41af9712018-04-16 21:30:08 +00007757bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
7758 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
7759}
7760
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007761void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007762 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007763 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007764
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007765 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007766}
7767
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007768/// Retrieve the template name that corresponds to a non-empty
John McCalld28ae272009-12-02 08:04:21 +00007769/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007770TemplateName
7771ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7772 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007773 unsigned size = End - Begin;
7774 assert(size > 1 && "set is not overloaded!");
7775
7776 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7777 size * sizeof(FunctionTemplateDecl*));
Eugene Zelenko7855e772018-04-03 00:11:50 +00007778 auto *OT = new (memory) OverloadedTemplateStorage(size);
John McCalld28ae272009-12-02 08:04:21 +00007779
7780 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007781 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007782 NamedDecl *D = *I;
7783 assert(isa<FunctionTemplateDecl>(D) ||
Richard Smithef53a3e2018-06-06 16:36:56 +00007784 isa<UnresolvedUsingValueDecl>(D) ||
John McCalld28ae272009-12-02 08:04:21 +00007785 (isa<UsingShadowDecl>(D) &&
7786 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7787 *Storage++ = D;
7788 }
7789
7790 return TemplateName(OT);
7791}
7792
Richard Smithb23c5e82019-05-09 03:31:27 +00007793/// Retrieve a template name representing an unqualified-id that has been
7794/// assumed to name a template for ADL purposes.
7795TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
7796 auto *OT = new (*this) AssumedTemplateStorage(Name);
7797 return TemplateName(OT);
7798}
7799
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007800/// Retrieve the template name that represents a qualified
Douglas Gregordc572a32009-03-30 22:58:21 +00007801/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007802TemplateName
7803ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7804 bool TemplateKeyword,
7805 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007806 assert(NNS && "Missing nested-name-specifier in qualified template name");
Fangrui Song6907ce22018-07-30 19:24:48 +00007807
Douglas Gregorc42075a2010-02-04 18:10:26 +00007808 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007809 llvm::FoldingSetNodeID ID;
7810 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7811
Craig Topper36250ad2014-05-12 05:36:57 +00007812 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007813 QualifiedTemplateName *QTN =
7814 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7815 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007816 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007817 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007818 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7819 }
7820
7821 return TemplateName(QTN);
7822}
7823
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007824/// Retrieve the template name that represents a dependent
Douglas Gregordc572a32009-03-30 22:58:21 +00007825/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007826TemplateName
7827ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7828 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007829 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007830 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007831
7832 llvm::FoldingSetNodeID ID;
7833 DependentTemplateName::Profile(ID, NNS, Name);
7834
Craig Topper36250ad2014-05-12 05:36:57 +00007835 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007836 DependentTemplateName *QTN =
7837 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7838
7839 if (QTN)
7840 return TemplateName(QTN);
7841
7842 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7843 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007844 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007845 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007846 } else {
7847 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007848 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007849 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007850 DependentTemplateName *CheckQTN =
7851 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7852 assert(!CheckQTN && "Dependent type name canonicalization broken");
7853 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007854 }
7855
7856 DependentTemplateNames.InsertNode(QTN, InsertPos);
7857 return TemplateName(QTN);
7858}
7859
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007860/// Retrieve the template name that represents a dependent
Douglas Gregor71395fa2009-11-04 00:56:37 +00007861/// template name such as \c MetaFun::template operator+.
Fangrui Song6907ce22018-07-30 19:24:48 +00007862TemplateName
Douglas Gregor71395fa2009-11-04 00:56:37 +00007863ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007864 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007865 assert((!NNS || NNS->isDependent()) &&
7866 "Nested name specifier must be dependent");
Fangrui Song6907ce22018-07-30 19:24:48 +00007867
Douglas Gregor71395fa2009-11-04 00:56:37 +00007868 llvm::FoldingSetNodeID ID;
7869 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007870
7871 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007872 DependentTemplateName *QTN
7873 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007874
Douglas Gregor71395fa2009-11-04 00:56:37 +00007875 if (QTN)
7876 return TemplateName(QTN);
Fangrui Song6907ce22018-07-30 19:24:48 +00007877
Douglas Gregor71395fa2009-11-04 00:56:37 +00007878 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7879 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007880 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007881 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007882 } else {
7883 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007884 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007885 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007886
Douglas Gregorc42075a2010-02-04 18:10:26 +00007887 DependentTemplateName *CheckQTN
7888 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7889 assert(!CheckQTN && "Dependent template name canonicalization broken");
7890 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007891 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007892
Douglas Gregor71395fa2009-11-04 00:56:37 +00007893 DependentTemplateNames.InsertNode(QTN, InsertPos);
7894 return TemplateName(QTN);
7895}
7896
Fangrui Song6907ce22018-07-30 19:24:48 +00007897TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007898ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7899 TemplateName replacement) const {
7900 llvm::FoldingSetNodeID ID;
7901 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007902
7903 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007904 SubstTemplateTemplateParmStorage *subst
7905 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007906
John McCalld9dfe3a2011-06-30 08:33:18 +00007907 if (!subst) {
7908 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7909 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7910 }
7911
7912 return TemplateName(subst);
7913}
7914
Fangrui Song6907ce22018-07-30 19:24:48 +00007915TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007916ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7917 const TemplateArgument &ArgPack) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007918 auto &Self = const_cast<ASTContext &>(*this);
Douglas Gregor5590be02011-01-15 06:45:20 +00007919 llvm::FoldingSetNodeID ID;
7920 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007921
7922 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007923 SubstTemplateTemplateParmPackStorage *Subst
7924 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007925
Douglas Gregor5590be02011-01-15 06:45:20 +00007926 if (!Subst) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007927 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007928 ArgPack.pack_size(),
7929 ArgPack.pack_begin());
7930 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7931 }
7932
7933 return TemplateName(Subst);
7934}
7935
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007936/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007937/// TargetInfo, produce the corresponding type. The unsigned @p Type
7938/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007939CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007940 switch (Type) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007941 case TargetInfo::NoInt: return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007942 case TargetInfo::SignedChar: return SignedCharTy;
7943 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007944 case TargetInfo::SignedShort: return ShortTy;
7945 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7946 case TargetInfo::SignedInt: return IntTy;
7947 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7948 case TargetInfo::SignedLong: return LongTy;
7949 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7950 case TargetInfo::SignedLongLong: return LongLongTy;
7951 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7952 }
7953
David Blaikie83d382b2011-09-23 05:06:16 +00007954 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007955}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007956
7957//===----------------------------------------------------------------------===//
7958// Type Predicates.
7959//===----------------------------------------------------------------------===//
7960
Fariborz Jahanian96207692009-02-18 21:49:28 +00007961/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7962/// garbage collection attribute.
7963///
John McCall553d45a2011-01-12 00:34:59 +00007964Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007965 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007966 return Qualifiers::GCNone;
7967
Erik Pilkingtonfa983902018-10-30 20:31:30 +00007968 assert(getLangOpts().ObjC);
John McCall553d45a2011-01-12 00:34:59 +00007969 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7970
7971 // Default behaviour under objective-C's gc is for ObjC pointers
7972 // (or pointers to them) be treated as though they were declared
7973 // as __strong.
7974 if (GCAttrs == Qualifiers::GCNone) {
7975 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7976 return Qualifiers::Strong;
7977 else if (Ty->isPointerType())
Simon Pilgrimeed4b122019-10-02 11:48:06 +00007978 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
John McCall553d45a2011-01-12 00:34:59 +00007979 } else {
7980 // It's not valid to set GC attributes on anything that isn't a
7981 // pointer.
7982#ifndef NDEBUG
7983 QualType CT = Ty->getCanonicalTypeInternal();
Eugene Zelenko7855e772018-04-03 00:11:50 +00007984 while (const auto *AT = dyn_cast<ArrayType>(CT))
John McCall553d45a2011-01-12 00:34:59 +00007985 CT = AT->getElementType();
7986 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7987#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007988 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007989 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007990}
7991
Chris Lattner49af6a42008-04-07 06:51:04 +00007992//===----------------------------------------------------------------------===//
7993// Type Compatibility Testing
7994//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007995
Mike Stump11289f42009-09-09 15:08:12 +00007996/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007997/// compatible.
7998static bool areCompatVectorTypes(const VectorType *LHS,
7999 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00008000 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00008001 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00008002 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00008003}
8004
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00008005bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
8006 QualType SecondVec) {
8007 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
8008 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
8009
8010 if (hasSameUnqualifiedType(FirstVec, SecondVec))
8011 return true;
8012
Bob Wilsone6aeebb2010-11-12 17:24:54 +00008013 // Treat Neon vector types and most AltiVec vector types as if they are the
8014 // equivalent GCC vector types.
Simon Pilgrimeed4b122019-10-02 11:48:06 +00008015 const auto *First = FirstVec->castAs<VectorType>();
8016 const auto *Second = SecondVec->castAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00008017 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00008018 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00008019 First->getVectorKind() != VectorType::AltiVecPixel &&
8020 First->getVectorKind() != VectorType::AltiVecBool &&
8021 Second->getVectorKind() != VectorType::AltiVecPixel &&
8022 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00008023 return true;
8024
8025 return false;
8026}
8027
Akira Hatanaka3f2c9912019-09-07 00:34:47 +00008028bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
8029 while (true) {
8030 // __strong id
8031 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
8032 if (Attr->getAttrKind() == attr::ObjCOwnership)
8033 return true;
8034
8035 Ty = Attr->getModifiedType();
8036
8037 // X *__strong (...)
8038 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
8039 Ty = Paren->getInnerType();
8040
8041 // We do not want to look through typedefs, typeof(expr),
8042 // typeof(type), or any other way that the type is somehow
8043 // abstracted.
8044 } else {
8045 return false;
8046 }
8047 }
8048}
8049
Steve Naroff8e6aee52009-07-23 01:01:38 +00008050//===----------------------------------------------------------------------===//
8051// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
8052//===----------------------------------------------------------------------===//
8053
8054/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
8055/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00008056bool
8057ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
8058 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00008059 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00008060 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00008061 for (auto *PI : rProto->protocols())
8062 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00008063 return true;
8064 return false;
8065}
8066
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00008067/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
8068/// Class<pr1, ...>.
James Y Knightc2ca0032019-09-21 22:31:28 +00008069bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
8070 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
8071 for (auto *lhsProto : lhs->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00008072 bool match = false;
James Y Knightc2ca0032019-09-21 22:31:28 +00008073 for (auto *rhsProto : rhs->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00008074 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
8075 match = true;
8076 break;
8077 }
8078 }
8079 if (!match)
8080 return false;
8081 }
8082 return true;
8083}
8084
Steve Naroff8e6aee52009-07-23 01:01:38 +00008085/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
8086/// ObjCQualifiedIDType.
James Y Knightc2ca0032019-09-21 22:31:28 +00008087bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
8088 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
8089 bool compare) {
James Y Knightccc4d832019-10-17 15:27:04 +00008090 // Allow id<P..> and an 'id' in all cases.
8091 if (lhs->isObjCIdType() || rhs->isObjCIdType())
Steve Naroff8e6aee52009-07-23 01:01:38 +00008092 return true;
James Y Knightccc4d832019-10-17 15:27:04 +00008093
8094 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
8095 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
8096 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
8097 return false;
Steve Naroff8e6aee52009-07-23 01:01:38 +00008098
James Y Knightc2ca0032019-09-21 22:31:28 +00008099 if (lhs->isObjCQualifiedIdType()) {
8100 if (rhs->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00008101 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00008102 // make sure we check the class hierarchy.
James Y Knightc2ca0032019-09-21 22:31:28 +00008103 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8104 for (auto *I : lhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008105 // when comparing an id<P> on lhs with a static type on rhs,
8106 // see if static class implements all of id's protocols, directly or
8107 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00008108 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00008109 return false;
8110 }
8111 }
8112 // If there are no qualifiers and no interface, we have an 'id'.
8113 return true;
8114 }
Mike Stump11289f42009-09-09 15:08:12 +00008115 // Both the right and left sides have qualifiers.
James Y Knightc2ca0032019-09-21 22:31:28 +00008116 for (auto *lhsProto : lhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008117 bool match = false;
8118
8119 // when comparing an id<P> on lhs with a static type on rhs,
8120 // see if static class implements all of id's protocols, directly or
8121 // through its super class and categories.
James Y Knightc2ca0032019-09-21 22:31:28 +00008122 for (auto *rhsProto : rhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008123 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8124 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8125 match = true;
8126 break;
8127 }
8128 }
Mike Stump11289f42009-09-09 15:08:12 +00008129 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00008130 // make sure we check the class hierarchy.
James Y Knightc2ca0032019-09-21 22:31:28 +00008131 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8132 for (auto *I : lhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008133 // when comparing an id<P> on lhs with a static type on rhs,
8134 // see if static class implements all of id's protocols, directly or
8135 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00008136 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008137 match = true;
8138 break;
8139 }
8140 }
8141 }
8142 if (!match)
8143 return false;
8144 }
Mike Stump11289f42009-09-09 15:08:12 +00008145
Steve Naroff8e6aee52009-07-23 01:01:38 +00008146 return true;
8147 }
Mike Stump11289f42009-09-09 15:08:12 +00008148
James Y Knightc2ca0032019-09-21 22:31:28 +00008149 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
Steve Naroff8e6aee52009-07-23 01:01:38 +00008150
James Y Knightc2ca0032019-09-21 22:31:28 +00008151 if (lhs->getInterfaceType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008152 // If both the right and left sides have qualifiers.
James Y Knightc2ca0032019-09-21 22:31:28 +00008153 for (auto *lhsProto : lhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008154 bool match = false;
8155
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008156 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00008157 // see if static class implements all of id's protocols, directly or
8158 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008159 // First, lhs protocols in the qualifier list must be found, direct
8160 // or indirect in rhs's qualifier list or it is a mismatch.
James Y Knightc2ca0032019-09-21 22:31:28 +00008161 for (auto *rhsProto : rhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008162 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8163 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8164 match = true;
8165 break;
8166 }
8167 }
8168 if (!match)
8169 return false;
8170 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008171
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008172 // Static class's protocols, or its super class or category protocols
8173 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
James Y Knightc2ca0032019-09-21 22:31:28 +00008174 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008175 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8176 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8177 // This is rather dubious but matches gcc's behavior. If lhs has
8178 // no type qualifier and its class has no static protocol(s)
8179 // assume that it is mismatch.
James Y Knightc2ca0032019-09-21 22:31:28 +00008180 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008181 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00008182 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008183 bool match = false;
James Y Knightc2ca0032019-09-21 22:31:28 +00008184 for (auto *rhsProto : rhs->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008185 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8186 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8187 match = true;
8188 break;
8189 }
8190 }
8191 if (!match)
8192 return false;
8193 }
8194 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00008195 return true;
8196 }
8197 return false;
8198}
8199
Eli Friedman47f77112008-08-22 00:56:42 +00008200/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00008201/// compatible for assignment from RHS to LHS. This handles validation of any
8202/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00008203bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
8204 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00008205 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8206 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8207
James Y Knightccc4d832019-10-17 15:27:04 +00008208 // If either type represents the built-in 'id' type, return true.
8209 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
Steve Naroff7cae42b2009-07-10 23:34:53 +00008210 return true;
8211
Douglas Gregorab209d82015-07-07 03:58:42 +00008212 // Function object that propagates a successful result or handles
8213 // __kindof types.
8214 auto finish = [&](bool succeeded) -> bool {
8215 if (succeeded)
8216 return true;
8217
8218 if (!RHS->isKindOfType())
8219 return false;
8220
8221 // Strip off __kindof and protocol qualifiers, then check whether
8222 // we can assign the other way.
8223 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8224 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8225 };
8226
James Y Knightccc4d832019-10-17 15:27:04 +00008227 // Casts from or to id<P> are allowed when the other side has compatible
8228 // protocols.
Douglas Gregorab209d82015-07-07 03:58:42 +00008229 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
James Y Knightc2ca0032019-09-21 22:31:28 +00008230 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
Douglas Gregorab209d82015-07-07 03:58:42 +00008231 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008232
James Y Knightccc4d832019-10-17 15:27:04 +00008233 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
Douglas Gregorab209d82015-07-07 03:58:42 +00008234 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
James Y Knightc2ca0032019-09-21 22:31:28 +00008235 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
Douglas Gregorab209d82015-07-07 03:58:42 +00008236 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008237
James Y Knightccc4d832019-10-17 15:27:04 +00008238 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
8239 if (LHS->isObjCClass() && RHS->isObjCClass()) {
8240 return true;
8241 }
8242
John McCall8b07ec22010-05-15 11:32:37 +00008243 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00008244 if (LHS->getInterface() && RHS->getInterface()) {
8245 return finish(canAssignObjCInterfaces(LHS, RHS));
8246 }
Mike Stump11289f42009-09-09 15:08:12 +00008247
Steve Naroff8e6aee52009-07-23 01:01:38 +00008248 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008249}
8250
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008251/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Fangrui Song6907ce22018-07-30 19:24:48 +00008252/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008253/// arguments in block literals. When passed as arguments, passing 'A*' where
8254/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8255/// not OK. For the return type, the opposite is not OK.
8256bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8257 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008258 const ObjCObjectPointerType *RHSOPT,
8259 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008260
8261 // Function object that propagates a successful result or handles
8262 // __kindof types.
8263 auto finish = [&](bool succeeded) -> bool {
8264 if (succeeded)
8265 return true;
8266
8267 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8268 if (!Expected->isKindOfType())
8269 return false;
8270
8271 // Strip off __kindof and protocol qualifiers, then check whether
8272 // we can assign the other way.
8273 return canAssignObjCInterfacesInBlockPointer(
8274 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8275 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8276 BlockReturnType);
8277 };
8278
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008279 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008280 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00008281
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008282 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008283 return finish(RHSOPT->isObjCBuiltinType() ||
8284 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008285 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008286
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008287 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Volodymyr Sapsai73152a22019-08-28 00:25:06 +00008288 return finish(ObjCQualifiedIdTypesAreCompatible(
James Y Knightc2ca0032019-09-21 22:31:28 +00008289 (BlockReturnType ? LHSOPT : RHSOPT),
8290 (BlockReturnType ? RHSOPT : LHSOPT), false));
Fangrui Song6907ce22018-07-30 19:24:48 +00008291
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008292 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8293 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8294 if (LHS && RHS) { // We have 2 user-defined types.
8295 if (LHS != RHS) {
8296 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008297 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008298 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008299 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008300 }
8301 else
8302 return true;
8303 }
8304 return false;
8305}
8306
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008307/// Comparison routine for Objective-C protocols to be used with
8308/// llvm::array_pod_sort.
8309static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8310 ObjCProtocolDecl * const *rhs) {
8311 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008312}
8313
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008314/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008315/// of protocols inherited from two distinct objective-c pointer objects with
8316/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008317/// It is used to build composite qualifier list of the composite type of
8318/// the conditional expression involving two objective-c pointer objects.
Fangrui Song6907ce22018-07-30 19:24:48 +00008319static
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008320void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008321 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008322 const ObjCObjectPointerType *LHSOPT,
8323 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008324 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008325
John McCall8b07ec22010-05-15 11:32:37 +00008326 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8327 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8328 assert(LHS->getInterface() && "LHS must have an interface base");
8329 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008330
8331 // Add all of the protocols for the LHS.
8332 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8333
8334 // Start with the protocol qualifiers.
8335 for (auto proto : LHS->quals()) {
8336 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008337 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008338
8339 // Also add the protocols associated with the LHS interface.
8340 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8341
Raphael Isemannb23ccec2018-12-10 12:37:46 +00008342 // Add all of the protocols for the RHS.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008343 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8344
8345 // Start with the protocol qualifiers.
8346 for (auto proto : RHS->quals()) {
8347 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008348 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008349
8350 // Also add the protocols associated with the RHS interface.
8351 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8352
8353 // Compute the intersection of the collected protocol sets.
8354 for (auto proto : LHSProtocolSet) {
8355 if (RHSProtocolSet.count(proto))
8356 IntersectionSet.push_back(proto);
8357 }
8358
8359 // Compute the set of protocols that is implied by either the common type or
8360 // the protocols within the intersection.
8361 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8362 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8363
8364 // Remove any implied protocols from the list of inherited protocols.
8365 if (!ImpliedProtocols.empty()) {
8366 IntersectionSet.erase(
8367 std::remove_if(IntersectionSet.begin(),
8368 IntersectionSet.end(),
8369 [&](ObjCProtocolDecl *proto) -> bool {
8370 return ImpliedProtocols.count(proto) > 0;
8371 }),
8372 IntersectionSet.end());
8373 }
8374
8375 // Sort the remaining protocols by name.
8376 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8377 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008378}
8379
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008380/// Determine whether the first type is a subtype of the second.
8381static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8382 QualType rhs) {
8383 // Common case: two object pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008384 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8385 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008386 if (lhsOPT && rhsOPT)
8387 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8388
8389 // Two block pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008390 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8391 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008392 if (lhsBlock && rhsBlock)
8393 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8394
8395 // If either is an unqualified 'id' and the other is a block, it's
8396 // acceptable.
8397 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8398 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8399 return true;
8400
8401 return false;
8402}
8403
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008404// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008405static bool sameObjCTypeArgs(ASTContext &ctx,
8406 const ObjCInterfaceDecl *iface,
8407 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00008408 ArrayRef<QualType> rhsArgs,
8409 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008410 if (lhsArgs.size() != rhsArgs.size())
8411 return false;
8412
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008413 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008414 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008415 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8416 continue;
8417
8418 switch (typeParams->begin()[i]->getVariance()) {
8419 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00008420 if (!stripKindOf ||
8421 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8422 rhsArgs[i].stripObjCKindOfType(ctx))) {
8423 return false;
8424 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008425 break;
8426
8427 case ObjCTypeParamVariance::Covariant:
8428 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8429 return false;
8430 break;
8431
8432 case ObjCTypeParamVariance::Contravariant:
8433 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8434 return false;
8435 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00008436 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008437 }
8438
8439 return true;
8440}
8441
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008442QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008443 const ObjCObjectPointerType *Lptr,
8444 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00008445 const ObjCObjectType *LHS = Lptr->getObjectType();
8446 const ObjCObjectType *RHS = Rptr->getObjectType();
8447 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8448 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008449
8450 if (!LDecl || !RDecl)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008451 return {};
Douglas Gregore83b9562015-07-07 03:57:53 +00008452
Manman Renc46f7d12016-05-06 19:35:02 +00008453 // When either LHS or RHS is a kindof type, we should return a kindof type.
8454 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8455 // kindof(A).
8456 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8457
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008458 // Follow the left-hand side up the class hierarchy until we either hit a
8459 // root or find the RHS. Record the ancestors in case we don't find it.
8460 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8461 LHSAncestors;
8462 while (true) {
8463 // Record this ancestor. We'll need this if the common type isn't in the
8464 // path from the LHS to the root.
8465 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00008466
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008467 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8468 // Get the type arguments.
8469 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8470 bool anyChanges = false;
8471 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8472 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008473 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8474 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008475 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008476 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008477 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8478 // If only one has type arguments, the result will not have type
8479 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008480 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008481 anyChanges = true;
8482 }
8483
8484 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008485 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008486 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8487 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00008488 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008489 anyChanges = true;
8490
8491 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00008492 // If we need to return a kindof type but LHS is not a kindof type, we
8493 // build a new result type.
8494 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008495 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008496 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008497 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008498 return getObjCObjectPointerType(Result);
8499 }
8500
8501 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008502 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008503
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008504 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00008505 QualType LHSSuperType = LHS->getSuperClassType();
8506 if (LHSSuperType.isNull())
8507 break;
8508
8509 LHS = LHSSuperType->castAs<ObjCObjectType>();
8510 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008511
8512 // We didn't find anything by following the LHS to its root; now check
8513 // the RHS against the cached set of ancestors.
8514 while (true) {
8515 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8516 if (KnownLHS != LHSAncestors.end()) {
8517 LHS = KnownLHS->second;
8518
8519 // Get the type arguments.
8520 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8521 bool anyChanges = false;
8522 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8523 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008524 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8525 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008526 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008527 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008528 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8529 // If only one has type arguments, the result will not have type
8530 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008531 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008532 anyChanges = true;
8533 }
8534
8535 // Compute the intersection of protocols.
8536 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8537 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8538 Protocols);
8539 if (!Protocols.empty())
8540 anyChanges = true;
8541
Manman Renc46f7d12016-05-06 19:35:02 +00008542 // If we need to return a kindof type but RHS is not a kindof type, we
8543 // build a new result type.
8544 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008545 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008546 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008547 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008548 return getObjCObjectPointerType(Result);
8549 }
8550
8551 return getObjCObjectPointerType(QualType(RHS, 0));
8552 }
8553
8554 // Find the superclass of the RHS.
8555 QualType RHSSuperType = RHS->getSuperClassType();
8556 if (RHSSuperType.isNull())
8557 break;
8558
8559 RHS = RHSSuperType->castAs<ObjCObjectType>();
8560 }
8561
Eugene Zelenko7855e772018-04-03 00:11:50 +00008562 return {};
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008563}
8564
John McCall8b07ec22010-05-15 11:32:37 +00008565bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8566 const ObjCObjectType *RHS) {
8567 assert(LHS->getInterface() && "LHS is not an interface type");
8568 assert(RHS->getInterface() && "RHS is not an interface type");
8569
Chris Lattner49af6a42008-04-07 06:51:04 +00008570 // Verify that the base decls are compatible: the RHS must be a subclass of
8571 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008572 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8573 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8574 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008575 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008576
Douglas Gregore83b9562015-07-07 03:57:53 +00008577 // If the LHS has protocol qualifiers, determine whether all of them are
8578 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8579 // LHS).
8580 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008581 // OK if conversion of LHS to SuperClass results in narrowing of types
8582 // ; i.e., SuperClass may implement at least one of the protocols
8583 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8584 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8585 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8586 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8587 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8588 // qualifiers.
8589 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008590 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008591 // If there is no protocols associated with RHS, it is not a match.
8592 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008593 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008594
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008595 for (const auto *LHSProto : LHS->quals()) {
8596 bool SuperImplementsProtocol = false;
8597 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8598 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8599 SuperImplementsProtocol = true;
8600 break;
8601 }
8602 if (!SuperImplementsProtocol)
8603 return false;
8604 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008605 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008606
8607 // If the LHS is specialized, we may need to check type arguments.
8608 if (LHS->isSpecialized()) {
8609 // Follow the superclass chain until we've matched the LHS class in the
8610 // hierarchy. This substitutes type arguments through.
8611 const ObjCObjectType *RHSSuper = RHS;
8612 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8613 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8614
8615 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008616 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008617 !sameObjCTypeArgs(*this, LHS->getInterface(),
8618 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008619 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008620 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008621 }
8622 }
8623
8624 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008625}
8626
Steve Naroffb7605152009-02-12 17:52:19 +00008627bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8628 // get the "pointed to" types
Eugene Zelenko7855e772018-04-03 00:11:50 +00008629 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8630 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008631
Steve Naroff7cae42b2009-07-10 23:34:53 +00008632 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008633 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008634
8635 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8636 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008637}
8638
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008639bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8640 return canAssignObjCInterfaces(
8641 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8642 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8643}
8644
Mike Stump11289f42009-09-09 15:08:12 +00008645/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008646/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008647/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008648/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008649bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8650 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008651 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008652 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008653
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008654 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008655}
8656
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008657bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008658 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008659}
8660
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008661bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8662 return !mergeTypes(LHS, RHS, true).isNull();
8663}
8664
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008665/// mergeTransparentUnionType - if T is a transparent union type and a member
8666/// of T is compatible with SubType, return the merged type, else return
8667/// QualType()
8668QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8669 bool OfBlockPointer,
8670 bool Unqualified) {
8671 if (const RecordType *UT = T->getAsUnionType()) {
8672 RecordDecl *UD = UT->getDecl();
8673 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008674 for (const auto *I : UD->fields()) {
8675 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008676 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8677 if (!MT.isNull())
8678 return MT;
8679 }
8680 }
8681 }
8682
Eugene Zelenko7855e772018-04-03 00:11:50 +00008683 return {};
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008684}
8685
Alp Toker9cacbab2014-01-20 20:26:09 +00008686/// mergeFunctionParameterTypes - merge two types which appear as function
8687/// parameter types
8688QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8689 bool OfBlockPointer,
8690 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008691 // GNU extension: two types are compatible if they appear as a function
8692 // argument, one of the types is a transparent union type and the other
8693 // type is compatible with a union member
8694 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8695 Unqualified);
8696 if (!lmerge.isNull())
8697 return lmerge;
8698
8699 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8700 Unqualified);
8701 if (!rmerge.isNull())
8702 return rmerge;
8703
8704 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8705}
8706
Fangrui Song6907ce22018-07-30 19:24:48 +00008707QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008708 bool OfBlockPointer,
8709 bool Unqualified) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008710 const auto *lbase = lhs->getAs<FunctionType>();
8711 const auto *rbase = rhs->getAs<FunctionType>();
8712 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8713 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008714 bool allLTypes = true;
8715 bool allRTypes = true;
8716
8717 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008718 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008719 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008720 QualType RHS = rbase->getReturnType();
8721 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008722 bool UnqualifiedResult = Unqualified;
8723 if (!UnqualifiedResult)
8724 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008725 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008726 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008727 else
Alp Toker314cc812014-01-25 16:55:45 +00008728 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008729 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008730 if (retType.isNull())
8731 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00008732
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008733 if (Unqualified)
8734 retType = retType.getUnqualifiedType();
8735
Alp Toker314cc812014-01-25 16:55:45 +00008736 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8737 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008738 if (Unqualified) {
8739 LRetType = LRetType.getUnqualifiedType();
8740 RRetType = RRetType.getUnqualifiedType();
8741 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008742
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008743 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008744 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008745 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008746 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008747
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008748 // FIXME: double check this
8749 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8750 // rbase->getRegParmAttr() != 0 &&
8751 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008752 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8753 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008754
Douglas Gregor8c940862010-01-18 17:14:39 +00008755 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008756 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008757 return {};
Mike Stump11289f42009-09-09 15:08:12 +00008758
John McCall8c6b56f2010-12-15 01:06:38 +00008759 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008760 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008761 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008762 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008763 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008764
John McCall31168b02011-06-15 23:02:42 +00008765 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008766 return {};
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008767 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008768 return {};
Oren Ben Simhon220671a2018-03-17 13:31:35 +00008769 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008770 return {};
John McCall31168b02011-06-15 23:02:42 +00008771
John McCall8c6b56f2010-12-15 01:06:38 +00008772 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8773 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008774
Rafael Espindola8778c282012-11-29 16:09:03 +00008775 if (lbaseInfo.getNoReturn() != NoReturn)
8776 allLTypes = false;
8777 if (rbaseInfo.getNoReturn() != NoReturn)
8778 allRTypes = false;
8779
John McCall31168b02011-06-15 23:02:42 +00008780 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008781
Eli Friedman47f77112008-08-22 00:56:42 +00008782 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008783 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8784 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008785 // Compatible functions must have the same number of parameters
8786 if (lproto->getNumParams() != rproto->getNumParams())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008787 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008788
8789 // Variadic and non-variadic functions aren't compatible
8790 if (lproto->isVariadic() != rproto->isVariadic())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008791 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008792
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008793 if (lproto->getMethodQuals() != rproto->getMethodQuals())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008794 return {};
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008795
Akira Hatanaka98a49332017-09-22 00:41:05 +00008796 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8797 bool canUseLeft, canUseRight;
8798 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8799 newParamInfos))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008800 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008801
Akira Hatanaka98a49332017-09-22 00:41:05 +00008802 if (!canUseLeft)
8803 allLTypes = false;
8804 if (!canUseRight)
8805 allRTypes = false;
8806
Alp Toker601b22c2014-01-21 23:35:24 +00008807 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008808 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008809 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8810 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8811 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8812 QualType paramType = mergeFunctionParameterTypes(
8813 lParamType, rParamType, OfBlockPointer, Unqualified);
8814 if (paramType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008815 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008816
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008817 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008818 paramType = paramType.getUnqualifiedType();
8819
8820 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008821 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008822 lParamType = lParamType.getUnqualifiedType();
8823 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008824 }
Alp Toker601b22c2014-01-21 23:35:24 +00008825
8826 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008827 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008828 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008829 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008830 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008831
Eli Friedman47f77112008-08-22 00:56:42 +00008832 if (allLTypes) return lhs;
8833 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008834
8835 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8836 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008837 EPI.ExtParameterInfos =
8838 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008839 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008840 }
8841
8842 if (lproto) allRTypes = false;
8843 if (rproto) allLTypes = false;
8844
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008845 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008846 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008847 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008848 if (proto->isVariadic())
8849 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008850 // Check that the types are compatible with the types that
8851 // would result from default argument promotions (C99 6.7.5.3p15).
8852 // The only types actually affected are promotable integer
8853 // types and floats, which would be passed as a different
8854 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008855 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8856 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008857
Eli Friedman448ce402012-08-30 00:44:15 +00008858 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008859 // to pass enum values.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008860 if (const auto *Enum = paramTy->getAs<EnumType>()) {
Alp Toker601b22c2014-01-21 23:35:24 +00008861 paramTy = Enum->getDecl()->getIntegerType();
8862 if (paramTy.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008863 return {};
Eli Friedman448ce402012-08-30 00:44:15 +00008864 }
Alp Toker601b22c2014-01-21 23:35:24 +00008865
8866 if (paramTy->isPromotableIntegerType() ||
8867 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008868 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008869 }
8870
8871 if (allLTypes) return lhs;
8872 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008873
8874 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8875 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008876 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008877 }
8878
8879 if (allLTypes) return lhs;
8880 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008881 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008882}
8883
John McCall433c2e62013-03-21 00:10:07 +00008884/// Given that we have an enum type and a non-enum type, try to merge them.
8885static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8886 QualType other, bool isBlockReturnType) {
8887 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8888 // a signed integer type, or an unsigned integer type.
8889 // Compatibility is based on the underlying type, not the promotion
8890 // type.
8891 QualType underlyingType = ET->getDecl()->getIntegerType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00008892 if (underlyingType.isNull())
8893 return {};
John McCall433c2e62013-03-21 00:10:07 +00008894 if (Context.hasSameType(underlyingType, other))
8895 return other;
8896
8897 // In block return types, we're more permissive and accept any
8898 // integral type of the same size.
8899 if (isBlockReturnType && other->isIntegerType() &&
8900 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8901 return other;
8902
Eugene Zelenko7855e772018-04-03 00:11:50 +00008903 return {};
John McCall433c2e62013-03-21 00:10:07 +00008904}
8905
Fangrui Song6907ce22018-07-30 19:24:48 +00008906QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008907 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008908 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008909 // C++ [expr]: If an expression initially has the type "reference to T", the
8910 // type is adjusted to "T" prior to any further analysis, the expression
8911 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008912 // expression is an lvalue unless the reference is an rvalue reference and
8913 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008914 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8915 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008916
8917 if (Unqualified) {
8918 LHS = LHS.getUnqualifiedType();
8919 RHS = RHS.getUnqualifiedType();
8920 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008921
Eli Friedman47f77112008-08-22 00:56:42 +00008922 QualType LHSCan = getCanonicalType(LHS),
8923 RHSCan = getCanonicalType(RHS);
8924
8925 // If two types are identical, they are compatible.
8926 if (LHSCan == RHSCan)
8927 return LHS;
8928
John McCall8ccfcb52009-09-24 19:53:00 +00008929 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008930 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8931 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008932 if (LQuals != RQuals) {
8933 // If any of these qualifiers are different, we have a type
8934 // mismatch.
8935 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008936 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008937 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8938 LQuals.hasUnaligned() != RQuals.hasUnaligned())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008939 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008940
8941 // Exactly one GC qualifier difference is allowed: __strong is
8942 // okay if the other type has no GC qualifier but is an Objective
8943 // C object pointer (i.e. implicitly strong by default). We fix
8944 // this by pretending that the unqualified type was actually
8945 // qualified __strong.
8946 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8947 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8948 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8949
8950 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008951 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008952
8953 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8954 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8955 }
8956 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8957 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8958 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008959 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008960 }
8961
8962 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008963
Eli Friedmandcca6332009-06-01 01:22:52 +00008964 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8965 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008966
Chris Lattnerfd652912008-01-14 05:45:46 +00008967 // We want to consider the two function types to be the same for these
8968 // comparisons, just force one to the other.
8969 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8970 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008971
8972 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008973 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8974 LHSClass = Type::ConstantArray;
8975 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8976 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008977
John McCall8b07ec22010-05-15 11:32:37 +00008978 // ObjCInterfaces are just specialized ObjCObjects.
8979 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8980 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8981
Nate Begemance4d7fc2008-04-18 23:10:10 +00008982 // Canonicalize ExtVector -> Vector.
8983 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8984 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008985
Chris Lattner95554662008-04-07 05:43:21 +00008986 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008987 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008988 // Note that we only have special rules for turning block enum
8989 // returns into block int returns, not vice-versa.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008990 if (const auto *ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008991 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008992 }
John McCall9dd450b2009-09-21 23:43:11 +00008993 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008994 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008995 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008996 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008997 if (OfBlockPointer && !BlockReturnType) {
8998 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8999 return LHS;
9000 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
9001 return RHS;
9002 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009003
Eugene Zelenko7855e772018-04-03 00:11:50 +00009004 return {};
Steve Naroff32e44c02007-10-15 20:41:53 +00009005 }
Eli Friedman47f77112008-08-22 00:56:42 +00009006
Steve Naroffc6edcbd2008-01-09 22:43:08 +00009007 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00009008 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009009#define TYPE(Class, Base)
9010#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00009011#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009012#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
9013#define DEPENDENT_TYPE(Class, Base) case Type::Class:
John McCall36b12a82019-10-02 06:35:23 +00009014#include "clang/AST/TypeNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +00009015 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009016
Richard Smith27d807c2013-04-30 13:56:41 +00009017 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00009018 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00009019 case Type::LValueReference:
9020 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009021 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00009022 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009023
John McCall8b07ec22010-05-15 11:32:37 +00009024 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009025 case Type::IncompleteArray:
9026 case Type::VariableArray:
9027 case Type::FunctionProto:
9028 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00009029 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009030
Chris Lattnerfd652912008-01-14 05:45:46 +00009031 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00009032 {
9033 // Merge two pointer types, while trying to preserve typedef info
Simon Pilgrimeed4b122019-10-02 11:48:06 +00009034 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
9035 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009036 if (Unqualified) {
9037 LHSPointee = LHSPointee.getUnqualifiedType();
9038 RHSPointee = RHSPointee.getUnqualifiedType();
9039 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009040 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009041 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00009042 if (ResultType.isNull())
9043 return {};
Eli Friedman091a9ac2009-06-02 05:28:56 +00009044 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00009045 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00009046 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00009047 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00009048 return getPointerType(ResultType);
9049 }
Steve Naroff68e167d2008-12-10 17:49:55 +00009050 case Type::BlockPointer:
9051 {
9052 // Merge two block pointer types, while trying to preserve typedef info
Simon Pilgrimeed4b122019-10-02 11:48:06 +00009053 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
9054 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009055 if (Unqualified) {
9056 LHSPointee = LHSPointee.getUnqualifiedType();
9057 RHSPointee = RHSPointee.getUnqualifiedType();
9058 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00009059 if (getLangOpts().OpenCL) {
9060 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
9061 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
9062 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
9063 // 6.12.5) thus the following check is asymmetric.
9064 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
Eugene Zelenko7855e772018-04-03 00:11:50 +00009065 return {};
Anastasia Stulova81a25e352017-03-10 15:23:07 +00009066 LHSPteeQual.removeAddressSpace();
9067 RHSPteeQual.removeAddressSpace();
9068 LHSPointee =
9069 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
9070 RHSPointee =
9071 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
9072 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009073 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
9074 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00009075 if (ResultType.isNull())
9076 return {};
Steve Naroff68e167d2008-12-10 17:49:55 +00009077 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9078 return LHS;
9079 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9080 return RHS;
9081 return getBlockPointerType(ResultType);
9082 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00009083 case Type::Atomic:
9084 {
9085 // Merge two pointer types, while trying to preserve typedef info
Simon Pilgrimeed4b122019-10-02 11:48:06 +00009086 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
9087 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
Eli Friedman0dfb8892011-10-06 23:00:33 +00009088 if (Unqualified) {
9089 LHSValue = LHSValue.getUnqualifiedType();
9090 RHSValue = RHSValue.getUnqualifiedType();
9091 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009092 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
Eli Friedman0dfb8892011-10-06 23:00:33 +00009093 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00009094 if (ResultType.isNull())
9095 return {};
Eli Friedman0dfb8892011-10-06 23:00:33 +00009096 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
9097 return LHS;
9098 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
9099 return RHS;
9100 return getAtomicType(ResultType);
9101 }
Chris Lattnerfd652912008-01-14 05:45:46 +00009102 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00009103 {
9104 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
9105 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
9106 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009107 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00009108
9109 QualType LHSElem = getAsArrayType(LHS)->getElementType();
9110 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009111 if (Unqualified) {
9112 LHSElem = LHSElem.getUnqualifiedType();
9113 RHSElem = RHSElem.getUnqualifiedType();
9114 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009115
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009116 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00009117 if (ResultType.isNull())
9118 return {};
Jeremy Morse8129c5c2018-06-05 09:18:26 +00009119
9120 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
9121 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
9122
9123 // If either side is a variable array, and both are complete, check whether
9124 // the current dimension is definite.
9125 if (LVAT || RVAT) {
9126 auto SizeFetch = [this](const VariableArrayType* VAT,
9127 const ConstantArrayType* CAT)
9128 -> std::pair<bool,llvm::APInt> {
9129 if (VAT) {
9130 llvm::APSInt TheInt;
9131 Expr *E = VAT->getSizeExpr();
9132 if (E && E->isIntegerConstantExpr(TheInt, *this))
9133 return std::make_pair(true, TheInt);
9134 else
9135 return std::make_pair(false, TheInt);
9136 } else if (CAT) {
9137 return std::make_pair(true, CAT->getSize());
9138 } else {
9139 return std::make_pair(false, llvm::APInt());
9140 }
9141 };
9142
9143 bool HaveLSize, HaveRSize;
9144 llvm::APInt LSize, RSize;
9145 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
9146 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
9147 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
9148 return {}; // Definite, but unequal, array dimension
9149 }
9150
Chris Lattner465fa322008-10-05 17:34:18 +00009151 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9152 return LHS;
9153 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9154 return RHS;
Richard Smith772e2662019-10-04 01:25:59 +00009155 if (LCAT)
9156 return getConstantArrayType(ResultType, LCAT->getSize(),
9157 LCAT->getSizeExpr(),
9158 ArrayType::ArraySizeModifier(), 0);
9159 if (RCAT)
9160 return getConstantArrayType(ResultType, RCAT->getSize(),
9161 RCAT->getSizeExpr(),
9162 ArrayType::ArraySizeModifier(), 0);
Chris Lattner465fa322008-10-05 17:34:18 +00009163 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9164 return LHS;
9165 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9166 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00009167 if (LVAT) {
9168 // FIXME: This isn't correct! But tricky to implement because
9169 // the array's size has to be the size of LHS, but the type
9170 // has to be different.
9171 return LHS;
9172 }
9173 if (RVAT) {
9174 // FIXME: This isn't correct! But tricky to implement because
9175 // the array's size has to be the size of RHS, but the type
9176 // has to be different.
9177 return RHS;
9178 }
Eli Friedman3e62c212008-08-22 01:48:21 +00009179 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
9180 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00009181 return getIncompleteArrayType(ResultType,
9182 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00009183 }
Chris Lattnerfd652912008-01-14 05:45:46 +00009184 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009185 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009186 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009187 case Type::Enum:
Eugene Zelenko7855e772018-04-03 00:11:50 +00009188 return {};
Chris Lattnerfd652912008-01-14 05:45:46 +00009189 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009190 // Only exactly equal builtin types are compatible, which is tested above.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009191 return {};
Daniel Dunbar804c0442009-01-28 21:22:12 +00009192 case Type::Complex:
9193 // Distinct complex types are incompatible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009194 return {};
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009195 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00009196 // FIXME: The merged type should be an ExtVector!
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009197 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
9198 RHSCan->castAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00009199 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009200 return {};
John McCall8b07ec22010-05-15 11:32:37 +00009201 case Type::ObjCObject: {
9202 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00009203 // FIXME: This should be type compatibility, e.g. whether
9204 // "LHS x; RHS x;" at global scope is legal.
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009205 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
9206 RHS->castAs<ObjCObjectType>()))
Steve Naroff7a7814c2009-02-21 16:18:07 +00009207 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009208 return {};
Cedric Venet4fc88b72009-02-21 17:14:49 +00009209 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009210 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009211 if (OfBlockPointer) {
9212 if (canAssignObjCInterfacesInBlockPointer(
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009213 LHS->castAs<ObjCObjectPointerType>(),
9214 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00009215 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009216 return {};
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009217 }
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009218 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
9219 RHS->castAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00009220 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009221 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009222 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00009223 assert(LHS != RHS &&
9224 "Equivalent pipe types should have already been handled!");
Eugene Zelenko7855e772018-04-03 00:11:50 +00009225 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009226 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009227
David Blaikie8a40f702012-01-17 06:56:22 +00009228 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00009229}
Ted Kremenekfc581a92007-10-31 17:10:13 +00009230
Akira Hatanaka98a49332017-09-22 00:41:05 +00009231bool ASTContext::mergeExtParameterInfo(
9232 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9233 bool &CanUseFirst, bool &CanUseSecond,
9234 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9235 assert(NewParamInfos.empty() && "param info list not empty");
9236 CanUseFirst = CanUseSecond = true;
9237 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9238 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9239
John McCall18afab72016-03-01 00:49:02 +00009240 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00009241 // we match if and only if the second type also doesn't have them.
9242 if (!FirstHasInfo && !SecondHasInfo)
9243 return true;
John McCall18afab72016-03-01 00:49:02 +00009244
Akira Hatanaka98a49332017-09-22 00:41:05 +00009245 bool NeedParamInfo = false;
9246 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9247 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00009248
Akira Hatanaka98a49332017-09-22 00:41:05 +00009249 for (size_t I = 0; I < E; ++I) {
9250 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9251 if (FirstHasInfo)
9252 FirstParam = FirstFnType->getExtParameterInfo(I);
9253 if (SecondHasInfo)
9254 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00009255
Akira Hatanaka98a49332017-09-22 00:41:05 +00009256 // Cannot merge unless everything except the noescape flag matches.
9257 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00009258 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00009259
9260 bool FirstNoEscape = FirstParam.isNoEscape();
9261 bool SecondNoEscape = SecondParam.isNoEscape();
9262 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9263 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9264 if (NewParamInfos.back().getOpaqueValue())
9265 NeedParamInfo = true;
9266 if (FirstNoEscape != IsNoEscape)
9267 CanUseFirst = false;
9268 if (SecondNoEscape != IsNoEscape)
9269 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00009270 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00009271
9272 if (!NeedParamInfo)
9273 NewParamInfos.clear();
9274
Fariborz Jahanian97676972011-09-28 21:52:05 +00009275 return true;
9276}
9277
Chandler Carruth21c90602015-12-30 03:24:14 +00009278void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9279 ObjCLayouts[CD] = nullptr;
9280}
9281
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009282/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9283/// 'RHS' attributes and returns the merged version; including for function
9284/// return types.
9285QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9286 QualType LHSCan = getCanonicalType(LHS),
9287 RHSCan = getCanonicalType(RHS);
9288 // If two types are identical, they are compatible.
9289 if (LHSCan == RHSCan)
9290 return LHS;
9291 if (RHSCan->isFunctionType()) {
9292 if (!LHSCan->isFunctionType())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009293 return {};
Alp Toker314cc812014-01-25 16:55:45 +00009294 QualType OldReturnType =
9295 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009296 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00009297 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009298 QualType ResReturnType =
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009299 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9300 if (ResReturnType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009301 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009302 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9303 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9304 // In either case, use OldReturnType to build the new function type.
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009305 const auto *F = LHS->castAs<FunctionType>();
Eugene Zelenko7855e772018-04-03 00:11:50 +00009306 if (const auto *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009307 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9308 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00009309 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00009310 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009311 return ResultType;
9312 }
9313 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009314 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009315 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009316
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009317 // If the qualifiers are different, the types can still be merged.
9318 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9319 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9320 if (LQuals != RQuals) {
9321 // If any of these qualifiers are different, we have a type mismatch.
9322 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9323 LQuals.getAddressSpace() != RQuals.getAddressSpace())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009324 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009325
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009326 // Exactly one GC qualifier difference is allowed: __strong is
9327 // okay if the other type has no GC qualifier but is an Objective
9328 // C object pointer (i.e. implicitly strong by default). We fix
9329 // this by pretending that the unqualified type was actually
9330 // qualified __strong.
9331 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9332 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9333 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
Fangrui Song6907ce22018-07-30 19:24:48 +00009334
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009335 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009336 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009337
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009338 if (GC_L == Qualifiers::Strong)
9339 return LHS;
9340 if (GC_R == Qualifiers::Strong)
9341 return RHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009342 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009343 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009344
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009345 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
Simon Pilgrimeed4b122019-10-02 11:48:06 +00009346 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
9347 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009348 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9349 if (ResQT == LHSBaseQT)
9350 return LHS;
9351 if (ResQT == RHSBaseQT)
9352 return RHS;
9353 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009354 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009355}
9356
Chris Lattner4ba0cef2008-04-07 07:01:58 +00009357//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009358// Integer Predicates
9359//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00009360
Jay Foad39c79802011-01-12 09:06:06 +00009361unsigned ASTContext::getIntWidth(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009362 if (const auto *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00009363 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00009364 if (T->isBooleanType())
9365 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00009366 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009367 return (unsigned)getTypeSize(T);
9368}
9369
Abramo Bagnara13640492012-09-09 10:21:24 +00009370QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Leonard Chanab80f3c2018-06-14 14:53:51 +00009371 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9372 "Unexpected type");
Fangrui Song6907ce22018-07-30 19:24:48 +00009373
Chris Lattnerec3a1562009-10-17 20:33:28 +00009374 // Turn <4 x signed int> -> <4 x unsigned int>
Eugene Zelenko7855e772018-04-03 00:11:50 +00009375 if (const auto *VTy = T->getAs<VectorType>())
Chris Lattnerec3a1562009-10-17 20:33:28 +00009376 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00009377 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00009378
9379 // For enums, we return the unsigned version of the base type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009380 if (const auto *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009381 T = ETy->getDecl()->getIntegerType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009382
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009383 switch (T->castAs<BuiltinType>()->getKind()) {
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009384 case BuiltinType::Char_S:
9385 case BuiltinType::SChar:
9386 return UnsignedCharTy;
9387 case BuiltinType::Short:
9388 return UnsignedShortTy;
9389 case BuiltinType::Int:
9390 return UnsignedIntTy;
9391 case BuiltinType::Long:
9392 return UnsignedLongTy;
9393 case BuiltinType::LongLong:
9394 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00009395 case BuiltinType::Int128:
9396 return UnsignedInt128Ty;
Leonard Chanab80f3c2018-06-14 14:53:51 +00009397
9398 case BuiltinType::ShortAccum:
9399 return UnsignedShortAccumTy;
9400 case BuiltinType::Accum:
9401 return UnsignedAccumTy;
9402 case BuiltinType::LongAccum:
9403 return UnsignedLongAccumTy;
9404 case BuiltinType::SatShortAccum:
9405 return SatUnsignedShortAccumTy;
9406 case BuiltinType::SatAccum:
9407 return SatUnsignedAccumTy;
9408 case BuiltinType::SatLongAccum:
9409 return SatUnsignedLongAccumTy;
9410 case BuiltinType::ShortFract:
9411 return UnsignedShortFractTy;
9412 case BuiltinType::Fract:
9413 return UnsignedFractTy;
9414 case BuiltinType::LongFract:
9415 return UnsignedLongFractTy;
9416 case BuiltinType::SatShortFract:
9417 return SatUnsignedShortFractTy;
9418 case BuiltinType::SatFract:
9419 return SatUnsignedFractTy;
9420 case BuiltinType::SatLongFract:
9421 return SatUnsignedLongFractTy;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009422 default:
Leonard Chanab80f3c2018-06-14 14:53:51 +00009423 llvm_unreachable("Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009424 }
9425}
9426
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009427ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00009428
Richard Smith1fa5d642013-05-11 05:45:24 +00009429void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9430 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00009431
9432//===----------------------------------------------------------------------===//
9433// Builtin Type Computation
9434//===----------------------------------------------------------------------===//
9435
9436/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00009437/// pointer over the consumed characters. This returns the resultant type. If
9438/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9439/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9440/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009441///
9442/// RequiresICE is filled in on return to indicate whether the value is required
9443/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00009444static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00009445 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009446 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00009447 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00009448 // Modifiers.
9449 int HowLong = 0;
9450 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009451 RequiresICE = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009452
Chris Lattnerdc226c22010-10-01 22:42:38 +00009453 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00009454 bool Done = false;
9455 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009456 bool IsSpecial = false;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009457 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00009458 while (!Done) {
9459 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00009460 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00009461 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009462 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00009463 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009464 case 'S':
9465 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9466 assert(!Signed && "Can't use 'S' modifier multiple times!");
9467 Signed = true;
9468 break;
9469 case 'U':
9470 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00009471 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009472 Unsigned = true;
9473 break;
9474 case 'L':
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009475 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009476 assert(HowLong <= 2 && "Can't have LLLL modifier");
9477 ++HowLong;
9478 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009479 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009480 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009481 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009482 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009483 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009484 IsSpecial = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009485 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009486 if (Context.getTargetInfo().getLongWidth() == 32)
9487 ++HowLong;
9488 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00009489 case 'W':
9490 // This modifier represents int64 type.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009491 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00009492 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009493 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009494 IsSpecial = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009495 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00009496 switch (Context.getTargetInfo().getInt64Type()) {
9497 default:
9498 llvm_unreachable("Unexpected integer type");
9499 case TargetInfo::SignedLong:
9500 HowLong = 1;
9501 break;
9502 case TargetInfo::SignedLongLong:
9503 HowLong = 2;
9504 break;
9505 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00009506 break;
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009507 case 'Z':
9508 // This modifier represents int32 type.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009509 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009510 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
9511 #ifndef NDEBUG
9512 IsSpecial = true;
9513 #endif
9514 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
9515 default:
9516 llvm_unreachable("Unexpected integer type");
9517 case TargetInfo::SignedInt:
9518 HowLong = 0;
9519 break;
9520 case TargetInfo::SignedLong:
9521 HowLong = 1;
9522 break;
9523 case TargetInfo::SignedLongLong:
9524 HowLong = 2;
9525 break;
9526 }
9527 break;
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009528 case 'O':
9529 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9530 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
9531 #ifndef NDEBUG
9532 IsSpecial = true;
9533 #endif
9534 if (Context.getLangOpts().OpenCL)
9535 HowLong = 1;
9536 else
9537 HowLong = 2;
9538 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009539 }
9540 }
9541
9542 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00009543
Chris Lattnerecd79c62009-06-14 00:45:47 +00009544 // Read the base type.
9545 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00009546 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009547 case 'v':
9548 assert(HowLong == 0 && !Signed && !Unsigned &&
9549 "Bad modifiers used with 'v'!");
9550 Type = Context.VoidTy;
9551 break;
Jack Carter24bef982013-08-15 15:16:57 +00009552 case 'h':
9553 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00009554 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00009555 Type = Context.HalfTy;
9556 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009557 case 'f':
9558 assert(HowLong == 0 && !Signed && !Unsigned &&
9559 "Bad modifiers used with 'f'!");
9560 Type = Context.FloatTy;
9561 break;
9562 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009563 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00009564 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009565 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00009566 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009567 else if (HowLong == 2)
9568 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009569 else
9570 Type = Context.DoubleTy;
9571 break;
9572 case 's':
9573 assert(HowLong == 0 && "Bad modifiers used with 's'!");
9574 if (Unsigned)
9575 Type = Context.UnsignedShortTy;
9576 else
9577 Type = Context.ShortTy;
9578 break;
9579 case 'i':
9580 if (HowLong == 3)
9581 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9582 else if (HowLong == 2)
9583 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9584 else if (HowLong == 1)
9585 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9586 else
9587 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9588 break;
9589 case 'c':
9590 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9591 if (Signed)
9592 Type = Context.SignedCharTy;
9593 else if (Unsigned)
9594 Type = Context.UnsignedCharTy;
9595 else
9596 Type = Context.CharTy;
9597 break;
9598 case 'b': // boolean
9599 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9600 Type = Context.BoolTy;
9601 break;
9602 case 'z': // size_t.
9603 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9604 Type = Context.getSizeType();
9605 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00009606 case 'w': // wchar_t.
9607 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9608 Type = Context.getWideCharType();
9609 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009610 case 'F':
9611 Type = Context.getCFConstantStringType();
9612 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00009613 case 'G':
9614 Type = Context.getObjCIdType();
9615 break;
9616 case 'H':
9617 Type = Context.getObjCSelType();
9618 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00009619 case 'M':
9620 Type = Context.getObjCSuperType();
9621 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009622 case 'a':
9623 Type = Context.getBuiltinVaListType();
9624 assert(!Type.isNull() && "builtin va list type not initialized!");
9625 break;
9626 case 'A':
9627 // This is a "reference" to a va_list; however, what exactly
9628 // this means depends on how va_list is defined. There are two
9629 // different kinds of va_list: ones passed by value, and ones
9630 // passed by reference. An example of a by-value va_list is
9631 // x86, where va_list is a char*. An example of by-ref va_list
9632 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9633 // we want this argument to be a char*&; for x86-64, we want
9634 // it to be a __va_list_tag*.
9635 Type = Context.getBuiltinVaListType();
9636 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009637 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009638 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009639 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009640 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009641 break;
9642 case 'V': {
9643 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009644 unsigned NumElements = strtoul(Str, &End, 10);
9645 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009646 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009647
Fangrui Song6907ce22018-07-30 19:24:48 +00009648 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009649 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009650 assert(!RequiresICE && "Can't require vector ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009651
Chris Lattnerdc226c22010-10-01 22:42:38 +00009652 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009653 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009654 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009655 break;
9656 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009657 case 'E': {
9658 char *End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009659
Douglas Gregorfed66992012-06-07 18:08:25 +00009660 unsigned NumElements = strtoul(Str, &End, 10);
9661 assert(End != Str && "Missing vector size");
Fangrui Song6907ce22018-07-30 19:24:48 +00009662
Douglas Gregorfed66992012-06-07 18:08:25 +00009663 Str = End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009664
Douglas Gregorfed66992012-06-07 18:08:25 +00009665 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009666 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009667 Type = Context.getExtVectorType(ElementType, NumElements);
Fangrui Song6907ce22018-07-30 19:24:48 +00009668 break;
Douglas Gregorfed66992012-06-07 18:08:25 +00009669 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009670 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009671 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009672 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009673 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009674 Type = Context.getComplexType(ElementType);
9675 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00009676 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009677 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009678 Type = Context.getPointerDiffType();
9679 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009680 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009681 Type = Context.getFILEType();
9682 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009683 Error = ASTContext::GE_Missing_stdio;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009684 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009685 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009686 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009687 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009688 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009689 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009690 else
9691 Type = Context.getjmp_bufType();
9692
Mike Stump2adb4da2009-07-28 23:47:15 +00009693 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009694 Error = ASTContext::GE_Missing_setjmp;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009695 return {};
Mike Stump2adb4da2009-07-28 23:47:15 +00009696 }
9697 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009698 case 'K':
9699 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9700 Type = Context.getucontext_tType();
9701
9702 if (Type.isNull()) {
9703 Error = ASTContext::GE_Missing_ucontext;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009704 return {};
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009705 }
9706 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009707 case 'p':
9708 Type = Context.getProcessIDType();
9709 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009710 }
Mike Stump11289f42009-09-09 15:08:12 +00009711
Chris Lattnerdc226c22010-10-01 22:42:38 +00009712 // If there are modifiers and if we're allowed to parse them, go for it.
9713 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009714 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009715 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009716 default: Done = true; --Str; break;
9717 case '*':
9718 case '&': {
9719 // Both pointers and references can have their pointee types
9720 // qualified with an address space.
9721 char *End;
9722 unsigned AddrSpace = strtoul(Str, &End, 10);
Matt Arsenaultc65f9662018-08-02 12:14:28 +00009723 if (End != Str) {
9724 // Note AddrSpace == 0 is not the same as an unspecified address space.
9725 Type = Context.getAddrSpaceQualType(
9726 Type,
9727 Context.getLangASForBuiltinAddressSpace(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009728 Str = End;
9729 }
9730 if (c == '*')
9731 Type = Context.getPointerType(Type);
9732 else
9733 Type = Context.getLValueReferenceType(Type);
9734 break;
9735 }
9736 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9737 case 'C':
9738 Type = Type.withConst();
9739 break;
9740 case 'D':
9741 Type = Context.getVolatileType(Type);
9742 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009743 case 'R':
9744 Type = Type.withRestrict();
9745 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009746 }
9747 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009748
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009749 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Fangrui Song6907ce22018-07-30 19:24:48 +00009750 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009751
Chris Lattnerecd79c62009-06-14 00:45:47 +00009752 return Type;
9753}
9754
9755/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009756QualType ASTContext::GetBuiltinType(unsigned Id,
9757 GetBuiltinTypeError &Error,
9758 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009759 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00009760 if (TypeStr[0] == '\0') {
9761 Error = GE_Missing_type;
9762 return {};
9763 }
Mike Stump11289f42009-09-09 15:08:12 +00009764
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009765 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009766
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009767 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009768 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009769 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9770 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009771 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009772 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009773
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009774 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009775
Chris Lattnerecd79c62009-06-14 00:45:47 +00009776 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009777 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009778 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009779 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009780
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009781 // If this argument is required to be an IntegerConstantExpression and the
9782 // caller cares, fill in the bitmask we return.
9783 if (RequiresICE && IntegerConstantArgs)
9784 *IntegerConstantArgs |= 1 << ArgTypes.size();
Fangrui Song6907ce22018-07-30 19:24:48 +00009785
Chris Lattnerecd79c62009-06-14 00:45:47 +00009786 // Do array -> pointer decay. The builtin should use the decayed type.
9787 if (Ty->isArrayType())
9788 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009789
Chris Lattnerecd79c62009-06-14 00:45:47 +00009790 ArgTypes.push_back(Ty);
9791 }
9792
David Majnemerba3e5ec2015-03-13 18:26:17 +00009793 if (Id == Builtin::BI__GetExceptionInfo)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009794 return {};
David Majnemerba3e5ec2015-03-13 18:26:17 +00009795
Chris Lattnerecd79c62009-06-14 00:45:47 +00009796 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9797 "'.' should only occur at end of builtin type list!");
9798
Erich Keane881e83d2019-03-04 14:54:52 +00009799 bool Variadic = (TypeStr[0] == '.');
9800
Erich Keane00022812019-05-23 16:05:21 +00009801 FunctionType::ExtInfo EI(getDefaultCallingConvention(
9802 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
John McCall991eb4b2010-12-21 00:44:39 +00009803 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9804
John McCall991eb4b2010-12-21 00:44:39 +00009805
Richard Smith836de6b2016-12-19 23:59:34 +00009806 // We really shouldn't be making a no-proto type here.
9807 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00009808 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00009809
John McCalldb40c7f2010-12-14 08:05:40 +00009810 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00009811 EPI.ExtInfo = EI;
9812 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00009813 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9814 EPI.ExceptionSpec.Type =
9815 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00009816
Jordan Rose5c382722013-03-08 21:51:21 +00009817 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009818}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00009819
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009820static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9821 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009822 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009823 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009824
Richard Smithe2467b72017-11-16 23:54:56 +00009825 // Non-user-provided functions get emitted as weak definitions with every
9826 // use, no matter whether they've been explicitly instantiated etc.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009827 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
Richard Smithe2467b72017-11-16 23:54:56 +00009828 if (!MD->isUserProvided())
9829 return GVA_DiscardableODR;
9830
Yaron Keren4cd211b2017-02-22 14:32:39 +00009831 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009832 switch (FD->getTemplateSpecializationKind()) {
9833 case TSK_Undeclared:
9834 case TSK_ExplicitSpecialization:
9835 External = GVA_StrongExternal;
9836 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009837
Rafael Espindola3ae00052013-05-13 00:12:11 +00009838 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009839 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009840
David Majnemerc3d07332014-05-15 06:25:57 +00009841 // C++11 [temp.explicit]p10:
9842 // [ Note: The intent is that an inline function that is the subject of
9843 // an explicit instantiation declaration will still be implicitly
9844 // instantiated when used so that the body can be considered for
9845 // inlining, but that no out-of-line copy of the inline function would be
9846 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00009847 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00009848 return GVA_AvailableExternally;
9849
Rafael Espindola3ae00052013-05-13 00:12:11 +00009850 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009851 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009852 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009853 }
9854
9855 if (!FD->isInlined())
9856 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00009857
David Majnemer3f021502015-10-08 04:53:31 +00009858 if ((!Context.getLangOpts().CPlusPlus &&
9859 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009860 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00009861 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009862 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9863
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009864 // GNU or C99 inline semantics. Determine whether this symbol should be
9865 // externally visible.
9866 if (FD->isInlineDefinitionExternallyVisible())
9867 return External;
9868
9869 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00009870 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009871 }
9872
David Majnemer54e3ba52014-04-02 23:17:29 +00009873 // Functions specified with extern and inline in -fms-compatibility mode
9874 // forcibly get emitted. While the body of the function cannot be later
9875 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00009876 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00009877 return GVA_StrongODR;
9878
David Majnemer27d69db2014-04-28 22:17:59 +00009879 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009880}
9881
Artem Belevichca2b9512016-05-02 20:30:03 +00009882static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00009883 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009884 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9885 // dllexport/dllimport on inline functions.
9886 if (D->hasAttr<DLLImportAttr>()) {
9887 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9888 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00009889 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009890 if (L == GVA_DiscardableODR)
9891 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00009892 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9893 D->hasAttr<CUDAGlobalAttr>()) {
9894 // Device-side functions with __global__ attribute must always be
9895 // visible externally so they can be launched from host.
9896 if (L == GVA_DiscardableODR || L == GVA_Internal)
9897 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009898 }
9899 return L;
9900}
9901
Richard Smitha4653622017-09-06 20:01:14 +00009902/// Adjust the GVALinkage for a declaration based on what an external AST source
9903/// knows about whether there can be other definitions of this declaration.
9904static GVALinkage
9905adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9906 GVALinkage L) {
9907 ExternalASTSource *Source = Ctx.getExternalSource();
9908 if (!Source)
9909 return L;
9910
9911 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00009912 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00009913 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009914 if (L == GVA_DiscardableODR)
9915 return GVA_StrongODR;
9916 break;
Richard Smitha4653622017-09-06 20:01:14 +00009917
David Blaikie9ffe5a32017-01-30 05:00:26 +00009918 case ExternalASTSource::EK_Always:
9919 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00009920
David Blaikie9ffe5a32017-01-30 05:00:26 +00009921 case ExternalASTSource::EK_ReplyHazy:
9922 break;
9923 }
9924 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009925}
9926
Richard Smitha4653622017-09-06 20:01:14 +00009927GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9928 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9929 adjustGVALinkageForAttributes(*this, FD,
9930 basicGVALinkageForFunction(*this, FD)));
9931}
9932
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009933static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9934 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009935 if (!VD->isExternallyVisible())
9936 return GVA_Internal;
9937
David Majnemer27d69db2014-04-28 22:17:59 +00009938 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00009939 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9940 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9941 LexicalContext = LexicalContext->getLexicalParent();
9942
David Blaikieeb210012017-01-27 23:11:10 +00009943 // ObjC Blocks can create local variables that don't have a FunctionDecl
9944 // LexicalContext.
9945 if (!LexicalContext)
9946 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00009947
David Blaikieeb210012017-01-27 23:11:10 +00009948 // Otherwise, let the static local variable inherit its linkage from the
9949 // nearest enclosing function.
9950 auto StaticLocalLinkage =
9951 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9952
9953 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9954 // be emitted in any object with references to the symbol for the object it
9955 // contains, whether inline or out-of-line."
9956 // Similar behavior is observed with MSVC. An alternative ABI could use
9957 // StrongODR/AvailableExternally to match the function, but none are
9958 // known/supported currently.
9959 if (StaticLocalLinkage == GVA_StrongODR ||
9960 StaticLocalLinkage == GVA_AvailableExternally)
9961 return GVA_DiscardableODR;
9962 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009963 }
9964
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009965 // MSVC treats in-class initialized static data members as definitions.
9966 // By giving them non-strong linkage, out-of-line definitions won't
9967 // cause link errors.
9968 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9969 return GVA_DiscardableODR;
9970
Richard Smithd9b90092016-07-02 01:32:16 +00009971 // Most non-template variables have strong linkage; inline variables are
9972 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9973 GVALinkage StrongLinkage;
9974 switch (Context.getInlineVariableDefinitionKind(VD)) {
9975 case ASTContext::InlineVariableDefinitionKind::None:
9976 StrongLinkage = GVA_StrongExternal;
9977 break;
9978 case ASTContext::InlineVariableDefinitionKind::Weak:
9979 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009980 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009981 break;
9982 case ASTContext::InlineVariableDefinitionKind::Strong:
9983 StrongLinkage = GVA_StrongODR;
9984 break;
9985 }
Richard Smith62f19e72016-06-25 00:15:56 +00009986
Richard Smith8809a0c2013-09-27 20:14:12 +00009987 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009988 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009989 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009990
David Majnemer6d1780c2015-07-17 23:36:49 +00009991 case TSK_ExplicitSpecialization:
Hans Wennborg4bdd5132019-09-25 11:09:46 +00009992 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9993 VD->isStaticDataMember()
9994 ? GVA_StrongODR
9995 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009996
Rafael Espindola3ae00052013-05-13 00:12:11 +00009997 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009998 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009999
David Majnemer27d69db2014-04-28 22:17:59 +000010000 case TSK_ExplicitInstantiationDeclaration:
10001 return GVA_AvailableExternally;
10002
Rafael Espindola3ae00052013-05-13 00:12:11 +000010003 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +000010004 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010005 }
Rafael Espindola27699c82013-05-13 14:05:53 +000010006
10007 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010008}
10009
Hans Wennborgb0f2f142014-05-15 22:07:49 +000010010GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +000010011 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
10012 adjustGVALinkageForAttributes(*this, VD,
10013 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +000010014}
10015
David Blaikiee6b7c282017-04-11 20:46:34 +000010016bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +000010017 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010018 if (!VD->isFileVarDecl())
10019 return false;
Renato Golin9258aa52014-05-21 10:40:27 +000010020 // Global named register variables (GNU extension) are never emitted.
10021 if (VD->getStorageClass() == SC_Register)
10022 return false;
Richard Smith7747ce22015-08-19 20:49:38 +000010023 if (VD->getDescribedVarTemplate() ||
10024 isa<VarTemplatePartialSpecializationDecl>(VD))
10025 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +000010026 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Smith5205a8c2013-04-01 20:22:16 +000010027 // We never need to emit an uninstantiated function template.
10028 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10029 return false;
Nico Weber66220292016-03-02 17:28:48 +000010030 } else if (isa<PragmaCommentDecl>(D))
10031 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +000010032 else if (isa<PragmaDetectMismatchDecl>(D))
10033 return true;
Nico Weber66220292016-03-02 17:28:48 +000010034 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +000010035 return !D->getDeclContext()->isDependentContext();
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010036 else if (isa<OMPAllocateDecl>(D))
10037 return !D->getDeclContext()->isDependentContext();
Michael Krused47b9432019-08-05 18:43:21 +000010038 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +000010039 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +000010040 else if (isa<ImportDecl>(D))
10041 return true;
Alexey Bataev97720002014-11-11 04:05:39 +000010042 else
Richard Smith5205a8c2013-04-01 20:22:16 +000010043 return false;
10044
Hans Wennborg08c5a7b2018-06-25 13:23:49 +000010045 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
10046 assert(getExternalSource() && "It's from an AST file; must have a source.");
10047 // On Windows, PCH files are built together with an object file. If this
10048 // declaration comes from such a PCH and DeclMustBeEmitted would return
10049 // true, it would have returned true and the decl would have been emitted
10050 // into that object file, so it doesn't need to be emitted here.
10051 // Note that decls are still emitted if they're referenced, as usual;
10052 // DeclMustBeEmitted is used to decide whether a decl must be emitted even
10053 // if it's not referenced.
10054 //
10055 // Explicit template instantiation definitions are tricky. If there was an
10056 // explicit template instantiation decl in the PCH before, it will look like
10057 // the definition comes from there, even if that was just the declaration.
10058 // (Explicit instantiation defs of variable templates always get emitted.)
10059 bool IsExpInstDef =
10060 isa<FunctionDecl>(D) &&
10061 cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
10062 TSK_ExplicitInstantiationDefinition;
10063
Hans Wennborgb51a7032018-09-14 15:18:30 +000010064 // Implicit member function definitions, such as operator= might not be
10065 // marked as template specializations, since they're not coming from a
10066 // template but synthesized directly on the class.
10067 IsExpInstDef |=
10068 isa<CXXMethodDecl>(D) &&
10069 cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
10070 TSK_ExplicitInstantiationDefinition;
10071
Hans Wennborg08c5a7b2018-06-25 13:23:49 +000010072 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
10073 return false;
10074 }
10075
Richard Smith5205a8c2013-04-01 20:22:16 +000010076 // If this is a member of a class template, we do not need to emit it.
10077 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010078 return false;
10079
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +000010080 // Weak references don't produce any output by themselves.
10081 if (D->hasAttr<WeakRefAttr>())
10082 return false;
10083
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010084 // Aliases and used decls are required.
10085 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
10086 return true;
10087
Eugene Zelenko7855e772018-04-03 00:11:50 +000010088 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010089 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +000010090 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +000010091 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010092
10093 // Constructors and destructors are required.
10094 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
10095 return true;
Hans Wennborg08c5a7b2018-06-25 13:23:49 +000010096
John McCall6bd2a892013-01-25 22:31:03 +000010097 // The key function for a class is required. This rule only comes
10098 // into play when inline functions can be key functions, though.
10099 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +000010100 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
John McCall6bd2a892013-01-25 22:31:03 +000010101 const CXXRecordDecl *RD = MD->getParent();
10102 if (MD->isOutOfLine() && RD->isDynamicClass()) {
10103 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
10104 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
10105 return true;
10106 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010107 }
10108 }
10109
David Blaikie9ffe5a32017-01-30 05:00:26 +000010110 GVALinkage Linkage = GetGVALinkageForFunction(FD);
10111
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010112 // static, static inline, always_inline, and extern inline functions can
10113 // always be deferred. Normal inline functions can be deferred in C99/C++.
10114 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +000010115 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010116 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +000010117
Eugene Zelenko7855e772018-04-03 00:11:50 +000010118 const auto *VD = cast<VarDecl>(D);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010119 assert(VD->isFileVarDecl() && "Expected file scoped var");
10120
Alexey Bataevd01b7492018-08-15 19:45:12 +000010121 // If the decl is marked as `declare target to`, it should be emitted for the
10122 // host and for the device.
10123 if (LangOpts.OpenMP &&
10124 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
10125 return true;
10126
Hans Wennborg56fc62b2014-07-17 20:25:23 +000010127 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
10128 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +000010129 return false;
10130
Richard Smitha0e5e542012-11-12 21:38:00 +000010131 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +000010132 auto Linkage = GetGVALinkageForVariable(VD);
10133 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +000010134 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010135
Richard Smitha4653622017-09-06 20:01:14 +000010136 // We never need to emit a variable that is available in another TU.
10137 if (Linkage == GVA_AvailableExternally)
10138 return false;
10139
Richard Smitha0e5e542012-11-12 21:38:00 +000010140 // Variables that have destruction with side-effects are required.
Richard Smith2b4fa532019-09-29 05:08:46 +000010141 if (VD->needsDestruction(*this))
Richard Smitha0e5e542012-11-12 21:38:00 +000010142 return true;
10143
10144 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +000010145 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +000010146 // We can get a value-dependent initializer during error recovery.
10147 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +000010148 return true;
10149
Richard Smithda383632016-08-15 01:33:41 +000010150 // Likewise, variables with tuple-like bindings are required if their
10151 // bindings have side-effects.
Eugene Zelenko7855e772018-04-03 00:11:50 +000010152 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
10153 for (const auto *BD : DD->bindings())
10154 if (const auto *BindingVD = BD->getHoldingVar())
Richard Smithda383632016-08-15 01:33:41 +000010155 if (DeclMustBeEmitted(BindingVD))
10156 return true;
10157
Richard Smitha0e5e542012-11-12 21:38:00 +000010158 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010159}
Charles Davis53c59df2010-08-16 03:33:14 +000010160
Erich Keane281d20b2018-01-08 21:34:17 +000010161void ASTContext::forEachMultiversionedFunctionVersion(
10162 const FunctionDecl *FD,
Erich Keane0fb16482018-08-13 18:33:20 +000010163 llvm::function_ref<void(FunctionDecl *)> Pred) const {
Erich Keane281d20b2018-01-08 21:34:17 +000010164 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
10165 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
Erich Keane7304f0a2018-11-28 20:58:43 +000010166 FD = FD->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +000010167 for (auto *CurDecl :
10168 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
Erich Keane7304f0a2018-11-28 20:58:43 +000010169 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +000010170 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
10171 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
10172 SeenDecls.insert(CurFD);
10173 Pred(CurFD);
10174 }
10175 }
10176}
10177
Reid Kleckner78af0702013-08-27 23:08:25 +000010178CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
Erich Keane00022812019-05-23 16:05:21 +000010179 bool IsCXXMethod,
10180 bool IsBuiltin) const {
Charles Davis99202b32010-11-09 18:04:24 +000010181 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +000010182 if (IsCXXMethod)
10183 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +000010184
Erich Keane00022812019-05-23 16:05:21 +000010185 // Builtins ignore user-specified default calling convention and remain the
10186 // Target's default calling convention.
10187 if (!IsBuiltin) {
10188 switch (LangOpts.getDefaultCallingConv()) {
10189 case LangOptions::DCC_None:
10190 break;
10191 case LangOptions::DCC_CDecl:
10192 return CC_C;
10193 case LangOptions::DCC_FastCall:
10194 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
10195 return CC_X86FastCall;
10196 break;
10197 case LangOptions::DCC_StdCall:
10198 if (!IsVariadic)
10199 return CC_X86StdCall;
10200 break;
10201 case LangOptions::DCC_VectorCall:
10202 // __vectorcall cannot be applied to variadic functions.
10203 if (!IsVariadic)
10204 return CC_X86VectorCall;
10205 break;
10206 case LangOptions::DCC_RegCall:
10207 // __regcall cannot be applied to variadic functions.
10208 if (!IsVariadic)
10209 return CC_X86RegCall;
10210 break;
10211 }
Alexey Bataeva7547182016-05-18 09:06:38 +000010212 }
Erich Keane39309482019-07-25 17:14:45 +000010213 return Target->getDefaultCallingConv();
Charles Davis99202b32010-11-09 18:04:24 +000010214}
10215
Jay Foad39c79802011-01-12 09:06:06 +000010216bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +000010217 // Pass through to the C++ ABI object
10218 return ABI->isNearlyEmpty(RD);
10219}
10220
Reid Kleckner96f8f932014-02-05 17:27:08 +000010221VTableContextBase *ASTContext::getVTableContext() {
10222 if (!VTContext.get()) {
10223 if (Target->getCXXABI().isMicrosoft())
10224 VTContext.reset(new MicrosoftVTableContext(*this));
10225 else
10226 VTContext.reset(new ItaniumVTableContext(*this));
10227 }
10228 return VTContext.get();
10229}
10230
Yaxun Liuc18e9ec2019-02-14 02:00:09 +000010231MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
10232 if (!T)
10233 T = Target;
10234 switch (T->getCXXABI().getKind()) {
Petr Hosek9c3f9b92019-09-06 18:59:43 -070010235 case TargetCXXABI::Fuchsia:
Tim Northover9bb857a2013-01-31 12:13:10 +000010236 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +000010237 case TargetCXXABI::GenericItanium:
10238 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +000010239 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +000010240 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000010241 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +000010242 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +000010243 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010244 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +000010245 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010246 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010247 }
David Blaikie83d382b2011-09-23 05:06:16 +000010248 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010249}
10250
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010251CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010252
10253size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +000010254 return ASTRecordLayouts.getMemorySize() +
10255 llvm::capacity_in_bytes(ObjCLayouts) +
10256 llvm::capacity_in_bytes(KeyFunctions) +
10257 llvm::capacity_in_bytes(ObjCImpls) +
10258 llvm::capacity_in_bytes(BlockVarCopyInits) +
10259 llvm::capacity_in_bytes(DeclAttrs) +
10260 llvm::capacity_in_bytes(TemplateOrInstantiation) +
10261 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10262 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10263 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10264 llvm::capacity_in_bytes(OverriddenMethods) +
10265 llvm::capacity_in_bytes(Types) +
Richard Smithf19a8b02019-05-02 00:49:14 +000010266 llvm::capacity_in_bytes(VariableArrayTypes);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010267}
Ted Kremenek540017e2011-10-06 05:00:56 +000010268
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010269/// getIntTypeForBitwidth -
10270/// sets integer QualTy according to specified details:
10271/// bitwidth, signed/unsigned.
10272/// Returns empty type if there is no appropriate target types.
10273QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
10274 unsigned Signed) const {
10275 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10276 CanQualType QualTy = getFromTargetType(Ty);
10277 if (!QualTy && DestWidth == 128)
10278 return Signed ? Int128Ty : UnsignedInt128Ty;
10279 return QualTy;
10280}
10281
10282/// getRealTypeForBitwidth -
10283/// sets floating point QualTy according to specified bitwidth.
10284/// Returns empty type if there is no appropriate target types.
10285QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
10286 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
10287 switch (Ty) {
10288 case TargetInfo::Float:
10289 return FloatTy;
10290 case TargetInfo::Double:
10291 return DoubleTy;
10292 case TargetInfo::LongDouble:
10293 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000010294 case TargetInfo::Float128:
10295 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010296 case TargetInfo::NoFloat:
Eugene Zelenko7855e772018-04-03 00:11:50 +000010297 return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010298 }
10299
10300 llvm_unreachable("Unhandled TargetInfo::RealType value");
10301}
10302
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010303void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10304 if (Number > 1)
10305 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +000010306}
10307
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010308unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010309 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010310 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +000010311}
10312
David Majnemer2206bf52014-03-05 08:57:59 +000010313void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10314 if (Number > 1)
10315 StaticLocalNumbers[VD] = Number;
10316}
10317
10318unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010319 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +000010320 return I != StaticLocalNumbers.end() ? I->second : 1;
10321}
10322
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010323MangleNumberingContext &
10324ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010325 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +000010326 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +000010327 if (!MCtx)
10328 MCtx = createMangleNumberingContext();
10329 return *MCtx;
10330}
10331
Reid Klecknerda2bde92019-10-10 01:14:22 +000010332MangleNumberingContext &
10333ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
10334 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
10335 std::unique_ptr<MangleNumberingContext> &MCtx =
10336 ExtraMangleNumberingContexts[D];
10337 if (!MCtx)
10338 MCtx = createMangleNumberingContext();
10339 return *MCtx;
10340}
10341
Justin Lebar20ebffc2016-10-10 16:26:19 +000010342std::unique_ptr<MangleNumberingContext>
10343ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010344 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +000010345}
10346
David Majnemere7a818f2015-03-06 18:53:55 +000010347const CXXConstructorDecl *
10348ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
10349 return ABI->getCopyConstructorForExceptionObject(
10350 cast<CXXRecordDecl>(RD->getFirstDecl()));
10351}
10352
10353void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
10354 CXXConstructorDecl *CD) {
10355 return ABI->addCopyConstructorForExceptionObject(
10356 cast<CXXRecordDecl>(RD->getFirstDecl()),
10357 cast<CXXConstructorDecl>(CD->getFirstDecl()));
10358}
10359
David Majnemer00350522015-08-31 18:48:39 +000010360void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10361 TypedefNameDecl *DD) {
10362 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10363}
10364
10365TypedefNameDecl *
10366ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10367 return ABI->getTypedefNameForUnnamedTagDecl(TD);
10368}
10369
10370void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10371 DeclaratorDecl *DD) {
10372 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10373}
10374
10375DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10376 return ABI->getDeclaratorForUnnamedTagDecl(TD);
10377}
10378
Ted Kremenek540017e2011-10-06 05:00:56 +000010379void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10380 ParamIndices[D] = index;
10381}
10382
10383unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10384 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
Fangrui Song6907ce22018-07-30 19:24:48 +000010385 assert(I != ParamIndices.end() &&
Ted Kremenek540017e2011-10-06 05:00:56 +000010386 "ParmIndices lacks entry set by ParmVarDecl");
10387 return I->second;
10388}
Fariborz Jahanian615de762013-05-28 17:37:39 +000010389
Eric Fiselier708afb52019-05-16 21:04:15 +000010390QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
10391 unsigned Length) const {
10392 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
10393 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
10394 EltTy = EltTy.withConst();
10395
10396 EltTy = adjustStringLiteralBaseType(EltTy);
10397
10398 // Get an array type for the string, according to C99 6.4.5. This includes
10399 // the null terminator character.
Richard Smith772e2662019-10-04 01:25:59 +000010400 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
Eric Fiselier708afb52019-05-16 21:04:15 +000010401 ArrayType::Normal, /*IndexTypeQuals*/ 0);
10402}
10403
10404StringLiteral *
10405ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
10406 StringLiteral *&Result = StringLiteralCache[Key];
10407 if (!Result)
10408 Result = StringLiteral::Create(
10409 *this, Key, StringLiteral::Ascii,
10410 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
10411 SourceLocation());
10412 return Result;
10413}
10414
Fariborz Jahanian615de762013-05-28 17:37:39 +000010415bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10416 const llvm::Triple &T = getTargetInfo().getTriple();
10417 if (!T.isOSDarwin())
10418 return false;
10419
Bob Wilson2c82c3d2013-11-02 23:27:49 +000010420 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10421 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10422 return false;
10423
Fariborz Jahanian615de762013-05-28 17:37:39 +000010424 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10425 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10426 uint64_t Size = sizeChars.getQuantity();
10427 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10428 unsigned Align = alignChars.getQuantity();
10429 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10430 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10431}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010432
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010433/// Template specializations to abstract away from pointers and TypeLocs.
10434/// @{
10435template <typename T>
Sam McCall814e7972018-11-14 10:33:30 +000010436static ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010437 return ast_type_traits::DynTypedNode::create(*Node);
10438}
10439template <>
10440ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
10441 return ast_type_traits::DynTypedNode::create(Node);
10442}
10443template <>
10444ast_type_traits::DynTypedNode
10445createDynTypedNode(const NestedNameSpecifierLoc &Node) {
10446 return ast_type_traits::DynTypedNode::create(Node);
10447}
10448/// @}
10449
Sam McCall814e7972018-11-14 10:33:30 +000010450/// A \c RecursiveASTVisitor that builds a map from nodes to their
10451/// parents as defined by the \c RecursiveASTVisitor.
10452///
10453/// Note that the relationship described here is purely in terms of AST
10454/// traversal - there are other relationships (for example declaration context)
10455/// in the AST that are better modeled by special matchers.
10456///
10457/// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
10458class ASTContext::ParentMap::ASTVisitor
10459 : public RecursiveASTVisitor<ASTVisitor> {
10460public:
Stephen Kelly0a717d52019-05-12 21:09:32 +010010461 ASTVisitor(ParentMap &Map, ASTContext &Context)
10462 : Map(Map), Context(Context) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010463
Sam McCall814e7972018-11-14 10:33:30 +000010464private:
10465 friend class RecursiveASTVisitor<ASTVisitor>;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010466
Sam McCall814e7972018-11-14 10:33:30 +000010467 using VisitorBase = RecursiveASTVisitor<ASTVisitor>;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010468
Sam McCall814e7972018-11-14 10:33:30 +000010469 bool shouldVisitTemplateInstantiations() const { return true; }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010470
Sam McCall814e7972018-11-14 10:33:30 +000010471 bool shouldVisitImplicitCode() const { return true; }
10472
10473 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
10474 typename MapTy>
10475 bool TraverseNode(T Node, MapNodeTy MapNode, BaseTraverseFn BaseTraverse,
10476 MapTy *Parents) {
10477 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010478 return true;
Sam McCall814e7972018-11-14 10:33:30 +000010479 if (ParentStack.size() > 0) {
10480 // FIXME: Currently we add the same parent multiple times, but only
10481 // when no memoization data is available for the type.
10482 // For example when we visit all subexpressions of template
10483 // instantiations; this is suboptimal, but benign: the only way to
10484 // visit those is with hasAncestor / hasParent, and those do not create
10485 // new matches.
10486 // The plan is to enable DynTypedNode to be storable in a map or hash
10487 // map. The main problem there is to implement hash functions /
10488 // comparison operators for all types that DynTypedNode supports that
10489 // do not have pointer identity.
10490 auto &NodeOrVector = (*Parents)[MapNode];
10491 if (NodeOrVector.isNull()) {
10492 if (const auto *D = ParentStack.back().get<Decl>())
10493 NodeOrVector = D;
10494 else if (const auto *S = ParentStack.back().get<Stmt>())
10495 NodeOrVector = S;
10496 else
10497 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
10498 } else {
10499 if (!NodeOrVector.template is<ParentVector *>()) {
10500 auto *Vector = new ParentVector(
10501 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
10502 delete NodeOrVector
10503 .template dyn_cast<ast_type_traits::DynTypedNode *>();
10504 NodeOrVector = Vector;
Manuel Klimek95403e62014-05-21 13:28:59 +000010505 }
Sam McCall814e7972018-11-14 10:33:30 +000010506
10507 auto *Vector = NodeOrVector.template get<ParentVector *>();
10508 // Skip duplicates for types that have memoization data.
10509 // We must check that the type has memoization data before calling
10510 // std::find() because DynTypedNode::operator== can't compare all
10511 // types.
10512 bool Found = ParentStack.back().getMemoizationData() &&
10513 std::find(Vector->begin(), Vector->end(),
10514 ParentStack.back()) != Vector->end();
10515 if (!Found)
10516 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +000010517 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010518 }
Sam McCall814e7972018-11-14 10:33:30 +000010519 ParentStack.push_back(createDynTypedNode(Node));
10520 bool Result = BaseTraverse();
10521 ParentStack.pop_back();
10522 return Result;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010523 }
Sam McCall814e7972018-11-14 10:33:30 +000010524
10525 bool TraverseDecl(Decl *DeclNode) {
10526 return TraverseNode(
10527 DeclNode, DeclNode, [&] { return VisitorBase::TraverseDecl(DeclNode); },
10528 &Map.PointerParents);
Manuel Klimek95403e62014-05-21 13:28:59 +000010529 }
Sam McCall814e7972018-11-14 10:33:30 +000010530
10531 bool TraverseStmt(Stmt *StmtNode) {
Stephen Kelly0a717d52019-05-12 21:09:32 +010010532 Stmt *FilteredNode = StmtNode;
10533 if (auto *ExprNode = dyn_cast_or_null<Expr>(FilteredNode))
10534 FilteredNode = Context.traverseIgnored(ExprNode);
10535 return TraverseNode(FilteredNode, FilteredNode,
10536 [&] { return VisitorBase::TraverseStmt(FilteredNode); },
10537 &Map.PointerParents);
Sam McCall814e7972018-11-14 10:33:30 +000010538 }
10539
10540 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
10541 return TraverseNode(
10542 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
10543 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
10544 &Map.OtherParents);
10545 }
10546
10547 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
10548 return TraverseNode(
10549 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
10550 [&] { return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); },
10551 &Map.OtherParents);
10552 }
10553
10554 ParentMap &Map;
Stephen Kelly0a717d52019-05-12 21:09:32 +010010555 ASTContext &Context;
Sam McCall814e7972018-11-14 10:33:30 +000010556 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
10557};
10558
10559ASTContext::ParentMap::ParentMap(ASTContext &Ctx) {
Stephen Kelly0a717d52019-05-12 21:09:32 +010010560 ASTVisitor(*this, Ctx).TraverseAST(Ctx);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010561}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010562
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010563ASTContext::DynTypedNodeList
10564ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
Stephen Kelly0a717d52019-05-12 21:09:32 +010010565 std::unique_ptr<ParentMap> &P = Parents[Traversal];
10566 if (!P)
Sam McCall814e7972018-11-14 10:33:30 +000010567 // We build the parent map for the traversal scope (usually whole TU), as
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010568 // hasAncestor can escape any subtree.
Stephen Kelly0a717d52019-05-12 21:09:32 +010010569 P = std::make_unique<ParentMap>(*this);
10570 return P->getParents(Node);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010571}
10572
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010573bool
10574ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10575 const ObjCMethodDecl *MethodImpl) {
10576 // No point trying to match an unavailable/deprecated mothod.
10577 if (MethodDecl->hasAttr<UnavailableAttr>()
10578 || MethodDecl->hasAttr<DeprecatedAttr>())
10579 return false;
10580 if (MethodDecl->getObjCDeclQualifier() !=
10581 MethodImpl->getObjCDeclQualifier())
10582 return false;
Alp Toker314cc812014-01-25 16:55:45 +000010583 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010584 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010585
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010586 if (MethodDecl->param_size() != MethodImpl->param_size())
10587 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010588
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010589 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10590 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10591 EF = MethodDecl->param_end();
10592 IM != EM && IF != EF; ++IM, ++IF) {
10593 const ParmVarDecl *DeclVar = (*IF);
10594 const ParmVarDecl *ImplVar = (*IM);
10595 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10596 return false;
10597 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10598 return false;
10599 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010600
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010601 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010602}
Richard Smith053f6c62014-05-16 23:01:30 +000010603
Yaxun Liu402804b2016-12-15 08:09:08 +000010604uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +000010605 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +000010606 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +000010607 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +000010608 else
10609 AS = QT->getPointeeType().getAddressSpace();
10610
10611 return getTargetInfo().getNullPointerValue(AS);
10612}
10613
Alexander Richardson6d989432017-10-15 18:48:14 +000010614unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10615 if (isTargetAddressSpace(AS))
10616 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +000010617 else
Alexander Richardson6d989432017-10-15 18:48:14 +000010618 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +000010619}
10620
Leonard Chanab80f3c2018-06-14 14:53:51 +000010621QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
10622 assert(Ty->isFixedPointType());
10623
10624 if (Ty->isSaturatedFixedPointType()) return Ty;
10625
Simon Pilgrimeed4b122019-10-02 11:48:06 +000010626 switch (Ty->castAs<BuiltinType>()->getKind()) {
Leonard Chanab80f3c2018-06-14 14:53:51 +000010627 default:
10628 llvm_unreachable("Not a fixed point type!");
10629 case BuiltinType::ShortAccum:
10630 return SatShortAccumTy;
10631 case BuiltinType::Accum:
10632 return SatAccumTy;
10633 case BuiltinType::LongAccum:
10634 return SatLongAccumTy;
10635 case BuiltinType::UShortAccum:
10636 return SatUnsignedShortAccumTy;
10637 case BuiltinType::UAccum:
10638 return SatUnsignedAccumTy;
10639 case BuiltinType::ULongAccum:
10640 return SatUnsignedLongAccumTy;
10641 case BuiltinType::ShortFract:
10642 return SatShortFractTy;
10643 case BuiltinType::Fract:
10644 return SatFractTy;
10645 case BuiltinType::LongFract:
10646 return SatLongFractTy;
10647 case BuiltinType::UShortFract:
10648 return SatUnsignedShortFractTy;
10649 case BuiltinType::UFract:
10650 return SatUnsignedFractTy;
10651 case BuiltinType::ULongFract:
10652 return SatUnsignedLongFractTy;
10653 }
10654}
10655
Matt Arsenaultc65f9662018-08-02 12:14:28 +000010656LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
10657 if (LangOpts.OpenCL)
10658 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
10659
10660 if (LangOpts.CUDA)
10661 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
10662
10663 return getLangASFromTargetAS(AS);
10664}
10665
Richard Smith053f6c62014-05-16 23:01:30 +000010666// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10667// doesn't include ASTContext.h
10668template
10669clang::LazyGenerationalUpdatePtr<
10670 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10671clang::LazyGenerationalUpdatePtr<
10672 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10673 const clang::ASTContext &Ctx, Decl *Value);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010674
10675unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10676 assert(Ty->isFixedPointType());
10677
Leonard Chandb01c3a2018-06-20 17:19:40 +000010678 const TargetInfo &Target = getTargetInfo();
Simon Pilgrim9588ae72019-10-03 21:47:42 +000010679 switch (Ty->castAs<BuiltinType>()->getKind()) {
Leonard Chandb01c3a2018-06-20 17:19:40 +000010680 default:
10681 llvm_unreachable("Not a fixed point type!");
10682 case BuiltinType::ShortAccum:
10683 case BuiltinType::SatShortAccum:
10684 return Target.getShortAccumScale();
10685 case BuiltinType::Accum:
10686 case BuiltinType::SatAccum:
10687 return Target.getAccumScale();
10688 case BuiltinType::LongAccum:
10689 case BuiltinType::SatLongAccum:
10690 return Target.getLongAccumScale();
10691 case BuiltinType::UShortAccum:
10692 case BuiltinType::SatUShortAccum:
10693 return Target.getUnsignedShortAccumScale();
10694 case BuiltinType::UAccum:
10695 case BuiltinType::SatUAccum:
10696 return Target.getUnsignedAccumScale();
10697 case BuiltinType::ULongAccum:
10698 case BuiltinType::SatULongAccum:
10699 return Target.getUnsignedLongAccumScale();
10700 case BuiltinType::ShortFract:
10701 case BuiltinType::SatShortFract:
10702 return Target.getShortFractScale();
10703 case BuiltinType::Fract:
10704 case BuiltinType::SatFract:
10705 return Target.getFractScale();
10706 case BuiltinType::LongFract:
10707 case BuiltinType::SatLongFract:
10708 return Target.getLongFractScale();
10709 case BuiltinType::UShortFract:
10710 case BuiltinType::SatUShortFract:
10711 return Target.getUnsignedShortFractScale();
10712 case BuiltinType::UFract:
10713 case BuiltinType::SatUFract:
10714 return Target.getUnsignedFractScale();
10715 case BuiltinType::ULongFract:
10716 case BuiltinType::SatULongFract:
10717 return Target.getUnsignedLongFractScale();
10718 }
10719}
10720
10721unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10722 assert(Ty->isFixedPointType());
10723
Leonard Chandb01c3a2018-06-20 17:19:40 +000010724 const TargetInfo &Target = getTargetInfo();
Simon Pilgrim9588ae72019-10-03 21:47:42 +000010725 switch (Ty->castAs<BuiltinType>()->getKind()) {
Leonard Chandb01c3a2018-06-20 17:19:40 +000010726 default:
10727 llvm_unreachable("Not a fixed point type!");
10728 case BuiltinType::ShortAccum:
10729 case BuiltinType::SatShortAccum:
10730 return Target.getShortAccumIBits();
10731 case BuiltinType::Accum:
10732 case BuiltinType::SatAccum:
10733 return Target.getAccumIBits();
10734 case BuiltinType::LongAccum:
10735 case BuiltinType::SatLongAccum:
10736 return Target.getLongAccumIBits();
10737 case BuiltinType::UShortAccum:
10738 case BuiltinType::SatUShortAccum:
10739 return Target.getUnsignedShortAccumIBits();
10740 case BuiltinType::UAccum:
10741 case BuiltinType::SatUAccum:
10742 return Target.getUnsignedAccumIBits();
10743 case BuiltinType::ULongAccum:
10744 case BuiltinType::SatULongAccum:
10745 return Target.getUnsignedLongAccumIBits();
10746 case BuiltinType::ShortFract:
10747 case BuiltinType::SatShortFract:
10748 case BuiltinType::Fract:
10749 case BuiltinType::SatFract:
10750 case BuiltinType::LongFract:
10751 case BuiltinType::SatLongFract:
10752 case BuiltinType::UShortFract:
10753 case BuiltinType::SatUShortFract:
10754 case BuiltinType::UFract:
10755 case BuiltinType::SatUFract:
10756 case BuiltinType::ULongFract:
10757 case BuiltinType::SatULongFract:
10758 return 0;
10759 }
10760}
Leonard Chana6779422018-08-06 16:42:37 +000010761
10762FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
Erich Keane8e772162019-01-18 19:31:54 +000010763 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
10764 "Can only get the fixed point semantics for a "
10765 "fixed point or integer type.");
Leonard Chan2044ac82019-01-16 18:13:59 +000010766 if (Ty->isIntegerType())
10767 return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty),
10768 Ty->isSignedIntegerType());
10769
Leonard Chana6779422018-08-06 16:42:37 +000010770 bool isSigned = Ty->isSignedFixedPointType();
10771 return FixedPointSemantics(
10772 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
10773 Ty->isSaturatedFixedPointType(),
10774 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
10775}
10776
10777APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
10778 assert(Ty->isFixedPointType());
10779 return APFixedPoint::getMax(getFixedPointSemantics(Ty));
10780}
10781
10782APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
10783 assert(Ty->isFixedPointType());
10784 return APFixedPoint::getMin(getFixedPointSemantics(Ty));
10785}
Leonard Chan2044ac82019-01-16 18:13:59 +000010786
10787QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
10788 assert(Ty->isUnsignedFixedPointType() &&
10789 "Expected unsigned fixed point type");
Leonard Chan2044ac82019-01-16 18:13:59 +000010790
Simon Pilgrim9588ae72019-10-03 21:47:42 +000010791 switch (Ty->castAs<BuiltinType>()->getKind()) {
Leonard Chan2044ac82019-01-16 18:13:59 +000010792 case BuiltinType::UShortAccum:
10793 return ShortAccumTy;
10794 case BuiltinType::UAccum:
10795 return AccumTy;
10796 case BuiltinType::ULongAccum:
10797 return LongAccumTy;
10798 case BuiltinType::SatUShortAccum:
10799 return SatShortAccumTy;
10800 case BuiltinType::SatUAccum:
10801 return SatAccumTy;
10802 case BuiltinType::SatULongAccum:
10803 return SatLongAccumTy;
10804 case BuiltinType::UShortFract:
10805 return ShortFractTy;
10806 case BuiltinType::UFract:
10807 return FractTy;
10808 case BuiltinType::ULongFract:
10809 return LongFractTy;
10810 case BuiltinType::SatUShortFract:
10811 return SatShortFractTy;
10812 case BuiltinType::SatUFract:
10813 return SatFractTy;
10814 case BuiltinType::SatULongFract:
10815 return SatLongFractTy;
10816 default:
10817 llvm_unreachable("Unexpected unsigned fixed point type");
10818 }
10819}