blob: a2de53ca0c11c42d12181180cc9f6cb072a59002 [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"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000015#include "clang/AST/APValue.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000017#include "clang/AST/ASTTypeTraits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000018#include "clang/AST/Attr.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000019#include "clang/AST/AttrIterator.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000020#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000021#include "clang/AST/Comment.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000022#include "clang/AST/Decl.h"
23#include "clang/AST/DeclBase.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000024#include "clang/AST/DeclCXX.h"
Chandler Carruthaa36b892015-12-30 03:40:23 +000025#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000026#include "clang/AST/DeclObjC.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000027#include "clang/AST/DeclOpenMP.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000028#include "clang/AST/DeclTemplate.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000029#include "clang/AST/DeclarationName.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000030#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000031#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000032#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000033#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000034#include "clang/AST/MangleNumberingContext.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000035#include "clang/AST/NestedNameSpecifier.h"
36#include "clang/AST/RawCommentList.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000037#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000038#include "clang/AST/RecursiveASTVisitor.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000039#include "clang/AST/Stmt.h"
40#include "clang/AST/TemplateBase.h"
41#include "clang/AST/TemplateName.h"
42#include "clang/AST/Type.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000043#include "clang/AST/TypeLoc.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000044#include "clang/AST/UnresolvedSet.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000045#include "clang/AST/VTableBuilder.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000046#include "clang/Basic/AddressSpaces.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000047#include "clang/Basic/Builtins.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000048#include "clang/Basic/CommentOptions.h"
Eugene Zelenko7855e772018-04-03 00:11:50 +000049#include "clang/Basic/ExceptionSpecificationType.h"
Leonard Chana6779422018-08-06 16:42:37 +000050#include "clang/Basic/FixedPoint.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000051#include "clang/Basic/IdentifierTable.h"
52#include "clang/Basic/LLVM.h"
53#include "clang/Basic/LangOptions.h"
54#include "clang/Basic/Linkage.h"
55#include "clang/Basic/ObjCRuntime.h"
56#include "clang/Basic/SanitizerBlacklist.h"
57#include "clang/Basic/SourceLocation.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000058#include "clang/Basic/SourceManager.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000059#include "clang/Basic/Specifiers.h"
60#include "clang/Basic/TargetCXXABI.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000061#include "clang/Basic/TargetInfo.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000062#include "clang/Basic/XRayLists.h"
63#include "llvm/ADT/APInt.h"
64#include "llvm/ADT/APSInt.h"
65#include "llvm/ADT/ArrayRef.h"
66#include "llvm/ADT/DenseMap.h"
67#include "llvm/ADT/DenseSet.h"
68#include "llvm/ADT/FoldingSet.h"
69#include "llvm/ADT/None.h"
70#include "llvm/ADT/Optional.h"
71#include "llvm/ADT/PointerUnion.h"
72#include "llvm/ADT/STLExtras.h"
73#include "llvm/ADT/SmallPtrSet.h"
74#include "llvm/ADT/SmallVector.h"
Anders Carlssond8499822007-10-29 05:01:08 +000075#include "llvm/ADT/StringExtras.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000076#include "llvm/ADT/StringRef.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000077#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000078#include "llvm/Support/Capacity.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000079#include "llvm/Support/Casting.h"
80#include "llvm/Support/Compiler.h"
81#include "llvm/Support/ErrorHandling.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000082#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000083#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000084#include <algorithm>
85#include <cassert>
86#include <cstddef>
87#include <cstdint>
88#include <cstdlib>
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000089#include <map>
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000090#include <memory>
91#include <string>
92#include <tuple>
93#include <utility>
Anders Carlssona4267a62009-07-18 21:19:52 +000094
Chris Lattnerddc135e2006-11-10 06:34:16 +000095using namespace clang;
96
Steve Naroff0af91202007-04-27 21:51:21 +000097enum FloatingRank {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +000098 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +000099};
100
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000101RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000102 assert(D);
103
Jan Korous6644d012019-04-10 20:23:33 +0000104 // If we already tried to load comments but there are none,
105 // we won't find anything.
106 if (CommentsLoaded && Comments.getComments().empty())
107 return nullptr;
108
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000109 // User can not attach documentation to implicit declarations.
110 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +0000111 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000112
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000113 // User can not attach documentation to implicit instantiations.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000114 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000115 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000116 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000117 }
118
Eugene Zelenko7855e772018-04-03 00:11:50 +0000119 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000120 if (VD->isStaticDataMember() &&
121 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000122 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000123 }
124
Eugene Zelenko7855e772018-04-03 00:11:50 +0000125 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000126 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000127 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000128 }
129
Eugene Zelenko7855e772018-04-03 00:11:50 +0000130 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000131 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
132 if (TSK == TSK_ImplicitInstantiation ||
133 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000134 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000135 }
136
Eugene Zelenko7855e772018-04-03 00:11:50 +0000137 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000138 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000139 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000140 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000141 if (const auto *TD = dyn_cast<TagDecl>(D)) {
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000142 // When tag declaration (but not definition!) is part of the
143 // decl-specifier-seq of some other declaration, it doesn't get comment
144 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000145 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000146 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000147 // TODO: handle comments for function parameters properly.
148 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000149 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000150
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000151 // TODO: we could look up template parameter documentation in the template
152 // documentation.
153 if (isa<TemplateTypeParmDecl>(D) ||
154 isa<NonTypeTemplateParmDecl>(D) ||
155 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000156 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000157
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000158 // Find declaration location.
159 // For Objective-C declarations we generally don't expect to have multiple
160 // declarators, thus use declaration starting location as the "declaration
161 // location".
162 // For all other declarations multiple declarators are used quite frequently,
163 // so we use the location of the identifier as the "declaration location".
164 SourceLocation DeclLoc;
165 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000166 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000167 isa<RedeclarableTemplateDecl>(D) ||
168 isa<ClassTemplateSpecializationDecl>(D))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000169 DeclLoc = D->getBeginLoc();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000170 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000171 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000172 if (DeclLoc.isMacroID()) {
173 if (isa<TypedefDecl>(D)) {
174 // If location of the typedef name is in a macro, it is because being
175 // declared via a macro. Try using declaration's starting location as
176 // the "declaration location".
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000177 DeclLoc = D->getBeginLoc();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000178 } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000179 // If location of the tag decl is inside a macro, but the spelling of
180 // the tag name comes from a macro argument, it looks like a special
181 // macro like NS_ENUM is being used to define the tag decl. In that
182 // case, adjust the source location to the expansion loc so that we can
183 // attach the comment to the tag decl.
184 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
185 TD->isCompleteDefinition())
186 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
187 }
188 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000189 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000190
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000191 // If the declaration doesn't map directly to a location in a file, we
192 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000193 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000194 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000195
Jan Korous6644d012019-04-10 20:23:33 +0000196 if (!CommentsLoaded && ExternalSource) {
197 ExternalSource->ReadComments();
198
199#ifndef NDEBUG
200 ArrayRef<RawComment *> RawComments = Comments.getComments();
201 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
202 BeforeThanCompare<RawComment>(SourceMgr)));
203#endif
204
205 CommentsLoaded = true;
206 }
207
208 ArrayRef<RawComment *> RawComments = Comments.getComments();
209 // If there are no comments anywhere, we won't find anything.
210 if (RawComments.empty())
211 return nullptr;
212
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000213 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000214 ArrayRef<RawComment *>::iterator Comment;
215 {
216 // When searching for comments during parsing, the comment we are looking
217 // for is usually among the last two comments we parsed -- check them
218 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000219 RawComment CommentAtDeclLoc(
David L. Jones13d5a872018-03-02 00:07:45 +0000220 SourceMgr, SourceRange(DeclLoc), LangOpts.CommentOpts, false);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000221 BeforeThanCompare<RawComment> Compare(SourceMgr);
222 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
223 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
224 if (!Found && RawComments.size() >= 2) {
225 MaybeBeforeDecl--;
226 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
227 }
228
229 if (Found) {
230 Comment = MaybeBeforeDecl + 1;
231 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
232 &CommentAtDeclLoc, Compare));
233 } else {
234 // Slow path.
235 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
236 &CommentAtDeclLoc, Compare);
237 }
238 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000239
240 // Decompose the location for the declaration and find the beginning of the
241 // file buffer.
242 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
243
244 // First check whether we have a trailing comment.
245 if (Comment != RawComments.end() &&
David L. Jones13d5a872018-03-02 00:07:45 +0000246 ((*Comment)->isDocumentation() || LangOpts.CommentOpts.ParseAllComments)
247 && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000248 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000249 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000250 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000251 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000252 // Check that Doxygen trailing comment comes after the declaration, starts
253 // on the same line and in the same file as the declaration.
254 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
255 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
256 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
257 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000258 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000259 }
260 }
261
262 // The comment just after the declaration was not a trailing comment.
263 // Let's look at the previous comment.
264 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000265 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000266 --Comment;
267
268 // Check that we actually have a non-member Doxygen comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000269 if (!((*Comment)->isDocumentation() ||
270 LangOpts.CommentOpts.ParseAllComments) ||
271 (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000272 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000273
274 // Decompose the end of the comment.
275 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000276 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000277
278 // If the comment and the declaration aren't in the same file, then they
279 // aren't related.
280 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000281 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000282
283 // Get the corresponding buffer.
284 bool Invalid = false;
285 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
286 &Invalid).data();
287 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000288 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000289
290 // Extract text between the comment and declaration.
291 StringRef Text(Buffer + CommentEndDecomp.second,
292 DeclLocDecomp.second - CommentEndDecomp.second);
293
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000294 // There should be no other declarations or preprocessor directives between
295 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000296 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000297 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000298
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000299 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000300}
301
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000302/// If we have a 'templated' declaration for a template, adjust 'D' to
303/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000304/// If we have an implicit instantiation, adjust 'D' to refer to template.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000305static const Decl *adjustDeclToTemplate(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000306 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000307 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000308 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000309 return FTD;
310
311 // Nothing to do if function is not an implicit instantiation.
312 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
313 return D;
314
315 // Function is an implicit instantiation of a function template?
316 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
317 return FTD;
318
319 // Function is instantiated from a member definition of a class template?
320 if (const FunctionDecl *MemberDecl =
321 FD->getInstantiatedFromMemberFunction())
322 return MemberDecl;
323
324 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000325 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000326 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000327 // Static data member is instantiated from a member definition of a class
328 // template?
329 if (VD->isStaticDataMember())
330 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
331 return MemberDecl;
332
333 return D;
334 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000335 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000336 // Is this class declaration part of a class template?
337 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
338 return CTD;
339
340 // Class is an implicit instantiation of a class template or partial
341 // specialization?
Eugene Zelenko7855e772018-04-03 00:11:50 +0000342 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000343 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
344 return D;
345 llvm::PointerUnion<ClassTemplateDecl *,
346 ClassTemplatePartialSpecializationDecl *>
347 PU = CTSD->getSpecializedTemplateOrPartial();
348 return PU.is<ClassTemplateDecl*>() ?
349 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
350 static_cast<const Decl*>(
351 PU.get<ClassTemplatePartialSpecializationDecl *>());
352 }
353
354 // Class is instantiated from a member definition of a class template?
355 if (const MemberSpecializationInfo *Info =
356 CRD->getMemberSpecializationInfo())
357 return Info->getInstantiatedFrom();
358
359 return D;
360 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000361 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000362 // Enum is instantiated from a member definition of a class template?
363 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
364 return MemberDecl;
365
366 return D;
367 }
368 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000369 return D;
370}
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000371
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000372const RawComment *ASTContext::getRawCommentForAnyRedecl(
373 const Decl *D,
374 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000375 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000376
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000377 // Check whether we have cached a comment for this declaration already.
378 {
379 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
380 RedeclComments.find(D);
381 if (Pos != RedeclComments.end()) {
382 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000383 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
384 if (OriginalDecl)
385 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000386 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000387 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000388 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000389 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000390
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000391 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000392 const RawComment *RC = nullptr;
393 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000394 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000395 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000396 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000397 if (Pos != RedeclComments.end()) {
398 const RawCommentAndCacheFlags &Raw = Pos->second;
399 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
400 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000401 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000402 break;
403 }
404 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000405 RC = getRawCommentForDeclNoCache(I);
406 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000407 RawCommentAndCacheFlags Raw;
408 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000409 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
410 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000411 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000412 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000413 } else
414 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000415 Raw.setOriginalDecl(I);
416 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000417 if (RC)
418 break;
419 }
420 }
421
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000422 // If we found a comment, it should be a documentation comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000423 assert(!RC || RC->isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000424
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000425 if (OriginalDecl)
426 *OriginalDecl = OriginalDeclForRC;
427
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000428 // Update cache for every declaration in the redeclaration chain.
429 RawCommentAndCacheFlags Raw;
430 Raw.setRaw(RC);
431 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000432 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000433
Aaron Ballman86c93902014-03-06 23:45:36 +0000434 for (auto I : D->redecls()) {
435 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000436 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
437 R = Raw;
438 }
439
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000440 return RC;
441}
442
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000443static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
444 SmallVectorImpl<const NamedDecl *> &Redeclared) {
445 const DeclContext *DC = ObjCMethod->getDeclContext();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000446 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000447 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
448 if (!ID)
449 return;
450 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000451 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000452 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000453 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000454 ObjCMethod->isInstanceMethod()))
455 Redeclared.push_back(RedeclaredMethod);
456 }
457 }
458}
459
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000460comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
461 const Decl *D) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000462 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000463 ThisDeclInfo->CommentDecl = D;
464 ThisDeclInfo->IsFilled = false;
465 ThisDeclInfo->fill();
466 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000467 if (!ThisDeclInfo->TemplateParameters)
468 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000469 comments::FullComment *CFC =
470 new (*this) comments::FullComment(FC->getBlocks(),
471 ThisDeclInfo);
472 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000473}
474
Richard Smithb39b9d52013-05-21 05:24:00 +0000475comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
476 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000477 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000478}
479
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000480comments::FullComment *ASTContext::getCommentForDecl(
481 const Decl *D,
482 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000483 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000484 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000485 D = adjustDeclToTemplate(D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000486
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000487 const Decl *Canonical = D->getCanonicalDecl();
488 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
489 ParsedComments.find(Canonical);
Fangrui Song6907ce22018-07-30 19:24:48 +0000490
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000491 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000492 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000493 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000494 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000495 return CFC;
496 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000497 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000498 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000499
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000500 const Decl *OriginalDecl;
Fangrui Song6907ce22018-07-30 19:24:48 +0000501
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000502 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000503 if (!RC) {
504 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000505 SmallVector<const NamedDecl*, 8> Overridden;
Eugene Zelenko7855e772018-04-03 00:11:50 +0000506 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000507 if (OMD && OMD->isPropertyAccessor())
508 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
509 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
510 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000511 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000512 addRedeclaredMethods(OMD, Overridden);
513 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000514 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
515 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
516 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000517 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000518 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000519 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000520 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000521 QualType QT = TD->getUnderlyingType();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000522 if (const auto *TT = QT->getAs<TagType>())
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000523 if (const Decl *TD = TT->getDecl())
524 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000525 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000526 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000527 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000528 while (IC->getSuperClass()) {
529 IC = IC->getSuperClass();
530 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
531 return cloneFullComment(FC, D);
532 }
533 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000534 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000535 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
536 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
537 return cloneFullComment(FC, D);
538 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000539 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000540 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000541 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000542 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000543 for (const auto &I : RD->bases()) {
544 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000545 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000546 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000547 if (Ty.isNull())
548 continue;
549 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
550 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
551 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000552
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000553 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
554 return cloneFullComment(FC, D);
555 }
556 }
557 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000558 for (const auto &I : RD->vbases()) {
559 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000560 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000561 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000562 if (Ty.isNull())
563 continue;
564 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
565 if (!(VirtualBase= VirtualBase->getDefinition()))
566 continue;
567 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
568 return cloneFullComment(FC, D);
569 }
570 }
571 }
Craig Topper36250ad2014-05-12 05:36:57 +0000572 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000573 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000574
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000575 // If the RawComment was attached to other redeclaration of this Decl, we
576 // should parse the comment in context of that other Decl. This is important
577 // because comments can contain references to parameter names which can be
578 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000579 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000580 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000581
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000582 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000583 ParsedComments[Canonical] = FC;
584 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000585}
586
Fangrui Song6907ce22018-07-30 19:24:48 +0000587void
588ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000589 TemplateTemplateParmDecl *Parm) {
590 ID.AddInteger(Parm->getDepth());
591 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000592 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000593
594 TemplateParameterList *Params = Parm->getTemplateParameters();
595 ID.AddInteger(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000596 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000597 PEnd = Params->end();
598 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000599 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000600 ID.AddInteger(0);
601 ID.AddBoolean(TTP->isParameterPack());
602 continue;
603 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000604
Eugene Zelenko7855e772018-04-03 00:11:50 +0000605 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000606 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000607 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000608 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000609 if (NTTP->isExpandedParameterPack()) {
610 ID.AddBoolean(true);
611 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000612 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
613 QualType T = NTTP->getExpansionType(I);
614 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
615 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000616 } else
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000617 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000618 continue;
619 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000620
Eugene Zelenko7855e772018-04-03 00:11:50 +0000621 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000622 ID.AddInteger(2);
623 Profile(ID, TTP);
624 }
625}
626
627TemplateTemplateParmDecl *
628ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000629 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000630 // Check if we already have a canonical template template parameter.
631 llvm::FoldingSetNodeID ID;
632 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000633 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000634 CanonicalTemplateTemplateParm *Canonical
635 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
636 if (Canonical)
637 return Canonical->getParam();
Fangrui Song6907ce22018-07-30 19:24:48 +0000638
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000639 // Build a canonical template parameter list.
640 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000641 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000642 CanonParams.reserve(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000643 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000644 PEnd = Params->end();
645 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000646 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000647 CanonParams.push_back(
Fangrui Song6907ce22018-07-30 19:24:48 +0000648 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000649 SourceLocation(),
650 SourceLocation(),
651 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000652 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000653 TTP->isParameterPack()));
Eugene Zelenko7855e772018-04-03 00:11:50 +0000654 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000655 QualType T = getCanonicalType(NTTP->getType());
656 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
657 NonTypeTemplateParmDecl *Param;
658 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000659 SmallVector<QualType, 2> ExpandedTypes;
660 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000661 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
662 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
663 ExpandedTInfos.push_back(
664 getTrivialTypeSourceInfo(ExpandedTypes.back()));
665 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000666
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000667 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000668 SourceLocation(),
669 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000670 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000671 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000672 T,
673 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000674 ExpandedTypes,
675 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000676 } else {
677 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000678 SourceLocation(),
679 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000680 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000681 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000682 T,
683 NTTP->isParameterPack(),
684 TInfo);
685 }
686 CanonParams.push_back(Param);
687
688 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000689 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
690 cast<TemplateTemplateParmDecl>(*P)));
691 }
692
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000693 assert(!TTP->getRequiresClause() &&
694 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000695 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000696
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000697 TemplateTemplateParmDecl *CanonTTP
Fangrui Song6907ce22018-07-30 19:24:48 +0000698 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000699 SourceLocation(), TTP->getDepth(),
Fangrui Song6907ce22018-07-30 19:24:48 +0000700 TTP->getPosition(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000701 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000702 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000703 TemplateParameterList::Create(*this, SourceLocation(),
704 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000705 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000706 SourceLocation(),
707 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000708
709 // Get the new insert position for the node we care about.
710 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000711 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000712 (void)Canonical;
713
714 // Create the canonical template template parameter entry.
715 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
716 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
717 return CanonTTP;
718}
719
Charles Davis53c59df2010-08-16 03:33:14 +0000720CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000721 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000722
John McCall359b8852013-01-25 22:30:49 +0000723 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000724 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000725 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000726 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000727 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000728 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000729 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000730 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000731 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000732 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000733 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000734 return CreateMicrosoftCXXABI(*this);
735 }
David Blaikie8a40f702012-01-17 06:56:22 +0000736 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000737}
738
Alexander Richardson6d989432017-10-15 18:48:14 +0000739static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
740 const LangOptions &LOpts) {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000741 if (LOpts.FakeAddressSpaceMap) {
742 // The fake address space map must have a distinct entry for each
743 // language-specific address space.
744 static const unsigned FakeAddrSpaceMap[] = {
Yaxun Liub34ec822017-04-11 17:24:23 +0000745 0, // Default
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000746 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000747 3, // opencl_local
748 2, // opencl_constant
Yaxun Liub7318e02017-10-13 03:37:48 +0000749 0, // opencl_private
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000750 4, // opencl_generic
751 5, // cuda_device
752 6, // cuda_constant
753 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000754 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000755 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000756 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000757 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000758 }
759}
760
David Tweed31d09b02013-09-13 12:04:22 +0000761static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
762 const LangOptions &LangOpts) {
763 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000764 case LangOptions::ASMM_Target:
765 return TI.useAddressSpaceMapMangling();
766 case LangOptions::ASMM_On:
767 return true;
768 case LangOptions::ASMM_Off:
769 return false;
770 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000771 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000772}
773
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000774ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000775 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000776 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000777 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
778 DependentTemplateSpecializationTypes(this_()),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000779 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000780 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000781 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +0000782 LangOpts.XRayNeverInstrumentFiles,
783 LangOpts.XRayAttrListFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000784 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000785 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000786 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
787 CompCategories(this_()), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000788 TUDecl = TranslationUnitDecl::Create(*this);
Sam McCall814e7972018-11-14 10:33:30 +0000789 TraversalScope = {TUDecl};
Daniel Dunbar221fa942008-08-11 04:54:23 +0000790}
791
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000792ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000793 // Release the DenseMaps associated with DeclContext objects.
794 // FIXME: Is this the ideal solution?
795 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000796
Manuel Klimeka7328992013-06-03 13:51:33 +0000797 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000798 for (auto &Pair : Deallocations)
799 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000800
Ted Kremenek076baeb2010-06-08 23:00:58 +0000801 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000802 // because they can contain DenseMaps.
803 for (llvm::DenseMap<const ObjCContainerDecl*,
804 const ASTRecordLayout*>::iterator
805 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
806 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000807 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Douglas Gregor5b11d492010-07-25 17:53:33 +0000808 R->Destroy(*this);
809
Ted Kremenek076baeb2010-06-08 23:00:58 +0000810 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
811 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
812 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000813 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Ted Kremenek076baeb2010-06-08 23:00:58 +0000814 R->Destroy(*this);
815 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000816
Douglas Gregor561eceb2010-08-30 16:49:28 +0000817 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
818 AEnd = DeclAttrs.end();
819 A != AEnd; ++A)
820 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000821
David Majnemere694f3e2015-08-14 14:43:50 +0000822 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
823 MaterializedTemporaryValues)
824 MTVPair.second->~APValue();
825
Richard Smith423f46f2016-07-20 21:38:26 +0000826 for (const auto &Value : ModuleInitializers)
827 Value.second->~PerModuleInitializers();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000828}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000829
Sam McCall814e7972018-11-14 10:33:30 +0000830class ASTContext::ParentMap {
831 /// Contains parents of a node.
832 using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
833
834 /// Maps from a node to its parents. This is used for nodes that have
835 /// pointer identity only, which are more common and we can save space by
836 /// only storing a unique pointer to them.
837 using ParentMapPointers = llvm::DenseMap<
838 const void *,
839 llvm::PointerUnion4<const Decl *, const Stmt *,
840 ast_type_traits::DynTypedNode *, ParentVector *>>;
841
842 /// Parent map for nodes without pointer identity. We store a full
843 /// DynTypedNode for all keys.
844 using ParentMapOtherNodes = llvm::DenseMap<
845 ast_type_traits::DynTypedNode,
846 llvm::PointerUnion4<const Decl *, const Stmt *,
847 ast_type_traits::DynTypedNode *, ParentVector *>>;
848
849 ParentMapPointers PointerParents;
850 ParentMapOtherNodes OtherParents;
851 class ASTVisitor;
852
853 static ast_type_traits::DynTypedNode
854 getSingleDynTypedNodeFromParentMap(ParentMapPointers::mapped_type U) {
855 if (const auto *D = U.dyn_cast<const Decl *>())
856 return ast_type_traits::DynTypedNode::create(*D);
857 if (const auto *S = U.dyn_cast<const Stmt *>())
858 return ast_type_traits::DynTypedNode::create(*S);
859 return *U.get<ast_type_traits::DynTypedNode *>();
860 }
861
862 template <typename NodeTy, typename MapTy>
863 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
864 const MapTy &Map) {
865 auto I = Map.find(Node);
866 if (I == Map.end()) {
867 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
868 }
869 if (const auto *V = I->second.template dyn_cast<ParentVector *>()) {
870 return llvm::makeArrayRef(*V);
871 }
872 return getSingleDynTypedNodeFromParentMap(I->second);
873 }
874
875public:
876 ParentMap(ASTContext &Ctx);
877 ~ParentMap() {
878 for (const auto &Entry : PointerParents) {
879 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
880 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
881 } else if (Entry.second.is<ParentVector *>()) {
882 delete Entry.second.get<ParentVector *>();
883 }
884 }
885 for (const auto &Entry : OtherParents) {
886 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
887 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
888 } else if (Entry.second.is<ParentVector *>()) {
889 delete Entry.second.get<ParentVector *>();
890 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000891 }
892 }
Sam McCall814e7972018-11-14 10:33:30 +0000893
894 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node) {
895 if (Node.getNodeKind().hasPointerIdentity())
896 return getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
897 return getDynNodeFromMap(Node, OtherParents);
Manuel Klimek95403e62014-05-21 13:28:59 +0000898 }
Sam McCall814e7972018-11-14 10:33:30 +0000899};
900
901void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
902 TraversalScope = TopLevelDecls;
903 Parents.reset();
Manuel Klimek95403e62014-05-21 13:28:59 +0000904}
905
Douglas Gregor1a809332010-05-23 18:26:36 +0000906void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000907 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000908}
909
Mike Stump11289f42009-09-09 15:08:12 +0000910void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000911ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000912 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000913}
914
Chris Lattner4eb445d2007-01-26 01:27:23 +0000915void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000916 llvm::errs() << "\n*** AST Context Stats:\n";
917 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000918
Douglas Gregora30d0462009-05-26 14:40:08 +0000919 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000920#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000921#define ABSTRACT_TYPE(Name, Parent)
922#include "clang/AST/TypeNodes.def"
923 0 // Extra
924 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000925
Chris Lattner4eb445d2007-01-26 01:27:23 +0000926 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
927 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000928 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000929 }
930
Douglas Gregora30d0462009-05-26 14:40:08 +0000931 unsigned Idx = 0;
932 unsigned TotalBytes = 0;
933#define TYPE(Name, Parent) \
934 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000935 llvm::errs() << " " << counts[Idx] << " " << #Name \
Bruno Ricci58e03222018-08-06 15:17:32 +0000936 << " types, " << sizeof(Name##Type) << " each " \
937 << "(" << counts[Idx] * sizeof(Name##Type) \
938 << " bytes)\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000939 TotalBytes += counts[Idx] * sizeof(Name##Type); \
940 ++Idx;
941#define ABSTRACT_TYPE(Name, Parent)
942#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000943
Chandler Carruth3c147a72011-07-04 05:32:14 +0000944 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
945
Douglas Gregor7454c562010-07-02 20:37:36 +0000946 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000947 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
948 << NumImplicitDefaultConstructors
949 << " implicit default constructors created\n";
950 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
951 << NumImplicitCopyConstructors
952 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000953 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000954 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
955 << NumImplicitMoveConstructors
956 << " implicit move constructors created\n";
957 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
958 << NumImplicitCopyAssignmentOperators
959 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000960 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000961 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
962 << NumImplicitMoveAssignmentOperators
963 << " implicit move assignment operators created\n";
964 llvm::errs() << NumImplicitDestructorsDeclared << "/"
965 << NumImplicitDestructors
966 << " implicit destructors created\n";
967
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000968 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000969 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000970 ExternalSource->PrintStats();
971 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000972
Douglas Gregor5b11d492010-07-25 17:53:33 +0000973 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000974}
975
Richard Smith42413142015-05-15 20:05:43 +0000976void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
977 bool NotifyListeners) {
978 if (NotifyListeners)
979 if (auto *Listener = getASTMutationListener())
980 Listener->RedefinedHiddenDefinition(ND, M);
981
Richard Smith13897eb2018-09-12 23:37:00 +0000982 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
Richard Smith42413142015-05-15 20:05:43 +0000983}
984
985void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
Richard Smith20fbdb32018-09-12 02:13:46 +0000986 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
Richard Smith42413142015-05-15 20:05:43 +0000987 if (It == MergedDefModules.end())
988 return;
989
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000990 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000991 llvm::DenseSet<Module*> Found;
992 for (Module *&M : Merged)
993 if (!Found.insert(M).second)
994 M = nullptr;
995 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
996}
997
Richard Smithdc1f0422016-07-20 19:10:16 +0000998void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
999 if (LazyInitializers.empty())
1000 return;
1001
1002 auto *Source = Ctx.getExternalSource();
1003 assert(Source && "lazy initializers but no external source");
1004
1005 auto LazyInits = std::move(LazyInitializers);
1006 LazyInitializers.clear();
1007
1008 for (auto ID : LazyInits)
1009 Initializers.push_back(Source->GetExternalDecl(ID));
1010
1011 assert(LazyInitializers.empty() &&
1012 "GetExternalDecl for lazy module initializer added more inits");
1013}
1014
1015void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1016 // One special case: if we add a module initializer that imports another
1017 // module, and that module's only initializer is an ImportDecl, simplify.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001018 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001019 auto It = ModuleInitializers.find(ID->getImportedModule());
1020
1021 // Maybe the ImportDecl does nothing at all. (Common case.)
1022 if (It == ModuleInitializers.end())
1023 return;
1024
1025 // Maybe the ImportDecl only imports another ImportDecl.
1026 auto &Imported = *It->second;
1027 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1028 Imported.resolve(*this);
1029 auto *OnlyDecl = Imported.Initializers.front();
1030 if (isa<ImportDecl>(OnlyDecl))
1031 D = OnlyDecl;
1032 }
1033 }
1034
1035 auto *&Inits = ModuleInitializers[M];
1036 if (!Inits)
1037 Inits = new (*this) PerModuleInitializers;
1038 Inits->Initializers.push_back(D);
1039}
1040
1041void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1042 auto *&Inits = ModuleInitializers[M];
1043 if (!Inits)
1044 Inits = new (*this) PerModuleInitializers;
1045 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1046 IDs.begin(), IDs.end());
1047}
1048
Eugene Zelenko7855e772018-04-03 00:11:50 +00001049ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001050 auto It = ModuleInitializers.find(M);
Fangrui Song6907ce22018-07-30 19:24:48 +00001051 if (It == ModuleInitializers.end())
Richard Smithdc1f0422016-07-20 19:10:16 +00001052 return None;
1053
1054 auto *Inits = It->second;
1055 Inits->resolve(*this);
1056 return Inits->Initializers;
1057}
1058
Richard Smithf19e1272015-03-07 00:04:49 +00001059ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1060 if (!ExternCContext)
1061 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1062
1063 return ExternCContext;
1064}
1065
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001066BuiltinTemplateDecl *
1067ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1068 const IdentifierInfo *II) const {
1069 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1070 BuiltinTemplate->setImplicit();
1071 TUDecl->addDecl(BuiltinTemplate);
1072
1073 return BuiltinTemplate;
1074}
1075
1076BuiltinTemplateDecl *
1077ASTContext::getMakeIntegerSeqDecl() const {
1078 if (!MakeIntegerSeqDecl)
1079 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1080 getMakeIntegerSeqName());
1081 return MakeIntegerSeqDecl;
1082}
1083
Eric Fiselier6ad68552016-07-01 01:24:09 +00001084BuiltinTemplateDecl *
1085ASTContext::getTypePackElementDecl() const {
1086 if (!TypePackElementDecl)
1087 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1088 getTypePackElementName());
1089 return TypePackElementDecl;
1090}
1091
Alp Toker2dea15b2013-12-17 01:22:38 +00001092RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1093 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001094 SourceLocation Loc;
1095 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001096 if (getLangOpts().CPlusPlus)
1097 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1098 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001099 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001100 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1101 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001102 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001103 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1104 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001105 return NewDecl;
1106}
1107
1108TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1109 StringRef Name) const {
1110 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1111 TypedefDecl *NewDecl = TypedefDecl::Create(
1112 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1113 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1114 NewDecl->setImplicit();
1115 return NewDecl;
1116}
1117
Douglas Gregor801c99d2011-08-12 06:49:56 +00001118TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001119 if (!Int128Decl)
1120 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001121 return Int128Decl;
1122}
1123
1124TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001125 if (!UInt128Decl)
1126 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001127 return UInt128Decl;
1128}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001129
John McCall48f2d582009-10-23 23:03:21 +00001130void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001131 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001132 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001133 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001134}
1135
Artem Belevichb5bc9232015-09-22 17:23:22 +00001136void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1137 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001138 assert((!this->Target || this->Target == &Target) &&
1139 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001140 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001141
Douglas Gregore8bbc122011-09-02 00:18:52 +00001142 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001143 this->AuxTarget = AuxTarget;
1144
Douglas Gregore8bbc122011-09-02 00:18:52 +00001145 ABI.reset(createCXXABI(Target));
1146 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001147 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Fangrui Song6907ce22018-07-30 19:24:48 +00001148
Chris Lattner970e54e2006-11-12 00:37:36 +00001149 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001150 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001151
Chris Lattner970e54e2006-11-12 00:37:36 +00001152 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001153 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001154 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001155 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001156 InitBuiltinType(CharTy, BuiltinType::Char_S);
1157 else
1158 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001159 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001160 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1161 InitBuiltinType(ShortTy, BuiltinType::Short);
1162 InitBuiltinType(IntTy, BuiltinType::Int);
1163 InitBuiltinType(LongTy, BuiltinType::Long);
1164 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001165
Chris Lattner970e54e2006-11-12 00:37:36 +00001166 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001167 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1168 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1169 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1170 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1171 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001172
Chris Lattner970e54e2006-11-12 00:37:36 +00001173 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001174 InitBuiltinType(FloatTy, BuiltinType::Float);
1175 InitBuiltinType(DoubleTy, BuiltinType::Double);
1176 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001177
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001178 // GNU extension, __float128 for IEEE quadruple precision
1179 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1180
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001181 // C11 extension ISO/IEC TS 18661-3
1182 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1183
Leonard Chanf921d852018-06-04 16:07:52 +00001184 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
Leonard Chanab80f3c2018-06-14 14:53:51 +00001185 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1186 InitBuiltinType(AccumTy, BuiltinType::Accum);
1187 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1188 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1189 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1190 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1191 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1192 InitBuiltinType(FractTy, BuiltinType::Fract);
1193 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1194 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1195 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1196 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1197 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1198 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1199 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1200 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1201 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1202 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1203 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1204 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1205 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1206 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1207 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1208 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
Leonard Chanf921d852018-06-04 16:07:52 +00001209
Chris Lattnerf122cef2009-04-30 02:43:43 +00001210 // GNU extension, 128-bit integers.
1211 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1212 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1213
Hans Wennborg0d81e012013-05-10 10:08:40 +00001214 // C++ 3.9.1p5
1215 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1216 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1217 else // -fshort-wchar makes wchar_t be unsigned.
1218 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1219 if (LangOpts.CPlusPlus && LangOpts.WChar)
1220 WideCharTy = WCharTy;
1221 else {
1222 // C99 (or C++ using -fno-wchar).
1223 WideCharTy = getFromTargetType(Target.getWCharType());
1224 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001225
James Molloy36365542012-05-04 10:55:22 +00001226 WIntTy = getFromTargetType(Target.getWIntType());
1227
Richard Smith3a8244d2018-05-01 05:02:45 +00001228 // C++20 (proposed)
1229 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1230
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001231 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1232 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1233 else // C99
1234 Char16Ty = getFromTargetType(Target.getChar16Type());
1235
1236 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1237 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1238 else // C99
1239 Char32Ty = getFromTargetType(Target.getChar32Type());
1240
Douglas Gregor4619e432008-12-05 23:32:09 +00001241 // Placeholder type for type-dependent expressions whose type is
1242 // completely unknown. No code should ever check a type against
1243 // DependentTy and users should never see it; however, it is here to
1244 // help diagnose failures to properly check for type-dependent
1245 // expressions.
1246 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001247
John McCall36e7fe32010-10-12 00:20:44 +00001248 // Placeholder type for functions.
1249 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1250
John McCall0009fcc2011-04-26 20:42:42 +00001251 // Placeholder type for bound members.
1252 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1253
John McCall526ab472011-10-25 17:37:35 +00001254 // Placeholder type for pseudo-objects.
1255 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1256
John McCall31996342011-04-07 08:22:57 +00001257 // "any" type; useful for debugger-like clients.
1258 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1259
John McCall8a6b59a2011-10-17 18:09:15 +00001260 // Placeholder type for unbridged ARC casts.
1261 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1262
Eli Friedman34866c72012-08-31 00:14:07 +00001263 // Placeholder type for builtin functions.
1264 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1265
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001266 // Placeholder type for OMP array sections.
1267 if (LangOpts.OpenMP)
1268 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1269
Chris Lattner970e54e2006-11-12 00:37:36 +00001270 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001271 FloatComplexTy = getComplexType(FloatTy);
1272 DoubleComplexTy = getComplexType(DoubleTy);
1273 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001274 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001275
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001276 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001277 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1278 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001279 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001280
Alexey Bader954ba212016-04-08 13:40:33 +00001281 if (LangOpts.OpenCL) {
1282#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1283 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001284#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001285
Guy Benyei61054192013-02-07 10:55:47 +00001286 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001287 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001288 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1289 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001290 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001291
1292#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1293 InitBuiltinType(Id##Ty, BuiltinType::Id);
1294#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001295 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001296
Ted Kremeneke65b0862012-03-06 20:05:56 +00001297 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001298 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1299 SignedCharTy : BoolTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001300
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001301 ObjCConstantStringType = QualType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001302
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001303 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001304
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001305 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001306 if (LangOpts.OpenCLVersion >= 200) {
1307 auto Q = VoidTy.getQualifiers();
1308 Q.setAddressSpace(LangAS::opencl_generic);
1309 VoidPtrTy = getPointerType(getCanonicalType(
1310 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1311 } else {
1312 VoidPtrTy = getPointerType(VoidTy);
1313 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001314
1315 // nullptr type (C++0x 2.14.7)
1316 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001317
1318 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1319 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001320
1321 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001322 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001323}
1324
David Blaikie9c902b52011-09-25 23:23:43 +00001325DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001326 return SourceMgr.getDiagnostics();
1327}
1328
Douglas Gregor561eceb2010-08-30 16:49:28 +00001329AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1330 AttrVec *&Result = DeclAttrs[D];
1331 if (!Result) {
1332 void *Mem = Allocate(sizeof(AttrVec));
1333 Result = new (Mem) AttrVec;
1334 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001335
Douglas Gregor561eceb2010-08-30 16:49:28 +00001336 return *Result;
1337}
1338
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001339/// Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001340void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001341 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1342 if (Pos != DeclAttrs.end()) {
1343 Pos->second->~AttrVec();
1344 DeclAttrs.erase(Pos);
1345 }
1346}
1347
Larisse Voufo39a1e502013-08-06 01:03:05 +00001348// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001349MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001350ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001351 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001352 return getTemplateOrSpecializationInfo(Var)
1353 .dyn_cast<MemberSpecializationInfo *>();
1354}
1355
1356ASTContext::TemplateOrSpecializationInfo
1357ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1358 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1359 TemplateOrInstantiation.find(Var);
1360 if (Pos == TemplateOrInstantiation.end())
Eugene Zelenko7855e772018-04-03 00:11:50 +00001361 return {};
Mike Stump11289f42009-09-09 15:08:12 +00001362
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001363 return Pos->second;
1364}
1365
Mike Stump11289f42009-09-09 15:08:12 +00001366void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001367ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001368 TemplateSpecializationKind TSK,
1369 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001370 assert(Inst->isStaticDataMember() && "Not a static data member");
1371 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001372 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1373 Tmpl, TSK, PointOfInstantiation));
1374}
1375
1376void
1377ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1378 TemplateOrSpecializationInfo TSI) {
1379 assert(!TemplateOrInstantiation[Inst] &&
1380 "Already noted what the variable was instantiated from");
1381 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001382}
1383
John McCalle61f2ba2009-11-18 02:36:19 +00001384NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001385ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1386 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001387 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001388 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001389
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001390 return Pos->second;
1391}
1392
1393void
Richard Smithd8a9e372016-12-18 21:39:37 +00001394ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001395 assert((isa<UsingDecl>(Pattern) ||
1396 isa<UnresolvedUsingValueDecl>(Pattern) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001397 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
John McCallb96ec562009-12-04 22:46:56 +00001398 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001399 assert((isa<UsingDecl>(Inst) ||
1400 isa<UnresolvedUsingValueDecl>(Inst) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001401 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
Richard Smithd8a9e372016-12-18 21:39:37 +00001402 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001403 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1404 InstantiatedFromUsingDecl[Inst] = Pattern;
1405}
1406
1407UsingShadowDecl *
1408ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1409 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1410 = InstantiatedFromUsingShadowDecl.find(Inst);
1411 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001412 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001413
1414 return Pos->second;
1415}
1416
1417void
1418ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1419 UsingShadowDecl *Pattern) {
1420 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1421 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001422}
1423
Anders Carlsson5da84842009-09-01 04:26:58 +00001424FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1425 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1426 = InstantiatedFromUnnamedFieldDecl.find(Field);
1427 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001428 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001429
Anders Carlsson5da84842009-09-01 04:26:58 +00001430 return Pos->second;
1431}
1432
1433void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1434 FieldDecl *Tmpl) {
1435 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1436 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1437 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1438 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001439
Anders Carlsson5da84842009-09-01 04:26:58 +00001440 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1441}
1442
Douglas Gregor832940b2010-03-02 23:58:15 +00001443ASTContext::overridden_cxx_method_iterator
1444ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001445 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001446}
1447
1448ASTContext::overridden_cxx_method_iterator
1449ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001450 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001451}
1452
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001453unsigned
1454ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001455 auto Range = overridden_methods(Method);
1456 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001457}
1458
Clement Courbet6ecaec82016-07-05 07:49:31 +00001459ASTContext::overridden_method_range
1460ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001461 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1462 OverriddenMethods.find(Method->getCanonicalDecl());
1463 if (Pos == OverriddenMethods.end())
1464 return overridden_method_range(nullptr, nullptr);
1465 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001466}
1467
Fangrui Song6907ce22018-07-30 19:24:48 +00001468void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
Douglas Gregor832940b2010-03-02 23:58:15 +00001469 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001470 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001471 OverriddenMethods[Method].push_back(Overridden);
1472}
1473
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001474void ASTContext::getOverriddenMethods(
1475 const NamedDecl *D,
1476 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001477 assert(D);
1478
Eugene Zelenko7855e772018-04-03 00:11:50 +00001479 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001480 Overridden.append(overridden_methods_begin(CXXMethod),
1481 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001482 return;
1483 }
1484
Eugene Zelenko7855e772018-04-03 00:11:50 +00001485 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001486 if (!Method)
1487 return;
1488
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001489 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1490 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001491 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001492}
1493
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001494void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1495 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1496 assert(!Import->isFromASTFile() && "Non-local import declaration");
1497 if (!FirstLocalImport) {
1498 FirstLocalImport = Import;
1499 LastLocalImport = Import;
1500 return;
1501 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001502
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001503 LastLocalImport->NextLocalImport = Import;
1504 LastLocalImport = Import;
1505}
1506
Chris Lattner53cfe802007-07-18 17:52:12 +00001507//===----------------------------------------------------------------------===//
1508// Type Sizing and Analysis
1509//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001510
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001511/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1512/// scalar floating point type.
1513const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001514 const auto *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001515 assert(BT && "Not a floating point type!");
1516 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001517 default: llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001518 case BuiltinType::Float16:
1519 case BuiltinType::Half:
1520 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001521 case BuiltinType::Float: return Target->getFloatFormat();
1522 case BuiltinType::Double: return Target->getDoubleFormat();
1523 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001524 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001525 }
1526}
1527
Rafael Espindola71eccb32013-08-08 19:53:46 +00001528CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001529 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001530
John McCall94268702010-10-08 18:24:19 +00001531 bool UseAlignAttrOnly = false;
1532 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1533 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001534
John McCall94268702010-10-08 18:24:19 +00001535 // __attribute__((aligned)) can increase or decrease alignment
1536 // *except* on a struct or struct member, where it only increases
1537 // alignment unless 'packed' is also specified.
1538 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001539 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001540 // ignore that possibility; Sema should diagnose it.
1541 if (isa<FieldDecl>(D)) {
1542 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1543 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1544 } else {
1545 UseAlignAttrOnly = true;
1546 }
1547 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001548 else if (isa<FieldDecl>(D))
Fangrui Song6907ce22018-07-30 19:24:48 +00001549 UseAlignAttrOnly =
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001550 D->hasAttr<PackedAttr>() ||
1551 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001552
John McCall4e819612011-01-20 07:57:12 +00001553 // If we're using the align attribute only, just ignore everything
1554 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001555 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001556 // do nothing
Eugene Zelenko7855e772018-04-03 00:11:50 +00001557 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001558 QualType T = VD->getType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001559 if (const auto *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001560 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001561 T = RT->getPointeeType();
1562 else
1563 T = getPointerType(RT->getPointeeType());
1564 }
Richard Smithf6d70302014-06-10 23:34:28 +00001565 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001566 if (T->isFunctionType())
1567 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1568 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001569 // Adjust alignments of declarations with array type by the
1570 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001571 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001572 unsigned MinWidth = Target->getLargeArrayMinWidth();
1573 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001574 if (isa<VariableArrayType>(arrayType))
1575 Align = std::max(Align, Target->getLargeArrayAlign());
1576 else if (isa<ConstantArrayType>(arrayType) &&
1577 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1578 Align = std::max(Align, Target->getLargeArrayAlign());
1579 }
John McCall33ddac02011-01-19 10:06:00 +00001580 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001581 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001582 if (BaseT.getQualifiers().hasUnaligned())
1583 Align = Target->getCharWidth();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001584 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Tom Tanb7c6d952019-05-02 00:38:14 +00001585 if (VD->hasGlobalStorage() && !ForAlignof) {
1586 uint64_t TypeSize = getTypeSize(T.getTypePtr());
1587 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1588 }
Ulrich Weigandfa806422013-05-06 16:23:57 +00001589 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001590 }
John McCall4e819612011-01-20 07:57:12 +00001591
1592 // Fields can be subject to extra alignment constraints, like if
1593 // the field is packed, the struct is packed, or the struct has a
1594 // a max-field-alignment constraint (#pragma pack). So calculate
1595 // the actual alignment of the field within the struct, and then
1596 // (as we're expected to) constrain that by the alignment of the type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001597 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001598 const RecordDecl *Parent = Field->getParent();
1599 // We can only produce a sensible answer if the record is valid.
1600 if (!Parent->isInvalidDecl()) {
1601 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001602
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001603 // Start with the record's overall alignment.
1604 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001605
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001606 // Use the GCD of that and the offset within the record.
1607 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1608 if (Offset > 0) {
1609 // Alignment is always a power of 2, so the GCD will be a power of 2,
1610 // which means we get to do this crazy thing instead of Euclid's.
1611 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1612 if (LowBitOfOffset < FieldAlign)
1613 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1614 }
1615
1616 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001617 }
Charles Davis3fc51072010-02-23 04:52:00 +00001618 }
Chris Lattner68061312009-01-24 21:53:27 +00001619 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001620
Ken Dyckcc56c542011-01-15 18:38:59 +00001621 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001622}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001623
John McCallf1249922012-08-21 04:10:00 +00001624// getTypeInfoDataSizeInChars - Return the size of a type, in
1625// chars. If the type is a record, its data size is returned. This is
1626// the size of the memcpy that's performed when assigning this type
1627// using a trivial copy/move assignment operator.
1628std::pair<CharUnits, CharUnits>
1629ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1630 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1631
1632 // In C++, objects can sometimes be allocated into the tail padding
1633 // of a base-class subobject. We decide whether that's possible
1634 // during class layout, so here we can just trust the layout results.
1635 if (getLangOpts().CPlusPlus) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001636 if (const auto *RT = T->getAs<RecordType>()) {
John McCallf1249922012-08-21 04:10:00 +00001637 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1638 sizeAndAlign.first = layout.getDataSize();
1639 }
1640 }
1641
1642 return sizeAndAlign;
1643}
1644
Richard Trieu04d2d942013-05-14 21:59:17 +00001645/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1646/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1647std::pair<CharUnits, CharUnits>
1648static getConstantArrayInfoInChars(const ASTContext &Context,
1649 const ConstantArrayType *CAT) {
1650 std::pair<CharUnits, CharUnits> EltInfo =
1651 Context.getTypeInfoInChars(CAT->getElementType());
1652 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001653 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1654 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001655 "Overflow in array type char size evaluation");
1656 uint64_t Width = EltInfo.first.getQuantity() * Size;
1657 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001658 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1659 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001660 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001661 return std::make_pair(CharUnits::fromQuantity(Width),
1662 CharUnits::fromQuantity(Align));
1663}
1664
John McCall87fe5d52010-05-20 01:18:31 +00001665std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001666ASTContext::getTypeInfoInChars(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001667 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
Richard Trieu04d2d942013-05-14 21:59:17 +00001668 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001669 TypeInfo Info = getTypeInfo(T);
1670 return std::make_pair(toCharUnitsFromBits(Info.Width),
1671 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001672}
1673
1674std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001675ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001676 return getTypeInfoInChars(T.getTypePtr());
1677}
1678
David Majnemer34b57492014-07-30 01:30:47 +00001679bool ASTContext::isAlignmentRequired(const Type *T) const {
1680 return getTypeInfo(T).AlignIsRequired;
1681}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001682
David Majnemer34b57492014-07-30 01:30:47 +00001683bool ASTContext::isAlignmentRequired(QualType T) const {
1684 return isAlignmentRequired(T.getTypePtr());
1685}
1686
Richard Smithb2f0f052016-10-10 18:54:32 +00001687unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1688 // An alignment on a typedef overrides anything else.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001689 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001690 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1691 return Align;
1692
1693 // If we have an (array of) complete type, we're done.
1694 T = getBaseElementType(T);
1695 if (!T->isIncompleteType())
1696 return getTypeAlign(T);
1697
1698 // If we had an array type, its element type might be a typedef
1699 // type with an alignment attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001700 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001701 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1702 return Align;
1703
1704 // Otherwise, see if the declaration of the type had an attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001705 if (const auto *TT = T->getAs<TagType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001706 return TT->getDecl()->getMaxAlignment();
1707
1708 return 0;
1709}
1710
David Majnemer34b57492014-07-30 01:30:47 +00001711TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001712 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1713 if (I != MemoizedTypeInfo.end())
1714 return I->second;
1715
1716 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1717 TypeInfo TI = getTypeInfoImpl(T);
1718 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001719 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001720}
1721
1722/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1723/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001724///
1725/// FIXME: Pointers into different addr spaces could have different sizes and
1726/// alignment requirements: getPointerInfo should take an AddrSpace, this
1727/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001728TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1729 uint64_t Width = 0;
1730 unsigned Align = 8;
1731 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001732 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001733 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001734#define TYPE(Class, Base)
1735#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001736#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001737#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001738#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1739 case Type::Class: \
1740 assert(!T->isDependentType() && "should not see dependent types here"); \
1741 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001742#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001743 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001744
Chris Lattner355332d2007-07-13 22:27:08 +00001745 case Type::FunctionNoProto:
1746 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001747 // GCC extension: alignof(function) = 32 bits
1748 Width = 0;
1749 Align = 32;
1750 break;
1751
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001752 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001753 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001754 Width = 0;
1755 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1756 break;
1757
Steve Naroff5c131802007-08-30 01:06:46 +00001758 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001759 const auto *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001760
David Majnemer34b57492014-07-30 01:30:47 +00001761 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001762 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001763 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001764 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001765 Width = EltInfo.Width * Size;
1766 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001767 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1768 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001769 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001770 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001771 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001772 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001773 case Type::Vector: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001774 const auto *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001775 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1776 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001777 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001778 // If the alignment is not a power of 2, round up to the next power of 2.
1779 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001780 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001781 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001782 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001783 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001784 // Adjust the alignment based on the target max.
1785 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1786 if (TargetVectorAlign && TargetVectorAlign < Align)
1787 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001788 break;
1789 }
Chris Lattner647fb222007-07-18 18:26:58 +00001790
Chris Lattner7570e9c2008-03-08 08:52:55 +00001791 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001792 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001793 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001794 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001795 // GCC extension: alignof(void) = 8 bits.
1796 Width = 0;
1797 Align = 8;
1798 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001799 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001800 Width = Target->getBoolWidth();
1801 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001802 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001803 case BuiltinType::Char_S:
1804 case BuiltinType::Char_U:
1805 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001806 case BuiltinType::SChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00001807 case BuiltinType::Char8:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001808 Width = Target->getCharWidth();
1809 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001810 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001811 case BuiltinType::WChar_S:
1812 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001813 Width = Target->getWCharWidth();
1814 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001815 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001816 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001817 Width = Target->getChar16Width();
1818 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001819 break;
1820 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001821 Width = Target->getChar32Width();
1822 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001823 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001824 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001825 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001826 Width = Target->getShortWidth();
1827 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001828 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001829 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001830 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001831 Width = Target->getIntWidth();
1832 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001833 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001834 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001835 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001836 Width = Target->getLongWidth();
1837 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001838 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001839 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001840 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001841 Width = Target->getLongLongWidth();
1842 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001843 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001844 case BuiltinType::Int128:
1845 case BuiltinType::UInt128:
1846 Width = 128;
1847 Align = 128; // int128_t is 128-bit aligned on all targets.
1848 break;
Leonard Chanf921d852018-06-04 16:07:52 +00001849 case BuiltinType::ShortAccum:
1850 case BuiltinType::UShortAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001851 case BuiltinType::SatShortAccum:
1852 case BuiltinType::SatUShortAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001853 Width = Target->getShortAccumWidth();
1854 Align = Target->getShortAccumAlign();
1855 break;
1856 case BuiltinType::Accum:
1857 case BuiltinType::UAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001858 case BuiltinType::SatAccum:
1859 case BuiltinType::SatUAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001860 Width = Target->getAccumWidth();
1861 Align = Target->getAccumAlign();
1862 break;
1863 case BuiltinType::LongAccum:
1864 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001865 case BuiltinType::SatLongAccum:
1866 case BuiltinType::SatULongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001867 Width = Target->getLongAccumWidth();
1868 Align = Target->getLongAccumAlign();
1869 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00001870 case BuiltinType::ShortFract:
1871 case BuiltinType::UShortFract:
1872 case BuiltinType::SatShortFract:
1873 case BuiltinType::SatUShortFract:
1874 Width = Target->getShortFractWidth();
1875 Align = Target->getShortFractAlign();
1876 break;
1877 case BuiltinType::Fract:
1878 case BuiltinType::UFract:
1879 case BuiltinType::SatFract:
1880 case BuiltinType::SatUFract:
1881 Width = Target->getFractWidth();
1882 Align = Target->getFractAlign();
1883 break;
1884 case BuiltinType::LongFract:
1885 case BuiltinType::ULongFract:
1886 case BuiltinType::SatLongFract:
1887 case BuiltinType::SatULongFract:
1888 Width = Target->getLongFractWidth();
1889 Align = Target->getLongFractAlign();
1890 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001891 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001892 case BuiltinType::Half:
Alexey Bataev123ad192019-02-27 20:29:45 +00001893 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
1894 !getLangOpts().OpenMPIsDevice) {
1895 Width = Target->getHalfWidth();
1896 Align = Target->getHalfAlign();
1897 } else {
1898 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1899 "Expected OpenMP device compilation.");
1900 Width = AuxTarget->getHalfWidth();
1901 Align = AuxTarget->getHalfAlign();
1902 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001903 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001904 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001905 Width = Target->getFloatWidth();
1906 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001907 break;
1908 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001909 Width = Target->getDoubleWidth();
1910 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001911 break;
1912 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001913 Width = Target->getLongDoubleWidth();
1914 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001915 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001916 case BuiltinType::Float128:
Alexey Bataev123ad192019-02-27 20:29:45 +00001917 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
1918 !getLangOpts().OpenMPIsDevice) {
1919 Width = Target->getFloat128Width();
1920 Align = Target->getFloat128Align();
1921 } else {
1922 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1923 "Expected OpenMP device compilation.");
1924 Width = AuxTarget->getFloat128Width();
1925 Align = AuxTarget->getFloat128Align();
1926 }
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001927 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001928 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001929 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1930 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001931 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001932 case BuiltinType::ObjCId:
1933 case BuiltinType::ObjCClass:
1934 case BuiltinType::ObjCSel:
Fangrui Song6907ce22018-07-30 19:24:48 +00001935 Width = Target->getPointerWidth(0);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001936 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001937 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001938 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001939 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001940 case BuiltinType::OCLClkEvent:
1941 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001942 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00001943#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1944 case BuiltinType::Id:
1945#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001946#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1947 case BuiltinType::Id:
1948#include "clang/Basic/OpenCLExtensionTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00001949 AS = getTargetAddressSpace(
1950 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001951 Width = Target->getPointerWidth(AS);
1952 Align = Target->getPointerAlign(AS);
1953 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001954 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001955 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001956 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001957 Width = Target->getPointerWidth(0);
1958 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001959 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001960 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001961 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001962 Width = Target->getPointerWidth(AS);
1963 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001964 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001965 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001966 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001967 // alignof and sizeof should never enter this code path here, so we go
1968 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001969 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001970 Width = Target->getPointerWidth(AS);
1971 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001972 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001973 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001974 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001975 Width = Target->getPointerWidth(AS);
1976 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001977 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001978 case Type::MemberPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001979 const auto *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00001980 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
1981 Width = MPI.Width;
1982 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00001983 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001984 }
Chris Lattner647fb222007-07-18 18:26:58 +00001985 case Type::Complex: {
1986 // Complex types have the same alignment as their elements, but twice the
1987 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001988 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1989 Width = EltInfo.Width * 2;
1990 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001991 break;
1992 }
John McCall8b07ec22010-05-15 11:32:37 +00001993 case Type::ObjCObject:
1994 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001995 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001996 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001997 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001998 case Type::ObjCInterface: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001999 const auto *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00002000 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00002001 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002002 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00002003 break;
2004 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002005 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002006 case Type::Enum: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002007 const auto *TT = cast<TagType>(T);
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00002008
2009 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00002010 Width = 8;
2011 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00002012 break;
2013 }
Mike Stump11289f42009-09-09 15:08:12 +00002014
Eugene Zelenko7855e772018-04-03 00:11:50 +00002015 if (const auto *ET = dyn_cast<EnumType>(TT)) {
David Majnemer475b25e2015-01-21 10:54:38 +00002016 const EnumDecl *ED = ET->getDecl();
2017 TypeInfo Info =
2018 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2019 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2020 Info.Align = AttrAlign;
2021 Info.AlignIsRequired = true;
2022 }
2023 return Info;
2024 }
Chris Lattner8b23c252008-04-06 22:05:18 +00002025
Eugene Zelenko7855e772018-04-03 00:11:50 +00002026 const auto *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00002027 const RecordDecl *RD = RT->getDecl();
2028 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00002029 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002030 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00002031 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00002032 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00002033 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002034
Chris Lattner63d2b362009-10-22 05:17:15 +00002035 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00002036 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2037 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00002038
Richard Smith600b5262017-01-26 20:40:47 +00002039 case Type::Auto:
2040 case Type::DeducedTemplateSpecialization: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002041 const auto *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00002042 assert(!A->getDeducedType().isNull() &&
2043 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00002044 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00002045 }
2046
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002047 case Type::Paren:
2048 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2049
Leonard Chanc72aaf62019-05-07 03:20:17 +00002050 case Type::MacroQualified:
2051 return getTypeInfo(
2052 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2053
Manman Rene6be26c2016-09-13 17:25:08 +00002054 case Type::ObjCTypeParam:
2055 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2056
Douglas Gregoref462e62009-04-30 17:32:17 +00002057 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00002058 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00002059 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00002060 // If the typedef has an aligned attribute on it, it overrides any computed
2061 // alignment we have. This violates the GCC documentation (which says that
2062 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00002063 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00002064 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00002065 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00002066 } else {
David Majnemer34b57492014-07-30 01:30:47 +00002067 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00002068 AlignIsRequired = Info.AlignIsRequired;
2069 }
David Majnemer34b57492014-07-30 01:30:47 +00002070 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00002071 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00002072 }
Douglas Gregoref462e62009-04-30 17:32:17 +00002073
Abramo Bagnara6150c882010-05-11 21:36:43 +00002074 case Type::Elaborated:
2075 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00002076
John McCall81904512011-01-06 01:58:22 +00002077 case Type::Attributed:
2078 return getTypeInfo(
2079 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2080
Eli Friedman0dfb8892011-10-06 23:00:33 +00002081 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00002082 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00002083 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2084 Width = Info.Width;
2085 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00002086
JF Bastien801fca22018-05-09 03:51:12 +00002087 if (!Width) {
2088 // An otherwise zero-sized type should still generate an
2089 // atomic operation.
2090 Width = Target->getCharWidth();
2091 assert(Align);
2092 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2093 // If the size of the type doesn't exceed the platform's max
2094 // atomic promotion width, make the size and alignment more
2095 // favorable to atomic operations:
2096
John McCalla8ec7eb2013-03-07 21:37:17 +00002097 // Round the size up to a power of 2.
2098 if (!llvm::isPowerOf2_64(Width))
2099 Width = llvm::NextPowerOf2(Width);
2100
2101 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002102 Align = static_cast<unsigned>(Width);
2103 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00002104 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00002105 break;
2106
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002107 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00002108 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2109 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002110 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00002111 }
Mike Stump11289f42009-09-09 15:08:12 +00002112
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002113 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00002114 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00002115}
2116
Momchil Velikov20208cc2018-07-30 17:48:23 +00002117unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2118 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2119 if (I != MemoizedUnadjustedAlign.end())
2120 return I->second;
2121
2122 unsigned UnadjustedAlign;
2123 if (const auto *RT = T->getAs<RecordType>()) {
2124 const RecordDecl *RD = RT->getDecl();
2125 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2126 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2127 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2128 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2129 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2130 } else {
2131 UnadjustedAlign = getTypeAlign(T);
2132 }
2133
2134 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2135 return UnadjustedAlign;
2136}
2137
Alexey Bataev00396512015-07-02 03:40:19 +00002138unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2139 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2140 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2141 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2142 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2143 getTargetInfo().getABI() == "elfv1-qpx" &&
2144 T->isSpecificBuiltinType(BuiltinType::Double))
2145 SimdAlign = 256;
2146 return SimdAlign;
2147}
2148
Ken Dyckcc56c542011-01-15 18:38:59 +00002149/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2150CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2151 return CharUnits::fromQuantity(BitSize / getCharWidth());
2152}
2153
Ken Dyckb0fcc592011-02-11 01:54:29 +00002154/// toBits - Convert a size in characters to a size in characters.
2155int64_t ASTContext::toBits(CharUnits CharSize) const {
2156 return CharSize.getQuantity() * getCharWidth();
2157}
2158
Ken Dyck8c89d592009-12-22 14:23:30 +00002159/// getTypeSizeInChars - Return the size of the specified type, in characters.
2160/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002161CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002162 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002163}
Jay Foad39c79802011-01-12 09:06:06 +00002164CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002165 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002166}
2167
Fangrui Song6907ce22018-07-30 19:24:48 +00002168/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002169/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002170CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002171 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002172}
Jay Foad39c79802011-01-12 09:06:06 +00002173CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002174 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002175}
2176
Momchil Velikov20208cc2018-07-30 17:48:23 +00002177/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2178/// type, in characters, before alignment adustments. This method does
2179/// not work on incomplete types.
2180CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2181 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2182}
2183CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2184 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2185}
2186
Chris Lattnera3402cd2009-01-27 18:08:34 +00002187/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2188/// type for the current target in bits. This can be different than the ABI
2189/// alignment in cases where it is beneficial for performance to overalign
2190/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002191unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002192 TypeInfo TI = getTypeInfo(T);
2193 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002194
David Majnemere1544562015-04-24 01:25:05 +00002195 T = T->getBaseElementTypeUnsafe();
2196
2197 // The preferred alignment of member pointers is that of a pointer.
2198 if (T->isMemberPointerType())
2199 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2200
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002201 if (!Target->allowsLargerPreferedTypeAlignment())
2202 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002203
Eli Friedman7ab09572009-05-25 21:27:19 +00002204 // Double and long long should be naturally aligned if possible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002205 if (const auto *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002206 T = CT->getElementType().getTypePtr();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002207 if (const auto *ET = T->getAs<EnumType>())
David Majnemer475b25e2015-01-21 10:54:38 +00002208 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002209 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002210 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2211 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002212 // Don't increase the alignment if an alignment attribute was specified on a
2213 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002214 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002215 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002216
Chris Lattnera3402cd2009-01-27 18:08:34 +00002217 return ABIAlign;
2218}
2219
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002220/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2221/// for __attribute__((aligned)) on this target, to be used if no alignment
2222/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002223unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002224 return getTargetInfo().getDefaultAlignForAttributeAligned();
2225}
2226
Ulrich Weigandfa806422013-05-06 16:23:57 +00002227/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2228/// to a global variable of the specified type.
2229unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
Tom Tanb7c6d952019-05-02 00:38:14 +00002230 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2231 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
Ulrich Weigandfa806422013-05-06 16:23:57 +00002232}
2233
2234/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2235/// should be given to a global variable of the specified type.
2236CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2237 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2238}
2239
David Majnemer08ef2ba2015-06-23 20:34:18 +00002240CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2241 CharUnits Offset = CharUnits::Zero();
2242 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2243 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2244 Offset += Layout->getBaseClassOffset(Base);
2245 Layout = &getASTRecordLayout(Base);
2246 }
2247 return Offset;
2248}
2249
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002250/// DeepCollectObjCIvars -
2251/// This routine first collects all declared, but not synthesized, ivars in
2252/// super class and then collects all ivars, including those synthesized for
2253/// current class. This routine is used for implementation of current class
2254/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002255void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2256 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002257 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002258 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2259 DeepCollectObjCIvars(SuperClass, false, Ivars);
2260 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002261 for (const auto *I : OI->ivars())
2262 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002263 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002264 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Fangrui Song6907ce22018-07-30 19:24:48 +00002265 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002266 Iv= Iv->getNextIvar())
2267 Ivars.push_back(Iv);
2268 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002269}
2270
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002271/// CollectInheritedProtocols - Collect all protocols in current class and
2272/// those inherited by it.
2273void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002274 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002275 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002276 // We can use protocol_iterator here instead of
Fangrui Song6907ce22018-07-30 19:24:48 +00002277 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002278 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002279 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002280 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002281
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002282 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002283 for (const auto *Cat : OI->visible_categories())
2284 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002285
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002286 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2287 while (SD) {
2288 CollectInheritedProtocols(SD, Protocols);
2289 SD = SD->getSuperClass();
2290 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002291 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002292 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002293 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002294 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002295 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002296 // Insert the protocol.
2297 if (!Protocols.insert(
2298 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2299 return;
2300
2301 for (auto *Proto : OP->protocols())
2302 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002303 }
2304}
2305
Erich Keane8a6b7402017-11-30 16:37:02 +00002306static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2307 const RecordDecl *RD) {
2308 assert(RD->isUnion() && "Must be union type");
2309 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2310
2311 for (const auto *Field : RD->fields()) {
2312 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2313 return false;
2314 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2315 if (FieldSize != UnionSize)
2316 return false;
2317 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002318 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002319}
2320
Benjamin Kramer802e6252017-12-24 12:46:22 +00002321static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002322 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2323
2324 if (!RD->field_empty())
2325 return false;
2326
2327 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2328 return ClassDecl->isEmpty();
2329
2330 return true;
2331}
2332
2333static llvm::Optional<int64_t>
2334structHasUniqueObjectRepresentations(const ASTContext &Context,
2335 const RecordDecl *RD) {
2336 assert(!RD->isUnion() && "Must be struct/class type");
2337 const auto &Layout = Context.getASTRecordLayout(RD);
2338
2339 int64_t CurOffsetInBits = 0;
2340 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2341 if (ClassDecl->isDynamicClass())
2342 return llvm::None;
2343
2344 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2345 for (const auto Base : ClassDecl->bases()) {
2346 // Empty types can be inherited from, and non-empty types can potentially
2347 // have tail padding, so just make sure there isn't an error.
2348 if (!isStructEmpty(Base.getType())) {
2349 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2350 Context, Base.getType()->getAs<RecordType>()->getDecl());
2351 if (!Size)
2352 return llvm::None;
2353 Bases.emplace_back(Base.getType(), Size.getValue());
2354 }
2355 }
2356
Fangrui Song1d38c132018-09-30 21:41:11 +00002357 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2358 const std::pair<QualType, int64_t> &R) {
2359 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2360 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2361 });
Erich Keane8a6b7402017-11-30 16:37:02 +00002362
2363 for (const auto Base : Bases) {
2364 int64_t BaseOffset = Context.toBits(
2365 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2366 int64_t BaseSize = Base.second;
2367 if (BaseOffset != CurOffsetInBits)
2368 return llvm::None;
2369 CurOffsetInBits = BaseOffset + BaseSize;
2370 }
2371 }
2372
2373 for (const auto *Field : RD->fields()) {
2374 if (!Field->getType()->isReferenceType() &&
2375 !Context.hasUniqueObjectRepresentations(Field->getType()))
2376 return llvm::None;
2377
2378 int64_t FieldSizeInBits =
2379 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2380 if (Field->isBitField()) {
2381 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2382
2383 if (BitfieldSize > FieldSizeInBits)
2384 return llvm::None;
2385 FieldSizeInBits = BitfieldSize;
2386 }
2387
2388 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2389
2390 if (FieldOffsetInBits != CurOffsetInBits)
2391 return llvm::None;
2392
2393 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2394 }
2395
2396 return CurOffsetInBits;
2397}
2398
2399bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2400 // C++17 [meta.unary.prop]:
2401 // The predicate condition for a template specialization
2402 // has_unique_object_representations<T> shall be
2403 // satisfied if and only if:
2404 // (9.1) - T is trivially copyable, and
2405 // (9.2) - any two objects of type T with the same value have the same
2406 // object representation, where two objects
2407 // of array or non-union class type are considered to have the same value
2408 // if their respective sequences of
2409 // direct subobjects have the same values, and two objects of union type
2410 // are considered to have the same
2411 // value if they have the same active member and the corresponding members
2412 // have the same value.
2413 // The set of scalar types for which this condition holds is
2414 // implementation-defined. [ Note: If a type has padding
2415 // bits, the condition does not hold; otherwise, the condition holds true
2416 // for unsigned integral types. -- end note ]
2417 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2418
2419 // Arrays are unique only if their element type is unique.
2420 if (Ty->isArrayType())
2421 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2422
2423 // (9.1) - T is trivially copyable...
2424 if (!Ty.isTriviallyCopyableType(*this))
2425 return false;
2426
2427 // All integrals and enums are unique.
2428 if (Ty->isIntegralOrEnumerationType())
2429 return true;
2430
2431 // All other pointers are unique.
2432 if (Ty->isPointerType())
2433 return true;
2434
2435 if (Ty->isMemberPointerType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002436 const auto *MPT = Ty->getAs<MemberPointerType>();
Erich Keane8a6b7402017-11-30 16:37:02 +00002437 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2438 }
2439
2440 if (Ty->isRecordType()) {
2441 const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
2442
Erich Keanebd2197c2017-12-12 16:02:06 +00002443 if (Record->isInvalidDecl())
2444 return false;
2445
Erich Keane8a6b7402017-11-30 16:37:02 +00002446 if (Record->isUnion())
2447 return unionHasUniqueObjectRepresentations(*this, Record);
2448
2449 Optional<int64_t> StructSize =
2450 structHasUniqueObjectRepresentations(*this, Record);
2451
2452 return StructSize &&
2453 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2454 }
2455
2456 // FIXME: More cases to handle here (list by rsmith):
2457 // vectors (careful about, eg, vector of 3 foo)
2458 // _Complex int and friends
2459 // _Atomic T
2460 // Obj-C block pointers
2461 // Obj-C object pointers
2462 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2463 // clk_event_t, queue_t, reserve_id_t)
2464 // There're also Obj-C class types and the Obj-C selector type, but I think it
2465 // makes sense for those to return false here.
2466
2467 return false;
2468}
2469
Jay Foad39c79802011-01-12 09:06:06 +00002470unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002471 unsigned count = 0;
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002472 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002473 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002474 count += Ext->ivar_size();
Fangrui Song6907ce22018-07-30 19:24:48 +00002475
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002476 // Count ivar defined in this class's implementation. This
2477 // includes synthesized ivars.
2478 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002479 count += ImplDecl->ivar_size();
2480
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002481 return count;
2482}
2483
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002484bool ASTContext::isSentinelNullExpr(const Expr *E) {
2485 if (!E)
2486 return false;
2487
2488 // nullptr_t is always treated as null.
2489 if (E->getType()->isNullPtrType()) return true;
2490
2491 if (E->getType()->isAnyPointerType() &&
2492 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2493 Expr::NPC_ValueDependentIsNull))
2494 return true;
2495
2496 // Unfortunately, __null has type 'int'.
2497 if (isa<GNUNullExpr>(E)) return true;
2498
2499 return false;
2500}
2501
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002502/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002503/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002504ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2505 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2506 I = ObjCImpls.find(D);
2507 if (I != ObjCImpls.end())
2508 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002509 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002510}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002511
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002512/// Get the implementation of ObjCCategoryDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002513/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002514ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2515 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2516 I = ObjCImpls.find(D);
2517 if (I != ObjCImpls.end())
2518 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002519 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002520}
2521
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002522/// Set the implementation of ObjCInterfaceDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002523void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2524 ObjCImplementationDecl *ImplD) {
2525 assert(IFaceD && ImplD && "Passed null params");
2526 ObjCImpls[IFaceD] = ImplD;
2527}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002528
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002529/// Set the implementation of ObjCCategoryDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002530void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2531 ObjCCategoryImplDecl *ImplD) {
2532 assert(CatD && ImplD && "Passed null params");
2533 ObjCImpls[CatD] = ImplD;
2534}
2535
Chandler Carruth21c90602015-12-30 03:24:14 +00002536const ObjCMethodDecl *
2537ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2538 return ObjCMethodRedecls.lookup(MD);
2539}
2540
2541void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2542 const ObjCMethodDecl *Redecl) {
2543 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2544 ObjCMethodRedecls[MD] = Redecl;
2545}
2546
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002547const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2548 const NamedDecl *ND) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002549 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002550 return ID;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002551 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002552 return CD->getClassInterface();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002553 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002554 return IMD->getClassInterface();
2555
Craig Topper36250ad2014-05-12 05:36:57 +00002556 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002557}
2558
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002559/// Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002560/// none exists.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002561ASTContext::BlockVarCopyInit
2562ASTContext::getBlockVarCopyInit(const VarDecl*VD) const {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002563 assert(VD && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002564 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002565 "getBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002566 auto I = BlockVarCopyInits.find(VD);
2567 if (I != BlockVarCopyInits.end())
2568 return I->second;
2569 return {nullptr, false};
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002570}
2571
JF Bastien0d702a72019-04-30 00:11:53 +00002572/// Set the copy initialization expression of a block var decl.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002573void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2574 bool CanThrow) {
2575 assert(VD && CopyExpr && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002576 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002577 "setBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002578 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002579}
2580
John McCallbcd03502009-12-07 02:54:59 +00002581TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002582 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002583 if (!DataSize)
2584 DataSize = TypeLoc::getFullDataSizeForType(T);
2585 else
2586 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002587 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002588
Eugene Zelenko7855e772018-04-03 00:11:50 +00002589 auto *TInfo =
John McCallbcd03502009-12-07 02:54:59 +00002590 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2591 new (TInfo) TypeSourceInfo(T);
2592 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002593}
2594
John McCallbcd03502009-12-07 02:54:59 +00002595TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002596 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002597 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002598 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002599 return DI;
2600}
2601
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002602const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002603ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002604 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002605}
2606
2607const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002608ASTContext::getASTObjCImplementationLayout(
2609 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002610 return getObjCLayout(D->getClassInterface(), D);
2611}
2612
Chris Lattner983a8bb2007-07-13 22:13:22 +00002613//===----------------------------------------------------------------------===//
2614// Type creation/memoization methods
2615//===----------------------------------------------------------------------===//
2616
Jay Foad39c79802011-01-12 09:06:06 +00002617QualType
John McCall33ddac02011-01-19 10:06:00 +00002618ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2619 unsigned fastQuals = quals.getFastQualifiers();
2620 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002621
2622 // Check if we've already instantiated this type.
2623 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002624 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002625 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002626 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2627 assert(eq->getQualifiers() == quals);
2628 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002629 }
2630
John McCall33ddac02011-01-19 10:06:00 +00002631 // If the base type is not canonical, make the appropriate canonical type.
2632 QualType canon;
2633 if (!baseType->isCanonicalUnqualified()) {
2634 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002635 canonSplit.Quals.addConsistentQualifiers(quals);
2636 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002637
2638 // Re-find the insert position.
2639 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2640 }
2641
Eugene Zelenko7855e772018-04-03 00:11:50 +00002642 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
John McCall33ddac02011-01-19 10:06:00 +00002643 ExtQualNodes.InsertNode(eq, insertPos);
2644 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002645}
2646
Alexander Richardson6d989432017-10-15 18:48:14 +00002647QualType ASTContext::getAddrSpaceQualType(QualType T,
2648 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002649 QualType CanT = getCanonicalType(T);
2650 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002651 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002652
John McCall8ccfcb52009-09-24 19:53:00 +00002653 // If we are composing extended qualifiers together, merge together
2654 // into one ExtQuals node.
2655 QualifierCollector Quals;
2656 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002657
John McCall8ccfcb52009-09-24 19:53:00 +00002658 // If this type already has an address space specified, it cannot get
2659 // another one.
2660 assert(!Quals.hasAddressSpace() &&
2661 "Type cannot be in multiple addr spaces!");
2662 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002663
John McCall8ccfcb52009-09-24 19:53:00 +00002664 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002665}
2666
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002667QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2668 // If we are composing extended qualifiers together, merge together
2669 // into one ExtQuals node.
2670 QualifierCollector Quals;
2671 const Type *TypeNode = Quals.strip(T);
2672
2673 // If the qualifier doesn't have an address space just return it.
2674 if (!Quals.hasAddressSpace())
2675 return T;
2676
2677 Quals.removeAddressSpace();
2678
2679 // Removal of the address space can mean there are no longer any
2680 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2681 // or required.
2682 if (Quals.hasNonFastQualifiers())
2683 return getExtQualType(TypeNode, Quals);
2684 else
2685 return QualType(TypeNode, Quals.getFastQualifiers());
2686}
2687
Chris Lattnerd60183d2009-02-18 22:53:11 +00002688QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002689 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002690 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002691 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002692 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002693
Eugene Zelenko7855e772018-04-03 00:11:50 +00002694 if (const auto *ptr = T->getAs<PointerType>()) {
John McCall53fa7142010-12-24 02:08:15 +00002695 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002696 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002697 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2698 return getPointerType(ResultType);
2699 }
2700 }
Mike Stump11289f42009-09-09 15:08:12 +00002701
John McCall8ccfcb52009-09-24 19:53:00 +00002702 // If we are composing extended qualifiers together, merge together
2703 // into one ExtQuals node.
2704 QualifierCollector Quals;
2705 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002706
John McCall8ccfcb52009-09-24 19:53:00 +00002707 // If this type already has an ObjCGC specified, it cannot get
2708 // another one.
2709 assert(!Quals.hasObjCGCAttr() &&
2710 "Type cannot have multiple ObjCGCs!");
2711 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002712
John McCall8ccfcb52009-09-24 19:53:00 +00002713 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002714}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002715
John McCall4f5019e2010-12-19 02:44:49 +00002716const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2717 FunctionType::ExtInfo Info) {
2718 if (T->getExtInfo() == Info)
2719 return T;
2720
2721 QualType Result;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002722 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002723 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002724 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002725 const auto *FPT = cast<FunctionProtoType>(T);
John McCall4f5019e2010-12-19 02:44:49 +00002726 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2727 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002728 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002729 }
2730
2731 return cast<FunctionType>(Result.getTypePtr());
2732}
2733
Richard Smith2a7d4812013-05-04 07:00:32 +00002734void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2735 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002736 FD = FD->getMostRecentDecl();
2737 while (true) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002738 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smith2a7d4812013-05-04 07:00:32 +00002739 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002740 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002741 if (FunctionDecl *Next = FD->getPreviousDecl())
2742 FD = Next;
2743 else
2744 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002745 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002746 if (ASTMutationListener *L = getASTMutationListener())
2747 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002748}
2749
Richard Smith0b3a4622014-11-13 20:01:57 +00002750/// Get a function type and produce the equivalent function type with the
2751/// specified exception specification. Type sugar that can be present on a
2752/// declaration of a function with an exception specification is permitted
2753/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002754QualType ASTContext::getFunctionTypeWithExceptionSpec(
2755 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002756 // Might have some parens.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002757 if (const auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002758 return getParenType(
2759 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002760
Leonard Chandc5d9752019-05-10 18:05:15 +00002761 // Might be wrapped in a macro qualified type.
2762 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
2763 return getMacroQualifiedType(
2764 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
2765 MQT->getMacroIdentifier());
2766
Richard Smith0b3a4622014-11-13 20:01:57 +00002767 // Might have a calling-convention attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002768 if (const auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002769 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002770 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002771 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2772 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002773
2774 // Anything else must be a function type. Rebuild it with the new exception
2775 // specification.
Stephan Bergmann84dcc8f2019-02-13 09:39:17 +00002776 const auto *Proto = Orig->getAs<FunctionProtoType>();
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002777 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002778 Proto->getReturnType(), Proto->getParamTypes(),
2779 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2780}
2781
Richard Smithdfe85e22016-12-15 02:35:39 +00002782bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2783 QualType U) {
2784 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002785 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002786 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2787 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002788}
2789
Richard Smith0b3a4622014-11-13 20:01:57 +00002790void ASTContext::adjustExceptionSpec(
2791 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2792 bool AsWritten) {
2793 // Update the type.
2794 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002795 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002796 FD->setType(Updated);
2797
2798 if (!AsWritten)
2799 return;
2800
2801 // Update the type in the type source information too.
2802 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2803 // If the type and the type-as-written differ, we may need to update
2804 // the type-as-written too.
2805 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002806 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002807
2808 // FIXME: When we get proper type location information for exceptions,
2809 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2810 // up the TypeSourceInfo;
2811 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2812 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2813 "TypeLoc size mismatch from updating exception specification");
2814 TSInfo->overrideType(Updated);
2815 }
2816}
2817
Chris Lattnerc6395932007-06-22 20:56:16 +00002818/// getComplexType - Return the uniqued reference to the type for a complex
2819/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002820QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002821 // Unique pointers, to guarantee there is only one pointer of a particular
2822 // structure.
2823 llvm::FoldingSetNodeID ID;
2824 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002825
Craig Topper36250ad2014-05-12 05:36:57 +00002826 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002827 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2828 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002829
Chris Lattnerc6395932007-06-22 20:56:16 +00002830 // If the pointee type isn't canonical, this won't be a canonical type either,
2831 // so fill in the canonical type field.
2832 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002833 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002834 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002835
Chris Lattnerc6395932007-06-22 20:56:16 +00002836 // Get the new insert position for the node we care about.
2837 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002838 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002839 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002840 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002841 Types.push_back(New);
2842 ComplexTypes.InsertNode(New, InsertPos);
2843 return QualType(New, 0);
2844}
2845
Chris Lattner970e54e2006-11-12 00:37:36 +00002846/// getPointerType - Return the uniqued reference to the type for a pointer to
2847/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002848QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002849 // Unique pointers, to guarantee there is only one pointer of a particular
2850 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002851 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002852 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002853
Craig Topper36250ad2014-05-12 05:36:57 +00002854 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002855 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002856 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002857
Chris Lattner7ccecb92006-11-12 08:50:50 +00002858 // If the pointee type isn't canonical, this won't be a canonical type either,
2859 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002860 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002861 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002862 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002863
Bob Wilsonc8541f22013-03-15 17:12:43 +00002864 // Get the new insert position for the node we care about.
2865 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002866 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002867 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002868 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002869 Types.push_back(New);
2870 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002871 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002872}
2873
Reid Kleckner0503a872013-12-05 01:23:43 +00002874QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2875 llvm::FoldingSetNodeID ID;
2876 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002877 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002878 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2879 if (AT)
2880 return QualType(AT, 0);
2881
2882 QualType Canonical = getCanonicalType(New);
2883
2884 // Get the new insert position for the node we care about.
2885 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002886 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002887
2888 AT = new (*this, TypeAlignment)
2889 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2890 Types.push_back(AT);
2891 AdjustedTypes.InsertNode(AT, InsertPos);
2892 return QualType(AT, 0);
2893}
2894
Reid Kleckner8a365022013-06-24 17:51:48 +00002895QualType ASTContext::getDecayedType(QualType T) const {
2896 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2897
Reid Kleckner8a365022013-06-24 17:51:48 +00002898 QualType Decayed;
2899
2900 // C99 6.7.5.3p7:
2901 // A declaration of a parameter as "array of type" shall be
2902 // adjusted to "qualified pointer to type", where the type
2903 // qualifiers (if any) are those specified within the [ and ] of
2904 // the array type derivation.
2905 if (T->isArrayType())
2906 Decayed = getArrayDecayedType(T);
2907
2908 // C99 6.7.5.3p8:
2909 // A declaration of a parameter as "function returning type"
2910 // shall be adjusted to "pointer to function returning type", as
2911 // in 6.3.2.1.
2912 if (T->isFunctionType())
2913 Decayed = getPointerType(T);
2914
Reid Kleckner0503a872013-12-05 01:23:43 +00002915 llvm::FoldingSetNodeID ID;
2916 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002917 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002918 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2919 if (AT)
2920 return QualType(AT, 0);
2921
Reid Kleckner8a365022013-06-24 17:51:48 +00002922 QualType Canonical = getCanonicalType(Decayed);
2923
2924 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002925 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002926 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002927
Reid Kleckner0503a872013-12-05 01:23:43 +00002928 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2929 Types.push_back(AT);
2930 AdjustedTypes.InsertNode(AT, InsertPos);
2931 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002932}
2933
Mike Stump11289f42009-09-09 15:08:12 +00002934/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002935/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002936QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002937 assert(T->isFunctionType() && "block of function types only");
2938 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002939 // structure.
2940 llvm::FoldingSetNodeID ID;
2941 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002942
Craig Topper36250ad2014-05-12 05:36:57 +00002943 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002944 if (BlockPointerType *PT =
2945 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2946 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002947
2948 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002949 // type either so fill in the canonical type field.
2950 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002951 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002952 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002953
Steve Naroffec33ed92008-08-27 16:04:49 +00002954 // Get the new insert position for the node we care about.
2955 BlockPointerType *NewIP =
2956 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002957 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002958 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002959 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002960 Types.push_back(New);
2961 BlockPointerTypes.InsertNode(New, InsertPos);
2962 return QualType(New, 0);
2963}
2964
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002965/// getLValueReferenceType - Return the uniqued reference to the type for an
2966/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002967QualType
2968ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002969 assert(getCanonicalType(T) != OverloadTy &&
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002970 "Unresolved overloaded function type");
Fangrui Song6907ce22018-07-30 19:24:48 +00002971
Bill Wendling3708c182007-05-27 10:15:43 +00002972 // Unique pointers, to guarantee there is only one pointer of a particular
2973 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002974 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002975 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002976
Craig Topper36250ad2014-05-12 05:36:57 +00002977 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002978 if (LValueReferenceType *RT =
2979 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002980 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002981
Eugene Zelenko7855e772018-04-03 00:11:50 +00002982 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00002983
Bill Wendling3708c182007-05-27 10:15:43 +00002984 // If the referencee type isn't canonical, this won't be a canonical type
2985 // either, so fill in the canonical type field.
2986 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002987 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2988 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2989 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002990
Bill Wendling3708c182007-05-27 10:15:43 +00002991 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002992 LValueReferenceType *NewIP =
2993 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002994 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002995 }
2996
Eugene Zelenko7855e772018-04-03 00:11:50 +00002997 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2998 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002999 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003000 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00003001
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003002 return QualType(New, 0);
3003}
3004
3005/// getRValueReferenceType - Return the uniqued reference to the type for an
3006/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00003007QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003008 // Unique pointers, to guarantee there is only one pointer of a particular
3009 // structure.
3010 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00003011 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003012
Craig Topper36250ad2014-05-12 05:36:57 +00003013 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003014 if (RValueReferenceType *RT =
3015 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3016 return QualType(RT, 0);
3017
Eugene Zelenko7855e772018-04-03 00:11:50 +00003018 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003019
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003020 // If the referencee type isn't canonical, this won't be a canonical type
3021 // either, so fill in the canonical type field.
3022 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003023 if (InnerRef || !T.isCanonical()) {
3024 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3025 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003026
3027 // Get the new insert position for the node we care about.
3028 RValueReferenceType *NewIP =
3029 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003030 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003031 }
3032
Eugene Zelenko7855e772018-04-03 00:11:50 +00003033 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003034 Types.push_back(New);
3035 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00003036 return QualType(New, 0);
3037}
3038
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003039/// getMemberPointerType - Return the uniqued reference to the type for a
3040/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00003041QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003042 // Unique pointers, to guarantee there is only one pointer of a particular
3043 // structure.
3044 llvm::FoldingSetNodeID ID;
3045 MemberPointerType::Profile(ID, T, Cls);
3046
Craig Topper36250ad2014-05-12 05:36:57 +00003047 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003048 if (MemberPointerType *PT =
3049 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3050 return QualType(PT, 0);
3051
3052 // If the pointee or class type isn't canonical, this won't be a canonical
3053 // type either, so fill in the canonical type field.
3054 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00003055 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003056 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3057
3058 // Get the new insert position for the node we care about.
3059 MemberPointerType *NewIP =
3060 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003061 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003062 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003063 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003064 Types.push_back(New);
3065 MemberPointerTypes.InsertNode(New, InsertPos);
3066 return QualType(New, 0);
3067}
3068
Mike Stump11289f42009-09-09 15:08:12 +00003069/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00003070/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00003071QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00003072 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003073 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003074 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00003075 assert((EltTy->isDependentType() ||
3076 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00003077 "Constant array of VLAs is illegal!");
3078
Chris Lattnere2df3f92009-05-13 04:12:56 +00003079 // Convert the array size into a canonical width matching the pointer size for
3080 // the target.
3081 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00003082 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00003083
Chris Lattner23b7eb62007-06-15 23:05:46 +00003084 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00003085 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00003086
Craig Topper36250ad2014-05-12 05:36:57 +00003087 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003088 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003089 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003090 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003091
John McCall33ddac02011-01-19 10:06:00 +00003092 // If the element type isn't canonical or has qualifiers, this won't
3093 // be a canonical type either, so fill in the canonical type field.
3094 QualType Canon;
3095 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3096 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003097 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003098 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003099 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003100
Chris Lattner36f8e652007-01-27 08:31:04 +00003101 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00003102 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003103 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003104 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00003105 }
Mike Stump11289f42009-09-09 15:08:12 +00003106
Eugene Zelenko7855e772018-04-03 00:11:50 +00003107 auto *New = new (*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003108 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00003109 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00003110 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003111 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00003112}
3113
John McCall06549462011-01-18 08:40:38 +00003114/// getVariableArrayDecayedType - Turns the given type, which may be
3115/// variably-modified, into the corresponding type with all the known
3116/// sizes replaced with [*].
3117QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3118 // Vastly most common case.
3119 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003120
John McCall06549462011-01-18 08:40:38 +00003121 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003122
John McCall06549462011-01-18 08:40:38 +00003123 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003124 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00003125 switch (ty->getTypeClass()) {
3126#define TYPE(Class, Base)
3127#define ABSTRACT_TYPE(Class, Base)
3128#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3129#include "clang/AST/TypeNodes.def"
3130 llvm_unreachable("didn't desugar past all non-canonical types?");
3131
3132 // These types should never be variably-modified.
3133 case Type::Builtin:
3134 case Type::Complex:
3135 case Type::Vector:
Erich Keanef702b022018-07-13 19:46:04 +00003136 case Type::DependentVector:
John McCall06549462011-01-18 08:40:38 +00003137 case Type::ExtVector:
3138 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003139 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00003140 case Type::ObjCObject:
3141 case Type::ObjCInterface:
3142 case Type::ObjCObjectPointer:
3143 case Type::Record:
3144 case Type::Enum:
3145 case Type::UnresolvedUsing:
3146 case Type::TypeOfExpr:
3147 case Type::TypeOf:
3148 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00003149 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00003150 case Type::DependentName:
3151 case Type::InjectedClassName:
3152 case Type::TemplateSpecialization:
3153 case Type::DependentTemplateSpecialization:
3154 case Type::TemplateTypeParm:
3155 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00003156 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003157 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00003158 case Type::PackExpansion:
3159 llvm_unreachable("type should never be variably-modified");
3160
3161 // These types can be variably-modified but should never need to
3162 // further decay.
3163 case Type::FunctionNoProto:
3164 case Type::FunctionProto:
3165 case Type::BlockPointer:
3166 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00003167 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00003168 return type;
3169
3170 // These types can be variably-modified. All these modifications
3171 // preserve structure except as noted by comments.
3172 // TODO: if we ever care about optimizing VLAs, there are no-op
3173 // optimizations available here.
3174 case Type::Pointer:
3175 result = getPointerType(getVariableArrayDecayedType(
3176 cast<PointerType>(ty)->getPointeeType()));
3177 break;
3178
3179 case Type::LValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003180 const auto *lv = cast<LValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003181 result = getLValueReferenceType(
3182 getVariableArrayDecayedType(lv->getPointeeType()),
3183 lv->isSpelledAsLValue());
3184 break;
3185 }
3186
3187 case Type::RValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003188 const auto *lv = cast<RValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003189 result = getRValueReferenceType(
3190 getVariableArrayDecayedType(lv->getPointeeType()));
3191 break;
3192 }
3193
Eli Friedman0dfb8892011-10-06 23:00:33 +00003194 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003195 const auto *at = cast<AtomicType>(ty);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003196 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3197 break;
3198 }
3199
John McCall06549462011-01-18 08:40:38 +00003200 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003201 const auto *cat = cast<ConstantArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003202 result = getConstantArrayType(
3203 getVariableArrayDecayedType(cat->getElementType()),
3204 cat->getSize(),
3205 cat->getSizeModifier(),
3206 cat->getIndexTypeCVRQualifiers());
3207 break;
3208 }
3209
3210 case Type::DependentSizedArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003211 const auto *dat = cast<DependentSizedArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003212 result = getDependentSizedArrayType(
3213 getVariableArrayDecayedType(dat->getElementType()),
3214 dat->getSizeExpr(),
3215 dat->getSizeModifier(),
3216 dat->getIndexTypeCVRQualifiers(),
3217 dat->getBracketsRange());
3218 break;
3219 }
3220
3221 // Turn incomplete types into [*] types.
3222 case Type::IncompleteArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003223 const auto *iat = cast<IncompleteArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003224 result = getVariableArrayType(
3225 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003226 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003227 ArrayType::Normal,
3228 iat->getIndexTypeCVRQualifiers(),
3229 SourceRange());
3230 break;
3231 }
3232
3233 // Turn VLA types into [*] types.
3234 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003235 const auto *vat = cast<VariableArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003236 result = getVariableArrayType(
3237 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003238 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003239 ArrayType::Star,
3240 vat->getIndexTypeCVRQualifiers(),
3241 vat->getBracketsRange());
3242 break;
3243 }
3244 }
3245
3246 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003247 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003248}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003249
Steve Naroffcadebd02007-08-30 18:14:25 +00003250/// getVariableArrayType - Returns a non-unique reference to the type for a
3251/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003252QualType ASTContext::getVariableArrayType(QualType EltTy,
3253 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003254 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003255 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003256 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003257 // Since we don't unique expressions, it isn't possible to unique VLA's
3258 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003259 QualType Canon;
Fangrui Song6907ce22018-07-30 19:24:48 +00003260
John McCall33ddac02011-01-19 10:06:00 +00003261 // Be sure to pull qualifiers off the element type.
3262 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3263 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003264 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003265 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003266 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003267 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003268
Eugene Zelenko7855e772018-04-03 00:11:50 +00003269 auto *New = new (*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003270 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003271
3272 VariableArrayTypes.push_back(New);
3273 Types.push_back(New);
3274 return QualType(New, 0);
3275}
3276
Douglas Gregor4619e432008-12-05 23:32:09 +00003277/// getDependentSizedArrayType - Returns a non-unique reference to
3278/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003279/// type.
John McCall33ddac02011-01-19 10:06:00 +00003280QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3281 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003282 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003283 unsigned elementTypeQuals,
3284 SourceRange brackets) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003285 assert((!numElements || numElements->isTypeDependent() ||
John McCall33ddac02011-01-19 10:06:00 +00003286 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003287 "Size must be type- or value-dependent!");
3288
John McCall33ddac02011-01-19 10:06:00 +00003289 // Dependently-sized array types that do not have a specified number
3290 // of elements will have their sizes deduced from a dependent
3291 // initializer. We do no canonicalization here at all, which is okay
3292 // because they can't be used in most locations.
3293 if (!numElements) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003294 auto *newType
John McCall33ddac02011-01-19 10:06:00 +00003295 = new (*this, TypeAlignment)
3296 DependentSizedArrayType(*this, elementType, QualType(),
3297 numElements, ASM, elementTypeQuals,
3298 brackets);
3299 Types.push_back(newType);
3300 return QualType(newType, 0);
3301 }
3302
3303 // Otherwise, we actually build a new type every time, but we
3304 // also build a canonical type.
3305
3306 SplitQualType canonElementType = getCanonicalType(elementType).split();
3307
Craig Topper36250ad2014-05-12 05:36:57 +00003308 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003309 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003310 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003311 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003312 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003313
John McCall33ddac02011-01-19 10:06:00 +00003314 // Look for an existing type with these properties.
3315 DependentSizedArrayType *canonTy =
3316 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003317
John McCall33ddac02011-01-19 10:06:00 +00003318 // If we don't have one, build one.
3319 if (!canonTy) {
3320 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003321 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003322 QualType(), numElements, ASM, elementTypeQuals,
3323 brackets);
3324 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3325 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003326 }
3327
John McCall33ddac02011-01-19 10:06:00 +00003328 // Apply qualifiers from the element type to the array.
3329 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003330 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003331
David Majnemer16a74702015-07-24 05:54:19 +00003332 // If we didn't need extra canonicalization for the element type or the size
3333 // expression, then just use that as our result.
3334 if (QualType(canonElementType.Ty, 0) == elementType &&
3335 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003336 return canon;
3337
3338 // Otherwise, we need to build a type which follows the spelling
3339 // of the element type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00003340 auto *sugaredType
John McCall33ddac02011-01-19 10:06:00 +00003341 = new (*this, TypeAlignment)
3342 DependentSizedArrayType(*this, elementType, canon, numElements,
3343 ASM, elementTypeQuals, brackets);
3344 Types.push_back(sugaredType);
3345 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003346}
3347
John McCall33ddac02011-01-19 10:06:00 +00003348QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003349 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003350 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003351 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003352 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003353
Craig Topper36250ad2014-05-12 05:36:57 +00003354 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003355 if (IncompleteArrayType *iat =
3356 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3357 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003358
3359 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003360 // either, so fill in the canonical type field. We also have to pull
3361 // qualifiers off the element type.
3362 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003363
John McCall33ddac02011-01-19 10:06:00 +00003364 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3365 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003366 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003367 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003368 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003369
3370 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003371 IncompleteArrayType *existing =
3372 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3373 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003374 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003375
Eugene Zelenko7855e772018-04-03 00:11:50 +00003376 auto *newType = new (*this, TypeAlignment)
John McCall33ddac02011-01-19 10:06:00 +00003377 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003378
John McCall33ddac02011-01-19 10:06:00 +00003379 IncompleteArrayTypes.InsertNode(newType, insertPos);
3380 Types.push_back(newType);
3381 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003382}
3383
Steve Naroff91fcddb2007-07-18 18:00:27 +00003384/// getVectorType - Return the unique reference to a vector type of
3385/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003386QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003387 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003388 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003389
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003390 // Check if we've already instantiated a vector of this type.
3391 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003392 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003393
Craig Topper36250ad2014-05-12 05:36:57 +00003394 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003395 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3396 return QualType(VTP, 0);
3397
3398 // If the element type isn't canonical, this won't be a canonical type either,
3399 // so fill in the canonical type field.
3400 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003401 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003402 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003403
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003404 // Get the new insert position for the node we care about.
3405 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003406 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003407 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003408 auto *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003409 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003410 VectorTypes.InsertNode(New, InsertPos);
3411 Types.push_back(New);
3412 return QualType(New, 0);
3413}
3414
Erich Keanef702b022018-07-13 19:46:04 +00003415QualType
3416ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3417 SourceLocation AttrLoc,
3418 VectorType::VectorKind VecKind) const {
3419 llvm::FoldingSetNodeID ID;
3420 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3421 VecKind);
3422 void *InsertPos = nullptr;
3423 DependentVectorType *Canon =
3424 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3425 DependentVectorType *New;
3426
3427 if (Canon) {
3428 New = new (*this, TypeAlignment) DependentVectorType(
3429 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3430 } else {
3431 QualType CanonVecTy = getCanonicalType(VecType);
3432 if (CanonVecTy == VecType) {
3433 New = new (*this, TypeAlignment) DependentVectorType(
3434 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3435
3436 DependentVectorType *CanonCheck =
3437 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3438 assert(!CanonCheck &&
3439 "Dependent-sized vector_size canonical type broken");
3440 (void)CanonCheck;
3441 DependentVectorTypes.InsertNode(New, InsertPos);
3442 } else {
3443 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3444 SourceLocation());
3445 New = new (*this, TypeAlignment) DependentVectorType(
3446 *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
3447 }
3448 }
3449
3450 Types.push_back(New);
3451 return QualType(New, 0);
3452}
3453
Nate Begemance4d7fc2008-04-18 23:10:10 +00003454/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003455/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003456QualType
3457ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003458 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003459
Steve Naroff91fcddb2007-07-18 18:00:27 +00003460 // Check if we've already instantiated a vector of this type.
3461 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003462 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003463 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003464 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003465 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3466 return QualType(VTP, 0);
3467
3468 // If the element type isn't canonical, this won't be a canonical type either,
3469 // so fill in the canonical type field.
3470 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003471 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003472 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003473
Steve Naroff91fcddb2007-07-18 18:00:27 +00003474 // Get the new insert position for the node we care about.
3475 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003476 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003477 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003478 auto *New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003479 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003480 VectorTypes.InsertNode(New, InsertPos);
3481 Types.push_back(New);
3482 return QualType(New, 0);
3483}
3484
Jay Foad39c79802011-01-12 09:06:06 +00003485QualType
3486ASTContext::getDependentSizedExtVectorType(QualType vecType,
3487 Expr *SizeExpr,
3488 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003489 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003490 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003491 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003492
Craig Topper36250ad2014-05-12 05:36:57 +00003493 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003494 DependentSizedExtVectorType *Canon
3495 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3496 DependentSizedExtVectorType *New;
3497 if (Canon) {
3498 // We already have a canonical version of this array type; use it as
3499 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003500 New = new (*this, TypeAlignment)
3501 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3502 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003503 } else {
3504 QualType CanonVecTy = getCanonicalType(vecType);
3505 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003506 New = new (*this, TypeAlignment)
3507 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3508 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003509
3510 DependentSizedExtVectorType *CanonCheck
3511 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3512 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3513 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003514 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3515 } else {
3516 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3517 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003518 New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003519 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003520 }
3521 }
Mike Stump11289f42009-09-09 15:08:12 +00003522
Douglas Gregor758a8692009-06-17 21:51:59 +00003523 Types.push_back(New);
3524 return QualType(New, 0);
3525}
3526
Fangrui Song6907ce22018-07-30 19:24:48 +00003527QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3528 Expr *AddrSpaceExpr,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003529 SourceLocation AttrLoc) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003530 assert(AddrSpaceExpr->isInstantiationDependent());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003531
3532 QualType canonPointeeType = getCanonicalType(PointeeType);
3533
3534 void *insertPos = nullptr;
3535 llvm::FoldingSetNodeID ID;
3536 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3537 AddrSpaceExpr);
3538
3539 DependentAddressSpaceType *canonTy =
3540 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3541
3542 if (!canonTy) {
3543 canonTy = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003544 DependentAddressSpaceType(*this, canonPointeeType,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003545 QualType(), AddrSpaceExpr, AttrLoc);
3546 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3547 Types.push_back(canonTy);
3548 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003549
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003550 if (canonPointeeType == PointeeType &&
3551 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
Fangrui Song6907ce22018-07-30 19:24:48 +00003552 return QualType(canonTy, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003553
Eugene Zelenko7855e772018-04-03 00:11:50 +00003554 auto *sugaredType
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003555 = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003556 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003557 AddrSpaceExpr, AttrLoc);
3558 Types.push_back(sugaredType);
Fangrui Song6907ce22018-07-30 19:24:48 +00003559 return QualType(sugaredType, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003560}
3561
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003562/// Determine whether \p T is canonical as the result type of a function.
John McCall18afab72016-03-01 00:49:02 +00003563static bool isCanonicalResultType(QualType T) {
3564 return T.isCanonical() &&
3565 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3566 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3567}
3568
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003569/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003570QualType
3571ASTContext::getFunctionNoProtoType(QualType ResultTy,
3572 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003573 // Unique functions, to guarantee there is only one function of a particular
3574 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003575 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003576 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003577
Craig Topper36250ad2014-05-12 05:36:57 +00003578 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003579 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003580 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003581 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003582
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003583 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003584 if (!isCanonicalResultType(ResultTy)) {
3585 Canonical =
3586 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003587
Chris Lattner47955de2007-01-27 08:37:20 +00003588 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003589 FunctionNoProtoType *NewIP =
3590 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003591 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003592 }
Mike Stump11289f42009-09-09 15:08:12 +00003593
Eugene Zelenko7855e772018-04-03 00:11:50 +00003594 auto *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003595 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003596 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003597 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003598 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003599}
3600
Douglas Gregora602a152015-10-01 20:20:47 +00003601CanQualType
3602ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3603 CanQualType CanResultType = getCanonicalType(ResultType);
3604
3605 // Canonical result types do not have ARC lifetime qualifiers.
3606 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3607 Qualifiers Qs = CanResultType.getQualifiers();
3608 Qs.removeObjCLifetime();
3609 return CanQualType::CreateUnsafe(
3610 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3611 }
3612
3613 return CanResultType;
3614}
3615
Richard Smith3c4f8d22016-10-16 17:54:23 +00003616static bool isCanonicalExceptionSpecification(
3617 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3618 if (ESI.Type == EST_None)
3619 return true;
3620 if (!NoexceptInType)
3621 return false;
3622
3623 // C++17 onwards: exception specification is part of the type, as a simple
3624 // boolean "can this function type throw".
3625 if (ESI.Type == EST_BasicNoexcept)
3626 return true;
3627
Richard Smitheaf11ad2018-05-03 03:58:32 +00003628 // A noexcept(expr) specification is (possibly) canonical if expr is
3629 // value-dependent.
3630 if (ESI.Type == EST_DependentNoexcept)
3631 return true;
3632
Richard Smith3c4f8d22016-10-16 17:54:23 +00003633 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003634 // expansions (so we can't tell whether it's non-throwing) and all its
3635 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003636 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003637 bool AnyPackExpansions = false;
3638 for (QualType ET : ESI.Exceptions) {
3639 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003640 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003641 if (ET->getAs<PackExpansionType>())
3642 AnyPackExpansions = true;
3643 }
3644 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003645 }
3646
Richard Smith3c4f8d22016-10-16 17:54:23 +00003647 return false;
3648}
3649
Richard Smith304b1242016-10-18 20:13:25 +00003650QualType ASTContext::getFunctionTypeInternal(
3651 QualType ResultTy, ArrayRef<QualType> ArgArray,
3652 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003653 size_t NumArgs = ArgArray.size();
3654
Richard Smith2a2cda52016-10-18 19:29:18 +00003655 // Unique functions, to guarantee there is only one function of a particular
3656 // structure.
3657 llvm::FoldingSetNodeID ID;
3658 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3659 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003660
Richard Smith2a2cda52016-10-18 19:29:18 +00003661 QualType Canonical;
3662 bool Unique = false;
3663
3664 void *InsertPos = nullptr;
3665 if (FunctionProtoType *FPT =
3666 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3667 QualType Existing = QualType(FPT, 0);
3668
3669 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3670 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003671 // noexcept expression, or we're just looking for a canonical type.
3672 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003673 // sugar node to hold the concrete expression.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003674 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003675 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3676 return Existing;
3677
3678 // We need a new type sugar node for this one, to hold the new noexcept
3679 // expression. We do no canonicalization here, but that's OK since we don't
3680 // expect to see the same noexcept expression much more than once.
3681 Canonical = getCanonicalType(Existing);
3682 Unique = true;
3683 }
3684
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003685 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003686 bool IsCanonicalExceptionSpec =
3687 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3688
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003689 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003690 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003691 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003692 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003693 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003694 isCanonical = false;
3695
Richard Smith304b1242016-10-18 20:13:25 +00003696 if (OnlyWantCanonical)
3697 assert(isCanonical &&
3698 "given non-canonical parameters constructing canonical type");
3699
Richard Smith2a2cda52016-10-18 19:29:18 +00003700 // If this type isn't canonical, get the canonical version of it if we don't
3701 // already have it. The exception spec is only partially part of the
3702 // canonical type, and only in C++17 onwards.
3703 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003704 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003705 CanonicalArgs.reserve(NumArgs);
3706 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003707 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003708
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003709 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003710 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003711 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003712
3713 if (IsCanonicalExceptionSpec) {
3714 // Exception spec is already OK.
3715 } else if (NoexceptInType) {
3716 switch (EPI.ExceptionSpec.Type) {
3717 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3718 // We don't know yet. It shouldn't matter what we pick here; no-one
3719 // should ever look at this.
3720 LLVM_FALLTHROUGH;
Richard Smitheaf11ad2018-05-03 03:58:32 +00003721 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003722 CanonicalEPI.ExceptionSpec.Type = EST_None;
3723 break;
3724
Richard Smith2a2cda52016-10-18 19:29:18 +00003725 // A dynamic exception specification is almost always "not noexcept",
3726 // with the exception that a pack expansion might expand to no types.
3727 case EST_Dynamic: {
3728 bool AnyPacks = false;
3729 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3730 if (ET->getAs<PackExpansionType>())
3731 AnyPacks = true;
3732 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3733 }
3734 if (!AnyPacks)
3735 CanonicalEPI.ExceptionSpec.Type = EST_None;
3736 else {
3737 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3738 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3739 }
3740 break;
3741 }
3742
Richard Smitheaf11ad2018-05-03 03:58:32 +00003743 case EST_DynamicNone: case EST_BasicNoexcept: case EST_NoexceptTrue:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003744 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3745 break;
3746
Richard Smitheaf11ad2018-05-03 03:58:32 +00003747 case EST_DependentNoexcept:
3748 llvm_unreachable("dependent noexcept is already canonical");
Richard Smith3c4f8d22016-10-16 17:54:23 +00003749 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003750 } else {
3751 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3752 }
John McCalldb40c7f2010-12-14 08:05:40 +00003753
Douglas Gregora602a152015-10-01 20:20:47 +00003754 // Adjust the canonical function result type.
3755 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003756 Canonical =
3757 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003758
Chris Lattnerfd4de792007-01-27 01:15:32 +00003759 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003760 FunctionProtoType *NewIP =
3761 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003762 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003763 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003764
Bruno Ricci26a25362018-10-02 11:46:38 +00003765 // Compute the needed size to hold this FunctionProtoType and the
3766 // various trailing objects.
3767 auto ESH = FunctionProtoType::getExceptionSpecSize(
3768 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
3769 size_t Size = FunctionProtoType::totalSizeToAlloc<
3770 QualType, FunctionType::FunctionTypeExtraBitfields,
3771 FunctionType::ExceptionType, Expr *, FunctionDecl *,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003772 FunctionProtoType::ExtParameterInfo, Qualifiers>(
Bruno Ricci26a25362018-10-02 11:46:38 +00003773 NumArgs, FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
3774 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003775 EPI.ExtParameterInfos ? NumArgs : 0,
3776 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
John McCall18afab72016-03-01 00:49:02 +00003777
Bruno Ricci26a25362018-10-02 11:46:38 +00003778 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003779 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003780 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003781 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003782 if (!Unique)
3783 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003784 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003785}
Chris Lattneref51c202006-11-10 07:17:23 +00003786
Joey Goulye3c85de2016-12-01 11:30:49 +00003787QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003788 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003789 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003790
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00003791 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00003792 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003793 return QualType(PT, 0);
3794
3795 // If the pipe element type isn't canonical, this won't be a canonical type
3796 // either, so fill in the canonical type field.
3797 QualType Canonical;
3798 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003799 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003800
3801 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003802 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003803 assert(!NewIP && "Shouldn't be in the map!");
3804 (void)NewIP;
3805 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003806 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003807 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003808 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003809 return QualType(New, 0);
3810}
3811
Anastasia Stulova59055b92018-05-09 13:23:26 +00003812QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
3813 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3814 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3815 : Ty;
3816}
3817
Joey Goulye3c85de2016-12-01 11:30:49 +00003818QualType ASTContext::getReadPipeType(QualType T) const {
3819 return getPipeType(T, true);
3820}
3821
Joey Gouly5788b782016-11-18 14:10:54 +00003822QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003823 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003824}
3825
John McCalle78aac42010-03-10 03:28:59 +00003826#ifndef NDEBUG
3827static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3828 if (!isa<CXXRecordDecl>(D)) return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00003829 const auto *RD = cast<CXXRecordDecl>(D);
John McCalle78aac42010-03-10 03:28:59 +00003830 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3831 return true;
3832 if (RD->getDescribedClassTemplate() &&
3833 !isa<ClassTemplateSpecializationDecl>(RD))
3834 return true;
3835 return false;
3836}
3837#endif
3838
3839/// getInjectedClassNameType - Return the unique reference to the
3840/// injected class name type for the specified templated declaration.
3841QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003842 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003843 assert(NeedsInjectedClassNameType(Decl));
3844 if (Decl->TypeForDecl) {
3845 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003846 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003847 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3848 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3849 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3850 } else {
John McCall424cec92011-01-19 06:33:43 +00003851 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003852 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003853 Decl->TypeForDecl = newType;
3854 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003855 }
3856 return QualType(Decl->TypeForDecl, 0);
3857}
3858
Douglas Gregor83a586e2008-04-13 21:07:44 +00003859/// getTypeDeclType - Return the unique reference to the type for the
3860/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003861QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003862 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003863 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003864
Eugene Zelenko7855e772018-04-03 00:11:50 +00003865 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003866 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003867
John McCall96f0b5f2010-03-10 06:48:02 +00003868 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3869 "Template type parameter types are always available.");
3870
Eugene Zelenko7855e772018-04-03 00:11:50 +00003871 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003872 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003873 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003874 return getRecordType(Record);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003875 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003876 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003877 return getEnumType(Enum);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003878 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003879 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3880 Decl->TypeForDecl = newType;
3881 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003882 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003883 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003884
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003885 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003886}
3887
Chris Lattner32d920b2007-01-26 02:01:53 +00003888/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003889/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003890QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003891ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3892 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003893 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003894
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003895 if (Canonical.isNull())
3896 Canonical = getCanonicalType(Decl->getUnderlyingType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00003897 auto *newType = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003898 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003899 Decl->TypeForDecl = newType;
3900 Types.push_back(newType);
3901 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003902}
3903
Jay Foad39c79802011-01-12 09:06:06 +00003904QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003905 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3906
Douglas Gregorec9fd132012-01-14 16:38:05 +00003907 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003908 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00003909 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003910
Eugene Zelenko7855e772018-04-03 00:11:50 +00003911 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003912 Decl->TypeForDecl = newType;
3913 Types.push_back(newType);
3914 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003915}
3916
Jay Foad39c79802011-01-12 09:06:06 +00003917QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003918 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3919
Douglas Gregorec9fd132012-01-14 16:38:05 +00003920 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003921 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00003922 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003923
Eugene Zelenko7855e772018-04-03 00:11:50 +00003924 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003925 Decl->TypeForDecl = newType;
3926 Types.push_back(newType);
3927 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003928}
3929
Richard Smithe43e2b32018-08-20 21:47:29 +00003930QualType ASTContext::getAttributedType(attr::Kind attrKind,
John McCall81904512011-01-06 01:58:22 +00003931 QualType modifiedType,
3932 QualType equivalentType) {
3933 llvm::FoldingSetNodeID id;
3934 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3935
Craig Topper36250ad2014-05-12 05:36:57 +00003936 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003937 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3938 if (type) return QualType(type, 0);
3939
3940 QualType canon = getCanonicalType(equivalentType);
3941 type = new (*this, TypeAlignment)
Leonard Chanc72aaf62019-05-07 03:20:17 +00003942 AttributedType(canon, attrKind, modifiedType, equivalentType);
John McCall81904512011-01-06 01:58:22 +00003943
3944 Types.push_back(type);
3945 AttributedTypes.InsertNode(type, insertPos);
3946
3947 return QualType(type, 0);
3948}
3949
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003950/// Retrieve a substitution-result type.
John McCallcebee162009-10-18 09:09:24 +00003951QualType
3952ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003953 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003954 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003955 && "replacement types must always be canonical");
3956
3957 llvm::FoldingSetNodeID ID;
3958 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003959 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003960 SubstTemplateTypeParmType *SubstParm
3961 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3962
3963 if (!SubstParm) {
3964 SubstParm = new (*this, TypeAlignment)
3965 SubstTemplateTypeParmType(Parm, Replacement);
3966 Types.push_back(SubstParm);
3967 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3968 }
3969
3970 return QualType(SubstParm, 0);
3971}
3972
Fangrui Song6907ce22018-07-30 19:24:48 +00003973/// Retrieve a
Douglas Gregorada4b792011-01-14 02:55:32 +00003974QualType ASTContext::getSubstTemplateTypeParmPackType(
3975 const TemplateTypeParmType *Parm,
3976 const TemplateArgument &ArgPack) {
3977#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003978 for (const auto &P : ArgPack.pack_elements()) {
3979 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3980 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003981 }
3982#endif
Fangrui Song6907ce22018-07-30 19:24:48 +00003983
Douglas Gregorada4b792011-01-14 02:55:32 +00003984 llvm::FoldingSetNodeID ID;
3985 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003986 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003987 if (SubstTemplateTypeParmPackType *SubstParm
3988 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3989 return QualType(SubstParm, 0);
Fangrui Song6907ce22018-07-30 19:24:48 +00003990
Douglas Gregorada4b792011-01-14 02:55:32 +00003991 QualType Canon;
3992 if (!Parm->isCanonicalUnqualified()) {
3993 Canon = getCanonicalType(QualType(Parm, 0));
3994 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3995 ArgPack);
3996 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3997 }
3998
Eugene Zelenko7855e772018-04-03 00:11:50 +00003999 auto *SubstParm
Douglas Gregorada4b792011-01-14 02:55:32 +00004000 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4001 ArgPack);
4002 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00004003 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00004004 return QualType(SubstParm, 0);
Douglas Gregorada4b792011-01-14 02:55:32 +00004005}
4006
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004007/// Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00004008/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00004009/// name.
Mike Stump11289f42009-09-09 15:08:12 +00004010QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00004011 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00004012 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00004013 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00004014 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00004015 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004016 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00004017 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4018
4019 if (TypeParm)
4020 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004021
Chandler Carruth08836322011-05-01 00:51:33 +00004022 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00004023 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00004024 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004025
Fangrui Song6907ce22018-07-30 19:24:48 +00004026 TemplateTypeParmType *TypeCheck
Douglas Gregorc42075a2010-02-04 18:10:26 +00004027 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4028 assert(!TypeCheck && "Template type parameter canonical type broken");
4029 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00004030 } else
John McCall90d1c2d2009-09-24 23:30:46 +00004031 TypeParm = new (*this, TypeAlignment)
4032 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00004033
4034 Types.push_back(TypeParm);
4035 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4036
4037 return QualType(TypeParm, 0);
4038}
4039
John McCalle78aac42010-03-10 03:28:59 +00004040TypeSourceInfo *
4041ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4042 SourceLocation NameLoc,
4043 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004044 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004045 assert(!Name.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004046 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004047 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00004048
4049 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00004050 TemplateSpecializationTypeLoc TL =
4051 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00004052 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00004053 TL.setTemplateNameLoc(NameLoc);
4054 TL.setLAngleLoc(Args.getLAngleLoc());
4055 TL.setRAngleLoc(Args.getRAngleLoc());
4056 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4057 TL.setArgLocInfo(i, Args[i].getLocInfo());
4058 return DI;
4059}
4060
Mike Stump11289f42009-09-09 15:08:12 +00004061QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00004062ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00004063 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004064 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004065 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004066 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00004067
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004068 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004069 ArgVec.reserve(Args.size());
4070 for (const TemplateArgumentLoc &Arg : Args.arguments())
4071 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00004072
David Majnemer6fbeee32016-07-07 04:43:07 +00004073 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00004074}
4075
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004076#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00004077static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4078 for (const TemplateArgument &Arg : Args)
4079 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004080 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004081
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004082 return true;
4083}
4084#endif
4085
John McCall0ad16662009-10-29 08:12:44 +00004086QualType
4087ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00004088 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004089 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004090 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004091 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00004092 // Look through qualified template names.
4093 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4094 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004095
4096 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00004097 Template.getAsTemplateDecl() &&
4098 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004099 QualType CanonType;
4100 if (!Underlying.isNull())
4101 CanonType = getCanonicalType(Underlying);
4102 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004103 // We can get here with an alias template when the specialization contains
4104 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00004105 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004106 "Caller must compute aliased type");
4107 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004108 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00004109 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00004110
Douglas Gregora8e02e72009-07-28 23:00:59 +00004111 // Allocate the (non-canonical) template specialization type, but don't
4112 // try to unique it: these types typically have location information that
4113 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004114 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00004115 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004116 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00004117 TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004118 auto *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00004119 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004120 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00004121
Douglas Gregor8bf42052009-02-09 18:46:07 +00004122 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00004123 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00004124}
4125
David Majnemer6fbeee32016-07-07 04:43:07 +00004126QualType ASTContext::getCanonicalTemplateSpecializationType(
4127 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004128 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004129 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004130
Douglas Gregore29139c2011-03-03 17:04:51 +00004131 // Look through qualified template names.
4132 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4133 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004134
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004135 // Build the canonical template specialization type.
4136 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004137 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00004138 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004139 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00004140 for (const TemplateArgument &Arg : Args)
4141 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004142
4143 // Determine whether this canonical template specialization type already
4144 // exists.
4145 llvm::FoldingSetNodeID ID;
4146 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004147 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004148
Craig Topper36250ad2014-05-12 05:36:57 +00004149 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004150 TemplateSpecializationType *Spec
4151 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4152
4153 if (!Spec) {
4154 // Allocate a new canonical template specialization type.
4155 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4156 sizeof(TemplateArgument) * NumArgs),
4157 TypeAlignment);
4158 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004159 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004160 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004161 Types.push_back(Spec);
4162 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4163 }
4164
4165 assert(Spec->isDependentType() &&
4166 "Non-dependent template-id type must have a canonical type");
4167 return QualType(Spec, 0);
4168}
4169
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004170QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4171 NestedNameSpecifier *NNS,
4172 QualType NamedType,
4173 TagDecl *OwnedTagDecl) const {
Douglas Gregor52537682009-03-19 00:18:19 +00004174 llvm::FoldingSetNodeID ID;
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004175 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
Douglas Gregor52537682009-03-19 00:18:19 +00004176
Craig Topper36250ad2014-05-12 05:36:57 +00004177 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00004178 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004179 if (T)
4180 return QualType(T, 0);
4181
Douglas Gregorc42075a2010-02-04 18:10:26 +00004182 QualType Canon = NamedType;
4183 if (!Canon.isCanonical()) {
4184 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004185 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4186 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004187 (void)CheckT;
4188 }
4189
Bruno Riccid6bd5982018-08-16 10:48:16 +00004190 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4191 TypeAlignment);
4192 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4193
Douglas Gregor52537682009-03-19 00:18:19 +00004194 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004195 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004196 return QualType(T, 0);
4197}
4198
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004199QualType
Jay Foad39c79802011-01-12 09:06:06 +00004200ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004201 llvm::FoldingSetNodeID ID;
4202 ParenType::Profile(ID, InnerType);
4203
Craig Topper36250ad2014-05-12 05:36:57 +00004204 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004205 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4206 if (T)
4207 return QualType(T, 0);
4208
4209 QualType Canon = InnerType;
4210 if (!Canon.isCanonical()) {
4211 Canon = getCanonicalType(InnerType);
4212 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4213 assert(!CheckT && "Paren canonical type broken");
4214 (void)CheckT;
4215 }
4216
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004217 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004218 Types.push_back(T);
4219 ParenTypes.InsertNode(T, InsertPos);
4220 return QualType(T, 0);
4221}
4222
Leonard Chanc72aaf62019-05-07 03:20:17 +00004223QualType
4224ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
4225 const IdentifierInfo *MacroII) const {
4226 QualType Canon = UnderlyingTy;
4227 if (!Canon.isCanonical())
4228 Canon = getCanonicalType(UnderlyingTy);
4229
4230 auto *newType = new (*this, TypeAlignment)
4231 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4232 Types.push_back(newType);
4233 return QualType(newType, 0);
4234}
4235
Douglas Gregor02085352010-03-31 20:19:30 +00004236QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4237 NestedNameSpecifier *NNS,
4238 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004239 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004240 if (Canon.isNull()) {
4241 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004242 if (CanonNNS != NNS)
4243 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004244 }
4245
4246 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004247 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004248
Craig Topper36250ad2014-05-12 05:36:57 +00004249 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004250 DependentNameType *T
4251 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004252 if (T)
4253 return QualType(T, 0);
4254
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004255 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004256 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004257 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004258 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004259}
4260
Mike Stump11289f42009-09-09 15:08:12 +00004261QualType
John McCallc392f372010-06-11 00:33:02 +00004262ASTContext::getDependentTemplateSpecializationType(
4263 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004264 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004265 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004266 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004267 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004268 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004269 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4270 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004271 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004272}
4273
4274QualType
4275ASTContext::getDependentTemplateSpecializationType(
4276 ElaboratedTypeKeyword Keyword,
4277 NestedNameSpecifier *NNS,
4278 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004279 ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004280 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor6e068012011-02-28 00:04:36 +00004281 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004282
Douglas Gregorc42075a2010-02-04 18:10:26 +00004283 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004284 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004285 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004286
Craig Topper36250ad2014-05-12 05:36:57 +00004287 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004288 DependentTemplateSpecializationType *T
4289 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004290 if (T)
4291 return QualType(T, 0);
4292
John McCallc392f372010-06-11 00:33:02 +00004293 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004294
John McCallc392f372010-06-11 00:33:02 +00004295 ElaboratedTypeKeyword CanonKeyword = Keyword;
4296 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4297
4298 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004299 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004300 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004301 for (unsigned I = 0; I != NumArgs; ++I) {
4302 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4303 if (!CanonArgs[I].structurallyEquals(Args[I]))
4304 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004305 }
4306
John McCallc392f372010-06-11 00:33:02 +00004307 QualType Canon;
4308 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4309 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004310 Name,
4311 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004312
4313 // Find the insert position again.
4314 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4315 }
4316
4317 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4318 sizeof(TemplateArgument) * NumArgs),
4319 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004320 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004321 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004322 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004323 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004324 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004325}
4326
Richard Smith32918772017-02-14 00:25:28 +00004327TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4328 TemplateArgument Arg;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004329 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith32918772017-02-14 00:25:28 +00004330 QualType ArgType = getTypeDeclType(TTP);
4331 if (TTP->isParameterPack())
4332 ArgType = getPackExpansionType(ArgType, None);
4333
4334 Arg = TemplateArgument(ArgType);
4335 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4336 Expr *E = new (*this) DeclRefExpr(
Bruno Ricci5fc4db72018-12-21 14:10:18 +00004337 *this, NTTP, /*enclosing*/ false,
Richard Smith32918772017-02-14 00:25:28 +00004338 NTTP->getType().getNonLValueExprType(*this),
4339 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4340
4341 if (NTTP->isParameterPack())
4342 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4343 None);
4344 Arg = TemplateArgument(E);
4345 } else {
4346 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4347 if (TTP->isParameterPack())
4348 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4349 else
4350 Arg = TemplateArgument(TemplateName(TTP));
4351 }
4352
4353 if (Param->isTemplateParameterPack())
4354 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4355
4356 return Arg;
4357}
4358
Richard Smith43e14d22016-12-23 02:10:11 +00004359void
4360ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4361 SmallVectorImpl<TemplateArgument> &Args) {
4362 Args.reserve(Args.size() + Params->size());
4363
Richard Smith32918772017-02-14 00:25:28 +00004364 for (NamedDecl *Param : *Params)
4365 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004366}
4367
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004368QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004369 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004370 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004371 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004372
4373 assert(Pattern->containsUnexpandedParameterPack() &&
4374 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004375 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004376 PackExpansionType *T
4377 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4378 if (T)
4379 return QualType(T, 0);
4380
4381 QualType Canon;
4382 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004383 Canon = getCanonicalType(Pattern);
4384 // The canonical type might not contain an unexpanded parameter pack, if it
4385 // contains an alias template specialization which ignores one of its
4386 // parameters.
4387 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004388 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004389
Richard Smith68eea502012-07-16 00:20:35 +00004390 // Find the insert position again, in case we inserted an element into
4391 // PackExpansionTypes and invalidated our insert position.
4392 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4393 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004394 }
4395
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004396 T = new (*this, TypeAlignment)
4397 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004398 Types.push_back(T);
4399 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004400 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004401}
4402
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004403/// CmpProtocolNames - Comparison predicate for sorting protocols
4404/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004405static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4406 ObjCProtocolDecl *const *RHS) {
4407 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004408}
4409
Craig Topper1f26d5b2016-01-03 19:43:23 +00004410static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4411 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004412
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004413 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4414 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004415
Craig Topper1f26d5b2016-01-03 19:43:23 +00004416 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004417 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004418 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004419 return false;
4420 return true;
4421}
4422
Craig Topper6a8c1512015-10-22 01:56:18 +00004423static void
4424SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004425 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004426 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004427
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004428 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004429 for (ObjCProtocolDecl *&P : Protocols)
4430 P = P->getCanonicalDecl();
4431
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004432 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004433 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4434 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004435}
4436
John McCall8b07ec22010-05-15 11:32:37 +00004437QualType ASTContext::getObjCObjectType(QualType BaseType,
4438 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004439 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004440 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004441 llvm::makeArrayRef(Protocols, NumProtocols),
4442 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004443}
4444
4445QualType ASTContext::getObjCObjectType(
4446 QualType baseType,
4447 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004448 ArrayRef<ObjCProtocolDecl *> protocols,
4449 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004450 // If the base type is an interface and there aren't any protocols or
4451 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004452 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4453 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004454 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004455
4456 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004457 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004458 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004459 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004460 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4461 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004462
Douglas Gregore9d95f12015-07-07 03:57:35 +00004463 // Determine the type arguments to be used for canonicalization,
4464 // which may be explicitly specified here or written on the base
4465 // type.
4466 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4467 if (effectiveTypeArgs.empty()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004468 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
Douglas Gregore9d95f12015-07-07 03:57:35 +00004469 effectiveTypeArgs = baseObject->getTypeArgs();
4470 }
John McCallfc93cf92009-10-22 22:37:11 +00004471
Douglas Gregore9d95f12015-07-07 03:57:35 +00004472 // Build the canonical type, which has the canonical base type and a
4473 // sorted-and-uniqued list of protocols and the type arguments
4474 // canonicalized.
4475 QualType canonical;
4476 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4477 effectiveTypeArgs.end(),
4478 [&](QualType type) {
4479 return type.isCanonical();
4480 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004481 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004482 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4483 // Determine the canonical type arguments.
4484 ArrayRef<QualType> canonTypeArgs;
4485 SmallVector<QualType, 4> canonTypeArgsVec;
4486 if (!typeArgsAreCanonical) {
4487 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4488 for (auto typeArg : effectiveTypeArgs)
4489 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4490 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004491 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004492 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004493 }
4494
Douglas Gregore9d95f12015-07-07 03:57:35 +00004495 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4496 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4497 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004498 canonProtocolsVec.append(protocols.begin(), protocols.end());
4499 SortAndUniqueProtocols(canonProtocolsVec);
4500 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004501 } else {
4502 canonProtocols = protocols;
4503 }
4504
4505 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004506 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004507
John McCallfc93cf92009-10-22 22:37:11 +00004508 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004509 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4510 }
4511
Douglas Gregore9d95f12015-07-07 03:57:35 +00004512 unsigned size = sizeof(ObjCObjectTypeImpl);
4513 size += typeArgs.size() * sizeof(QualType);
4514 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4515 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004516 auto *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004517 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4518 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004519
4520 Types.push_back(T);
4521 ObjCObjectTypes.InsertNode(T, InsertPos);
4522 return QualType(T, 0);
4523}
4524
Manman Ren3569eb52016-09-13 17:03:12 +00004525/// Apply Objective-C protocol qualifiers to the given type.
4526/// If this is for the canonical type of a type parameter, we can apply
4527/// protocol qualifiers on the ObjCObjectPointerType.
4528QualType
4529ASTContext::applyObjCProtocolQualifiers(QualType type,
4530 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4531 bool allowOnPointerType) const {
4532 hasError = false;
4533
Eugene Zelenko7855e772018-04-03 00:11:50 +00004534 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
Manman Renc5705ba2016-09-13 17:41:05 +00004535 return getObjCTypeParamType(objT->getDecl(), protocols);
4536 }
4537
Manman Ren3569eb52016-09-13 17:03:12 +00004538 // Apply protocol qualifiers to ObjCObjectPointerType.
4539 if (allowOnPointerType) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004540 if (const auto *objPtr =
4541 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
Manman Ren3569eb52016-09-13 17:03:12 +00004542 const ObjCObjectType *objT = objPtr->getObjectType();
4543 // Merge protocol lists and construct ObjCObjectType.
4544 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4545 protocolsVec.append(objT->qual_begin(),
4546 objT->qual_end());
4547 protocolsVec.append(protocols.begin(), protocols.end());
4548 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4549 type = getObjCObjectType(
4550 objT->getBaseType(),
4551 objT->getTypeArgsAsWritten(),
4552 protocols,
4553 objT->isKindOfTypeAsWritten());
4554 return getObjCObjectPointerType(type);
4555 }
4556 }
4557
4558 // Apply protocol qualifiers to ObjCObjectType.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004559 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
Manman Ren3569eb52016-09-13 17:03:12 +00004560 // FIXME: Check for protocols to which the class type is already
4561 // known to conform.
4562
4563 return getObjCObjectType(objT->getBaseType(),
4564 objT->getTypeArgsAsWritten(),
4565 protocols,
4566 objT->isKindOfTypeAsWritten());
4567 }
4568
4569 // If the canonical type is ObjCObjectType, ...
4570 if (type->isObjCObjectType()) {
4571 // Silently overwrite any existing protocol qualifiers.
4572 // TODO: determine whether that's the right thing to do.
4573
4574 // FIXME: Check for protocols to which the class type is already
4575 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004576 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004577 }
4578
4579 // id<protocol-list>
4580 if (type->isObjCIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004581 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004582 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004583 objPtr->isKindOfType());
4584 return getObjCObjectPointerType(type);
4585 }
4586
4587 // Class<protocol-list>
4588 if (type->isObjCClassType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004589 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004590 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004591 objPtr->isKindOfType());
4592 return getObjCObjectPointerType(type);
4593 }
4594
4595 hasError = true;
4596 return type;
4597}
4598
Manman Rene6be26c2016-09-13 17:25:08 +00004599QualType
4600ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4601 ArrayRef<ObjCProtocolDecl *> protocols,
4602 QualType Canonical) const {
4603 // Look in the folding set for an existing type.
4604 llvm::FoldingSetNodeID ID;
4605 ObjCTypeParamType::Profile(ID, Decl, protocols);
4606 void *InsertPos = nullptr;
4607 if (ObjCTypeParamType *TypeParam =
4608 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4609 return QualType(TypeParam, 0);
4610
4611 if (Canonical.isNull()) {
4612 // We canonicalize to the underlying type.
4613 Canonical = getCanonicalType(Decl->getUnderlyingType());
4614 if (!protocols.empty()) {
4615 // Apply the protocol qualifers.
4616 bool hasError;
Richard Trieua986a312018-08-30 01:57:52 +00004617 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
4618 Canonical, protocols, hasError, true /*allowOnPointerType*/));
Manman Rene6be26c2016-09-13 17:25:08 +00004619 assert(!hasError && "Error when apply protocol qualifier to bound type");
4620 }
4621 }
4622
4623 unsigned size = sizeof(ObjCTypeParamType);
4624 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4625 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004626 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
Manman Rene6be26c2016-09-13 17:25:08 +00004627
4628 Types.push_back(newType);
4629 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4630 return QualType(newType, 0);
4631}
4632
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004633/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4634/// protocol list adopt all protocols in QT's qualified-id protocol
4635/// list.
4636bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4637 ObjCInterfaceDecl *IC) {
4638 if (!QT->isObjCQualifiedIdType())
4639 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004640
Eugene Zelenko7855e772018-04-03 00:11:50 +00004641 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004642 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004643 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004644 if (!IC->ClassImplementsProtocol(Proto, false))
4645 return false;
4646 }
4647 return true;
4648 }
4649 return false;
4650}
4651
4652/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4653/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4654/// of protocols.
4655bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4656 ObjCInterfaceDecl *IDecl) {
4657 if (!QT->isObjCQualifiedIdType())
4658 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004659 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004660 if (!OPT)
4661 return false;
4662 if (!IDecl->hasDefinition())
4663 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004664 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4665 CollectInheritedProtocols(IDecl, InheritedProtocols);
4666 if (InheritedProtocols.empty())
4667 return false;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004668 // Check that if every protocol in list of id<plist> conforms to a protocol
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004669 // of IDecl's, then bridge casting is ok.
4670 bool Conforms = false;
4671 for (auto *Proto : OPT->quals()) {
4672 Conforms = false;
4673 for (auto *PI : InheritedProtocols) {
4674 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4675 Conforms = true;
4676 break;
4677 }
4678 }
4679 if (!Conforms)
4680 break;
4681 }
4682 if (Conforms)
4683 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004684
Aaron Ballman83731462014-03-17 16:14:00 +00004685 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004686 // If both the right and left sides have qualifiers.
4687 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004688 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004689 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004690 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004691 break;
4692 }
4693 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004694 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004695 }
4696 return true;
4697}
4698
John McCall8b07ec22010-05-15 11:32:37 +00004699/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4700/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004701QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004702 llvm::FoldingSetNodeID ID;
4703 ObjCObjectPointerType::Profile(ID, ObjectT);
4704
Craig Topper36250ad2014-05-12 05:36:57 +00004705 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004706 if (ObjCObjectPointerType *QT =
4707 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4708 return QualType(QT, 0);
4709
4710 // Find the canonical object type.
4711 QualType Canonical;
4712 if (!ObjectT.isCanonical()) {
4713 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4714
4715 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004716 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4717 }
4718
Douglas Gregorf85bee62010-02-08 22:59:26 +00004719 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004720 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004721 auto *QType =
John McCall8b07ec22010-05-15 11:32:37 +00004722 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004723
Steve Narofffb4330f2009-06-17 22:40:22 +00004724 Types.push_back(QType);
4725 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004726 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004727}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004728
Douglas Gregor1c283312010-08-11 12:19:30 +00004729/// getObjCInterfaceType - Return the unique reference to the type for the
4730/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004731QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4732 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004733 if (Decl->TypeForDecl)
4734 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004735
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004736 if (PrevDecl) {
4737 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4738 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4739 return QualType(PrevDecl->TypeForDecl, 0);
4740 }
4741
Douglas Gregor7671e532011-12-16 16:34:57 +00004742 // Prefer the definition, if there is one.
4743 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4744 Decl = Def;
Fangrui Song6907ce22018-07-30 19:24:48 +00004745
Douglas Gregor1c283312010-08-11 12:19:30 +00004746 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004747 auto *T = new (Mem) ObjCInterfaceType(Decl);
Douglas Gregor1c283312010-08-11 12:19:30 +00004748 Decl->TypeForDecl = T;
4749 Types.push_back(T);
4750 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004751}
4752
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004753/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4754/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004755/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004756/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004757/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004758QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004759 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004760 if (tofExpr->isTypeDependent()) {
4761 llvm::FoldingSetNodeID ID;
4762 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004763
Craig Topper36250ad2014-05-12 05:36:57 +00004764 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004765 DependentTypeOfExprType *Canon
4766 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4767 if (Canon) {
4768 // We already have a "canonical" version of an identical, dependent
4769 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004770 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004771 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004772 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004773 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004774 Canon
4775 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004776 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4777 toe = Canon;
4778 }
4779 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004780 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004781 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004782 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004783 Types.push_back(toe);
4784 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004785}
4786
Steve Naroffa773cd52007-08-01 18:02:17 +00004787/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004788/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004789/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004790/// an issue. This doesn't affect the type checker, since it operates
4791/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004792QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004793 QualType Canonical = getCanonicalType(tofType);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004794 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004795 Types.push_back(tot);
4796 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004797}
4798
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004799/// Unlike many "get<Type>" functions, we don't unique DecltypeType
Richard Smith8eb1d322014-06-05 20:13:13 +00004800/// nodes. This would never be helpful, since each such type has its own
4801/// expression, and would not give a significant memory saving, since there
4802/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004803QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004804 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004805
4806 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004807 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004808 // unique dependent type. Two such decltype-specifiers refer to the same
4809 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004810 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004811 llvm::FoldingSetNodeID ID;
4812 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004813
Craig Topper36250ad2014-05-12 05:36:57 +00004814 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004815 DependentDecltypeType *Canon
4816 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004817 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004818 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004819 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004820 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004821 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004822 dt = new (*this, TypeAlignment)
4823 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004824 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004825 dt = new (*this, TypeAlignment)
4826 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004827 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004828 Types.push_back(dt);
4829 return QualType(dt, 0);
4830}
4831
Alexis Hunte852b102011-05-24 22:41:36 +00004832/// getUnaryTransformationType - We don't unique these, since the memory
4833/// savings are minimal and these are rare.
4834QualType ASTContext::getUnaryTransformType(QualType BaseType,
4835 QualType UnderlyingType,
4836 UnaryTransformType::UTTKind Kind)
4837 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004838 UnaryTransformType *ut = nullptr;
4839
4840 if (BaseType->isDependentType()) {
4841 // Look in the folding set for an existing type.
4842 llvm::FoldingSetNodeID ID;
4843 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4844
4845 void *InsertPos = nullptr;
4846 DependentUnaryTransformType *Canon
4847 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4848
4849 if (!Canon) {
4850 // Build a new, canonical __underlying_type(type) type.
4851 Canon = new (*this, TypeAlignment)
4852 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4853 Kind);
4854 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4855 }
4856 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4857 QualType(), Kind,
4858 QualType(Canon, 0));
4859 } else {
4860 QualType CanonType = getCanonicalType(UnderlyingType);
4861 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4862 UnderlyingType, Kind,
4863 CanonType);
4864 }
4865 Types.push_back(ut);
4866 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004867}
4868
Richard Smith2a7d4812013-05-04 07:00:32 +00004869/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4870/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4871/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004872QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004873 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004874 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004875 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004876
Richard Smith2a7d4812013-05-04 07:00:32 +00004877 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004878 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004879 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004880 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004881 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4882 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004883
Eugene Zelenko7855e772018-04-03 00:11:50 +00004884 auto *AT = new (*this, TypeAlignment)
4885 AutoType(DeducedType, Keyword, IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004886 Types.push_back(AT);
4887 if (InsertPos)
4888 AutoTypes.InsertNode(AT, InsertPos);
4889 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004890}
4891
Richard Smith600b5262017-01-26 20:40:47 +00004892/// Return the uniqued reference to the deduced template specialization type
4893/// which has been deduced to the given type, or to the canonical undeduced
4894/// such type, or the canonical deduced-but-dependent such type.
4895QualType ASTContext::getDeducedTemplateSpecializationType(
4896 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4897 // Look in the folding set for an existing type.
4898 void *InsertPos = nullptr;
4899 llvm::FoldingSetNodeID ID;
4900 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4901 IsDependent);
4902 if (DeducedTemplateSpecializationType *DTST =
4903 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4904 return QualType(DTST, 0);
4905
Eugene Zelenko7855e772018-04-03 00:11:50 +00004906 auto *DTST = new (*this, TypeAlignment)
Richard Smith600b5262017-01-26 20:40:47 +00004907 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4908 Types.push_back(DTST);
4909 if (InsertPos)
4910 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4911 return QualType(DTST, 0);
4912}
4913
Eli Friedman0dfb8892011-10-06 23:00:33 +00004914/// getAtomicType - Return the uniqued reference to the atomic type for
4915/// the given value type.
4916QualType ASTContext::getAtomicType(QualType T) const {
4917 // Unique pointers, to guarantee there is only one pointer of a particular
4918 // structure.
4919 llvm::FoldingSetNodeID ID;
4920 AtomicType::Profile(ID, T);
4921
Craig Topper36250ad2014-05-12 05:36:57 +00004922 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004923 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4924 return QualType(AT, 0);
4925
4926 // If the atomic value type isn't canonical, this won't be a canonical type
4927 // either, so fill in the canonical type field.
4928 QualType Canonical;
4929 if (!T.isCanonical()) {
4930 Canonical = getAtomicType(getCanonicalType(T));
4931
4932 // Get the new insert position for the node we care about.
4933 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004934 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004935 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00004936 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
Eli Friedman0dfb8892011-10-06 23:00:33 +00004937 Types.push_back(New);
4938 AtomicTypes.InsertNode(New, InsertPos);
4939 return QualType(New, 0);
4940}
4941
Richard Smith02e85f32011-04-14 22:09:26 +00004942/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4943QualType ASTContext::getAutoDeductType() const {
4944 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004945 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004946 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004947 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004948 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004949 return AutoDeductTy;
4950}
4951
4952/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4953QualType ASTContext::getAutoRRefDeductType() const {
4954 if (AutoRRefDeductTy.isNull())
4955 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4956 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4957 return AutoRRefDeductTy;
4958}
4959
Chris Lattnerfb072462007-01-23 05:45:31 +00004960/// getTagDeclType - Return the unique reference to the type for the
4961/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004962QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004963 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004964 // FIXME: What is the design on getTagDeclType when it requires casting
4965 // away const? mutable?
4966 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004967}
4968
Mike Stump11289f42009-09-09 15:08:12 +00004969/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4970/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4971/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004972CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004973 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004974}
Chris Lattnerfb072462007-01-23 05:45:31 +00004975
Fangrui Song6907ce22018-07-30 19:24:48 +00004976/// Return the unique signed counterpart of the integer type
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00004977/// corresponding to size_t.
4978CanQualType ASTContext::getSignedSizeType() const {
4979 return getFromTargetType(Target->getSignedSizeType());
4980}
4981
Hans Wennborg27541db2011-10-27 08:29:09 +00004982/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4983CanQualType ASTContext::getIntMaxType() const {
4984 return getFromTargetType(Target->getIntMaxType());
4985}
4986
4987/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4988CanQualType ASTContext::getUIntMaxType() const {
4989 return getFromTargetType(Target->getUIntMaxType());
4990}
4991
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004992/// getSignedWCharType - Return the type of "signed wchar_t".
4993/// Used when in C++, as a GCC extension.
4994QualType ASTContext::getSignedWCharType() const {
4995 // FIXME: derive from "Target" ?
4996 return WCharTy;
4997}
4998
4999/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5000/// Used when in C++, as a GCC extension.
5001QualType ASTContext::getUnsignedWCharType() const {
5002 // FIXME: derive from "Target" ?
5003 return UnsignedIntTy;
5004}
5005
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00005006QualType ASTContext::getIntPtrType() const {
5007 return getFromTargetType(Target->getIntPtrType());
5008}
5009
5010QualType ASTContext::getUIntPtrType() const {
5011 return getCorrespondingUnsignedType(getIntPtrType());
5012}
5013
Hans Wennborg27541db2011-10-27 08:29:09 +00005014/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005015/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5016QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00005017 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005018}
5019
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005020/// Return the unique unsigned counterpart of "ptrdiff_t"
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00005021/// integer type. The standard (C11 7.21.6.1p7) refers to this type
5022/// in the definition of %tu format specifier.
5023QualType ASTContext::getUnsignedPointerDiffType() const {
5024 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5025}
5026
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005027/// Return the unique type for "pid_t" defined in
Eli Friedman4e91899e2012-11-27 02:58:24 +00005028/// <sys/types.h>. We need this to compute the correct type for vfork().
5029QualType ASTContext::getProcessIDType() const {
5030 return getFromTargetType(Target->getProcessIDType());
5031}
5032
Chris Lattnera21ad802008-04-02 05:18:44 +00005033//===----------------------------------------------------------------------===//
5034// Type Operators
5035//===----------------------------------------------------------------------===//
5036
Jay Foad39c79802011-01-12 09:06:06 +00005037CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00005038 // Push qualifiers into arrays, and then discard any remaining
5039 // qualifiers.
5040 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00005041 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00005042 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00005043 QualType Result;
5044 if (isa<ArrayType>(Ty)) {
5045 Result = getArrayDecayedType(QualType(Ty,0));
5046 } else if (isa<FunctionType>(Ty)) {
5047 Result = getPointerType(QualType(Ty, 0));
5048 } else {
5049 Result = QualType(Ty, 0);
5050 }
5051
5052 return CanQualType::CreateUnsafe(Result);
5053}
5054
John McCall6c9dd522011-01-18 07:41:22 +00005055QualType ASTContext::getUnqualifiedArrayType(QualType type,
5056 Qualifiers &quals) {
5057 SplitQualType splitType = type.getSplitUnqualifiedType();
5058
5059 // FIXME: getSplitUnqualifiedType() actually walks all the way to
5060 // the unqualified desugared type and then drops it on the floor.
5061 // We then have to strip that sugar back off with
5062 // getUnqualifiedDesugaredType(), which is silly.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005063 const auto *AT =
5064 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00005065
5066 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005067 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00005068 quals = splitType.Quals;
5069 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005070 }
5071
John McCall6c9dd522011-01-18 07:41:22 +00005072 // Otherwise, recurse on the array's element type.
5073 QualType elementType = AT->getElementType();
5074 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5075
5076 // If that didn't change the element type, AT has no qualifiers, so we
5077 // can just use the results in splitType.
5078 if (elementType == unqualElementType) {
5079 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00005080 quals = splitType.Quals;
5081 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00005082 }
5083
5084 // Otherwise, add in the qualifiers from the outermost type, then
5085 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00005086 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005087
Eugene Zelenko7855e772018-04-03 00:11:50 +00005088 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005089 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005090 CAT->getSizeModifier(), 0);
5091 }
5092
Eugene Zelenko7855e772018-04-03 00:11:50 +00005093 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005094 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005095 }
5096
Eugene Zelenko7855e772018-04-03 00:11:50 +00005097 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005098 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00005099 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005100 VAT->getSizeModifier(),
5101 VAT->getIndexTypeCVRQualifiers(),
5102 VAT->getBracketsRange());
5103 }
5104
Eugene Zelenko7855e772018-04-03 00:11:50 +00005105 const auto *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00005106 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005107 DSAT->getSizeModifier(), 0,
5108 SourceRange());
5109}
5110
Richard Smitha3405ff2018-07-11 00:19:19 +00005111/// Attempt to unwrap two types that may both be array types with the same bound
5112/// (or both be array types of unknown bound) for the purpose of comparing the
5113/// cv-decomposition of two types per C++ [conv.qual].
Richard Smith5407d4f2018-07-18 20:13:36 +00005114bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5115 bool UnwrappedAny = false;
Richard Smitha3405ff2018-07-11 00:19:19 +00005116 while (true) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005117 auto *AT1 = getAsArrayType(T1);
5118 if (!AT1) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005119
Richard Smith5407d4f2018-07-18 20:13:36 +00005120 auto *AT2 = getAsArrayType(T2);
5121 if (!AT2) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005122
5123 // If we don't have two array types with the same constant bound nor two
5124 // incomplete array types, we've unwrapped everything we can.
5125 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5126 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5127 if (!CAT2 || CAT1->getSize() != CAT2->getSize())
Richard Smith5407d4f2018-07-18 20:13:36 +00005128 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005129 } else if (!isa<IncompleteArrayType>(AT1) ||
5130 !isa<IncompleteArrayType>(AT2)) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005131 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005132 }
5133
5134 T1 = AT1->getElementType();
5135 T2 = AT2->getElementType();
Richard Smith5407d4f2018-07-18 20:13:36 +00005136 UnwrappedAny = true;
Richard Smitha3405ff2018-07-11 00:19:19 +00005137 }
5138}
5139
5140/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5141///
5142/// If T1 and T2 are both pointer types of the same kind, or both array types
5143/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5144/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5145///
5146/// This function will typically be called in a loop that successively
5147/// "unwraps" pointer and pointer-to-member types to compare them at each
5148/// level.
5149///
5150/// \return \c true if a pointer type was unwrapped, \c false if we reached a
5151/// pair of types that can't be unwrapped further.
5152bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005153 UnwrapSimilarArrayTypes(T1, T2);
Richard Smitha3405ff2018-07-11 00:19:19 +00005154
Eugene Zelenko7855e772018-04-03 00:11:50 +00005155 const auto *T1PtrType = T1->getAs<PointerType>();
5156 const auto *T2PtrType = T2->getAs<PointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005157 if (T1PtrType && T2PtrType) {
5158 T1 = T1PtrType->getPointeeType();
5159 T2 = T2PtrType->getPointeeType();
5160 return true;
5161 }
Richard Smith5407d4f2018-07-18 20:13:36 +00005162
Eugene Zelenko7855e772018-04-03 00:11:50 +00005163 const auto *T1MPType = T1->getAs<MemberPointerType>();
5164 const auto *T2MPType = T2->getAs<MemberPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00005165 if (T1MPType && T2MPType &&
5166 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005167 QualType(T2MPType->getClass(), 0))) {
5168 T1 = T1MPType->getPointeeType();
5169 T2 = T2MPType->getPointeeType();
5170 return true;
5171 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005172
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005173 if (getLangOpts().ObjC) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005174 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5175 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005176 if (T1OPType && T2OPType) {
5177 T1 = T1OPType->getPointeeType();
5178 T2 = T2OPType->getPointeeType();
5179 return true;
5180 }
5181 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005182
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005183 // FIXME: Block pointers, too?
Fangrui Song6907ce22018-07-30 19:24:48 +00005184
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005185 return false;
5186}
5187
Richard Smitha3405ff2018-07-11 00:19:19 +00005188bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5189 while (true) {
5190 Qualifiers Quals;
5191 T1 = getUnqualifiedArrayType(T1, Quals);
5192 T2 = getUnqualifiedArrayType(T2, Quals);
5193 if (hasSameType(T1, T2))
5194 return true;
5195 if (!UnwrapSimilarTypes(T1, T2))
5196 return false;
5197 }
5198}
5199
5200bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5201 while (true) {
5202 Qualifiers Quals1, Quals2;
5203 T1 = getUnqualifiedArrayType(T1, Quals1);
5204 T2 = getUnqualifiedArrayType(T2, Quals2);
5205
5206 Quals1.removeCVRQualifiers();
5207 Quals2.removeCVRQualifiers();
5208 if (Quals1 != Quals2)
5209 return false;
5210
5211 if (hasSameType(T1, T2))
5212 return true;
5213
5214 if (!UnwrapSimilarTypes(T1, T2))
5215 return false;
5216 }
5217}
5218
Jay Foad39c79802011-01-12 09:06:06 +00005219DeclarationNameInfo
5220ASTContext::getNameForTemplate(TemplateName Name,
5221 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005222 switch (Name.getKind()) {
5223 case TemplateName::QualifiedTemplate:
5224 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005225 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00005226 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5227 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005228
John McCalld9dfe3a2011-06-30 08:33:18 +00005229 case TemplateName::OverloadedTemplate: {
5230 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5231 // DNInfo work in progress: CHECKME: what about DNLoc?
5232 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5233 }
5234
Richard Smithb23c5e82019-05-09 03:31:27 +00005235 case TemplateName::AssumedTemplate: {
5236 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5237 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5238 }
5239
John McCalld9dfe3a2011-06-30 08:33:18 +00005240 case TemplateName::DependentTemplate: {
5241 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005242 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00005243 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005244 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5245 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00005246 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005247 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5248 // DNInfo work in progress: FIXME: source locations?
5249 DeclarationNameLoc DNLoc;
5250 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5251 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5252 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00005253 }
5254 }
5255
John McCalld9dfe3a2011-06-30 08:33:18 +00005256 case TemplateName::SubstTemplateTemplateParm: {
5257 SubstTemplateTemplateParmStorage *subst
5258 = Name.getAsSubstTemplateTemplateParm();
5259 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5260 NameLoc);
5261 }
5262
5263 case TemplateName::SubstTemplateTemplateParmPack: {
5264 SubstTemplateTemplateParmPackStorage *subst
5265 = Name.getAsSubstTemplateTemplateParmPack();
5266 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5267 NameLoc);
5268 }
5269 }
5270
5271 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005272}
5273
Jay Foad39c79802011-01-12 09:06:06 +00005274TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005275 switch (Name.getKind()) {
5276 case TemplateName::QualifiedTemplate:
5277 case TemplateName::Template: {
5278 TemplateDecl *Template = Name.getAsTemplateDecl();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005279 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005280 Template = getCanonicalTemplateTemplateParmDecl(TTP);
Fangrui Song6907ce22018-07-30 19:24:48 +00005281
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005282 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005283 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005284 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005285
John McCalld9dfe3a2011-06-30 08:33:18 +00005286 case TemplateName::OverloadedTemplate:
Richard Smithb23c5e82019-05-09 03:31:27 +00005287 case TemplateName::AssumedTemplate:
5288 llvm_unreachable("cannot canonicalize unresolved template");
Mike Stump11289f42009-09-09 15:08:12 +00005289
John McCalld9dfe3a2011-06-30 08:33:18 +00005290 case TemplateName::DependentTemplate: {
5291 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5292 assert(DTN && "Non-dependent template names must refer to template decls.");
5293 return DTN->CanonicalTemplateName;
5294 }
5295
5296 case TemplateName::SubstTemplateTemplateParm: {
5297 SubstTemplateTemplateParmStorage *subst
5298 = Name.getAsSubstTemplateTemplateParm();
5299 return getCanonicalTemplateName(subst->getReplacement());
5300 }
5301
5302 case TemplateName::SubstTemplateTemplateParmPack: {
5303 SubstTemplateTemplateParmPackStorage *subst
5304 = Name.getAsSubstTemplateTemplateParmPack();
5305 TemplateTemplateParmDecl *canonParameter
5306 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5307 TemplateArgument canonArgPack
5308 = getCanonicalTemplateArgument(subst->getArgumentPack());
5309 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5310 }
5311 }
5312
5313 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005314}
5315
Douglas Gregoradee3e32009-11-11 23:06:43 +00005316bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5317 X = getCanonicalTemplateName(X);
5318 Y = getCanonicalTemplateName(Y);
5319 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5320}
5321
Mike Stump11289f42009-09-09 15:08:12 +00005322TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005323ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005324 switch (Arg.getKind()) {
5325 case TemplateArgument::Null:
5326 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005327
Douglas Gregora8e02e72009-07-28 23:00:59 +00005328 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005329 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005330
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005331 case TemplateArgument::Declaration: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005332 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005333 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005334 }
Mike Stump11289f42009-09-09 15:08:12 +00005335
Eli Friedmanb826a002012-09-26 02:36:12 +00005336 case TemplateArgument::NullPtr:
5337 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5338 /*isNullPtr*/true);
5339
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005340 case TemplateArgument::Template:
5341 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005342
5343 case TemplateArgument::TemplateExpansion:
5344 return TemplateArgument(getCanonicalTemplateName(
5345 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005346 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005347
Douglas Gregora8e02e72009-07-28 23:00:59 +00005348 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005349 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005350
Douglas Gregora8e02e72009-07-28 23:00:59 +00005351 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005352 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005353
Douglas Gregora8e02e72009-07-28 23:00:59 +00005354 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005355 if (Arg.pack_size() == 0)
5356 return Arg;
Fangrui Song6907ce22018-07-30 19:24:48 +00005357
Eugene Zelenko7855e772018-04-03 00:11:50 +00005358 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005359 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005360 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005361 AEnd = Arg.pack_end();
5362 A != AEnd; (void)++A, ++Idx)
5363 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005364
Benjamin Kramercce63472015-08-05 09:40:22 +00005365 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005366 }
5367 }
5368
5369 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005370 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005371}
5372
Douglas Gregor333489b2009-03-27 23:10:48 +00005373NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005374ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005375 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005376 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005377
5378 switch (NNS->getKind()) {
5379 case NestedNameSpecifier::Identifier:
5380 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005381 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005382 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5383 NNS->getAsIdentifier());
5384
5385 case NestedNameSpecifier::Namespace:
5386 // A namespace is canonical; build a nested-name-specifier with
5387 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005388 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005389 NNS->getAsNamespace()->getOriginalNamespace());
5390
5391 case NestedNameSpecifier::NamespaceAlias:
5392 // A namespace is canonical; build a nested-name-specifier with
5393 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005394 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005395 NNS->getAsNamespaceAlias()->getNamespace()
5396 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005397
5398 case NestedNameSpecifier::TypeSpec:
5399 case NestedNameSpecifier::TypeSpecWithTemplate: {
5400 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Fangrui Song6907ce22018-07-30 19:24:48 +00005401
Douglas Gregor3ade5702010-11-04 00:09:33 +00005402 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5403 // break it apart into its prefix and identifier, then reconsititute those
5404 // as the canonical nested-name-specifier. This is required to canonicalize
5405 // a dependent nested-name-specifier involving typedefs of dependent-name
5406 // types, e.g.,
5407 // typedef typename T::type T1;
5408 // typedef typename T1::type T2;
Eugene Zelenko7855e772018-04-03 00:11:50 +00005409 if (const auto *DNT = T->getAs<DependentNameType>())
Fangrui Song6907ce22018-07-30 19:24:48 +00005410 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005411 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005412
Eli Friedman5358a0a2012-03-03 04:09:56 +00005413 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5414 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5415 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005416 return NestedNameSpecifier::Create(*this, nullptr, false,
5417 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005418 }
5419
5420 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005421 case NestedNameSpecifier::Super:
5422 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005423 return NNS;
5424 }
5425
David Blaikie8a40f702012-01-17 06:56:22 +00005426 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005427}
5428
Jay Foad39c79802011-01-12 09:06:06 +00005429const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005430 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005431 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005432 // Handle the common positive case fast.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005433 if (const auto *AT = dyn_cast<ArrayType>(T))
Chris Lattner7adf0762008-08-04 07:31:14 +00005434 return AT;
5435 }
Mike Stump11289f42009-09-09 15:08:12 +00005436
John McCall8ccfcb52009-09-24 19:53:00 +00005437 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005438 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005439 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005440
John McCall8ccfcb52009-09-24 19:53:00 +00005441 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005442 // implements C99 6.7.3p8: "If the specification of an array type includes
5443 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005444
Chris Lattner7adf0762008-08-04 07:31:14 +00005445 // If we get here, we either have type qualifiers on the type, or we have
5446 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005447 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005448
John McCall33ddac02011-01-19 10:06:00 +00005449 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005450 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005451
Chris Lattner7adf0762008-08-04 07:31:14 +00005452 // If we have a simple case, just return now.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005453 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005454 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005455 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005456
Chris Lattner7adf0762008-08-04 07:31:14 +00005457 // Otherwise, we have an array and we have qualifiers on it. Push the
5458 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005459 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005460
Eugene Zelenko7855e772018-04-03 00:11:50 +00005461 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005462 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5463 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005464 CAT->getIndexTypeCVRQualifiers()));
Eugene Zelenko7855e772018-04-03 00:11:50 +00005465 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005466 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5467 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005468 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005469
Eugene Zelenko7855e772018-04-03 00:11:50 +00005470 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
Douglas Gregor4619e432008-12-05 23:32:09 +00005471 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005472 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005473 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005474 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005475 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005476 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005477
Eugene Zelenko7855e772018-04-03 00:11:50 +00005478 const auto *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005479 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005480 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005481 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005482 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005483 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005484}
5485
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005486QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005487 if (T->isArrayType() || T->isFunctionType())
5488 return getDecayedType(T);
5489 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005490}
5491
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005492QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005493 T = getVariableArrayDecayedType(T);
5494 T = getAdjustedParameterType(T);
5495 return T.getUnqualifiedType();
5496}
5497
David Majnemerd09a51c2015-03-03 01:50:05 +00005498QualType ASTContext::getExceptionObjectType(QualType T) const {
5499 // C++ [except.throw]p3:
5500 // A throw-expression initializes a temporary object, called the exception
5501 // object, the type of which is determined by removing any top-level
5502 // cv-qualifiers from the static type of the operand of throw and adjusting
5503 // the type from "array of T" or "function returning T" to "pointer to T"
5504 // or "pointer to function returning T", [...]
5505 T = getVariableArrayDecayedType(T);
5506 if (T->isArrayType() || T->isFunctionType())
5507 T = getDecayedType(T);
5508 return T.getUnqualifiedType();
5509}
5510
Chris Lattnera21ad802008-04-02 05:18:44 +00005511/// getArrayDecayedType - Return the properly qualified result of decaying the
5512/// specified array type to a pointer. This operation is non-trivial when
5513/// handling typedefs etc. The canonical type of "T" must be an array type,
5514/// this returns a pointer to a properly qualified element of the array.
5515///
5516/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005517QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005518 // Get the element type with 'getAsArrayType' so that we don't lose any
5519 // typedefs in the element type of the array. This also handles propagation
5520 // of type qualifiers from the array type into the element type if present
5521 // (C99 6.7.3p8).
5522 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5523 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005524
Chris Lattner7adf0762008-08-04 07:31:14 +00005525 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005526
5527 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005528 QualType Result = getQualifiedType(PtrTy,
5529 PrettyArrayType->getIndexTypeQualifiers());
5530
5531 // int x[_Nullable] -> int * _Nullable
5532 if (auto Nullability = Ty->getNullability(*this)) {
5533 Result = const_cast<ASTContext *>(this)->getAttributedType(
5534 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5535 }
5536 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005537}
5538
John McCall33ddac02011-01-19 10:06:00 +00005539QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5540 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005541}
5542
John McCall33ddac02011-01-19 10:06:00 +00005543QualType ASTContext::getBaseElementType(QualType type) const {
5544 Qualifiers qs;
5545 while (true) {
5546 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005547 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005548 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005549
John McCall33ddac02011-01-19 10:06:00 +00005550 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005551 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005552 }
Mike Stump11289f42009-09-09 15:08:12 +00005553
John McCall33ddac02011-01-19 10:06:00 +00005554 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005555}
5556
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005557/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005558uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005559ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5560 uint64_t ElementCount = 1;
5561 do {
5562 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005563 CA = dyn_cast_or_null<ConstantArrayType>(
5564 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005565 } while (CA);
5566 return ElementCount;
5567}
5568
Steve Naroff0af91202007-04-27 21:51:21 +00005569/// getFloatingRank - Return a relative rank for floating point types.
5570/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005571static FloatingRank getFloatingRank(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005572 if (const auto *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005573 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005574
John McCall9dd450b2009-09-21 23:43:11 +00005575 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5576 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005577 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005578 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005579 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005580 case BuiltinType::Float: return FloatRank;
5581 case BuiltinType::Double: return DoubleRank;
5582 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005583 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005584 }
5585}
5586
Mike Stump11289f42009-09-09 15:08:12 +00005587/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5588/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005589/// 'typeDomain' is a real floating point or complex type.
5590/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005591QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5592 QualType Domain) const {
5593 FloatingRank EltRank = getFloatingRank(Size);
5594 if (Domain->isComplexType()) {
5595 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005596 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005597 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005598 case FloatRank: return FloatComplexTy;
5599 case DoubleRank: return DoubleComplexTy;
5600 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005601 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005602 }
Steve Naroff0af91202007-04-27 21:51:21 +00005603 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005604
5605 assert(Domain->isRealFloatingType() && "Unknown domain!");
5606 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005607 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005608 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005609 case FloatRank: return FloatTy;
5610 case DoubleRank: return DoubleTy;
5611 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005612 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005613 }
David Blaikief47fa302012-01-17 02:30:50 +00005614 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005615}
5616
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005617/// getFloatingTypeOrder - Compare the rank of the two specified floating
5618/// point types, ignoring the domain of the type (i.e. 'double' ==
5619/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005620/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005621int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005622 FloatingRank LHSR = getFloatingRank(LHS);
5623 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005624
Chris Lattnerb90739d2008-04-06 23:38:49 +00005625 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005626 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005627 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005628 return 1;
5629 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005630}
5631
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +00005632int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
5633 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
5634 return 0;
5635 return getFloatingTypeOrder(LHS, RHS);
5636}
5637
Chris Lattner76a00cf2008-04-06 22:59:24 +00005638/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5639/// routine will assert if passed a built-in type that isn't an integer or enum,
5640/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005641unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005642 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005643
Chris Lattner76a00cf2008-04-06 22:59:24 +00005644 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005645 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005646 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005647 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005648 case BuiltinType::Char_S:
5649 case BuiltinType::Char_U:
5650 case BuiltinType::SChar:
5651 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005652 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005653 case BuiltinType::Short:
5654 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005655 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005656 case BuiltinType::Int:
5657 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005658 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005659 case BuiltinType::Long:
5660 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005661 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005662 case BuiltinType::LongLong:
5663 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005664 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005665 case BuiltinType::Int128:
5666 case BuiltinType::UInt128:
5667 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005668 }
5669}
5670
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005671/// Whether this is a promotable bitfield reference according
Eli Friedman629ffb92009-08-20 04:21:42 +00005672/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5673///
5674/// \returns the type this bit-field will promote to, or NULL if no
5675/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005676QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005677 if (E->isTypeDependent() || E->isValueDependent())
Eugene Zelenko7855e772018-04-03 00:11:50 +00005678 return {};
Richard Smith5b571672014-09-24 23:55:00 +00005679
Richard Smithaadb2542018-06-28 21:17:55 +00005680 // C++ [conv.prom]p5:
5681 // If the bit-field has an enumerated type, it is treated as any other
5682 // value of that type for promotion purposes.
5683 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5684 return {};
5685
Richard Smith5b571672014-09-24 23:55:00 +00005686 // FIXME: We should not do this unless E->refersToBitField() is true. This
5687 // matters in C where getSourceBitField() will find bit-fields for various
5688 // cases where the source expression is not a bit-field designator.
5689
John McCalld25db7e2013-05-06 21:39:12 +00005690 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005691 if (!Field)
Eugene Zelenko7855e772018-04-03 00:11:50 +00005692 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005693
5694 QualType FT = Field->getType();
5695
Richard Smithcaf33902011-10-10 18:28:20 +00005696 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005697 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005698 // C++ [conv.prom]p5:
5699 // A prvalue for an integral bit-field can be converted to a prvalue of type
5700 // int if int can represent all the values of the bit-field; otherwise, it
5701 // can be converted to unsigned int if unsigned int can represent all the
5702 // values of the bit-field. If the bit-field is larger yet, no integral
5703 // promotion applies to it.
5704 // C11 6.3.1.1/2:
5705 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5706 // If an int can represent all values of the original type (as restricted by
5707 // the width, for a bit-field), the value is converted to an int; otherwise,
5708 // it is converted to an unsigned int.
5709 //
5710 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5711 // We perform that promotion here to match GCC and C++.
Richard Smithaadb2542018-06-28 21:17:55 +00005712 // FIXME: C does not permit promotion of an enum bit-field whose rank is
5713 // greater than that of 'int'. We perform that promotion to match GCC.
Eli Friedman629ffb92009-08-20 04:21:42 +00005714 if (BitWidth < IntSize)
5715 return IntTy;
5716
5717 if (BitWidth == IntSize)
5718 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5719
Richard Smithaadb2542018-06-28 21:17:55 +00005720 // Bit-fields wider than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005721 // like the base type. GCC has some weird bugs in this area that we
5722 // deliberately do not follow (GCC follows a pre-standard resolution to
5723 // C's DR315 which treats bit-width as being part of the type, and this leaks
5724 // into their semantics in some cases).
Eugene Zelenko7855e772018-04-03 00:11:50 +00005725 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005726}
5727
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005728/// getPromotedIntegerType - Returns the type that Promotable will
5729/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5730/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005731QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005732 assert(!Promotable.isNull());
5733 assert(Promotable->isPromotableIntegerType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005734 if (const auto *ET = Promotable->getAs<EnumType>())
John McCall56774992009-12-09 09:09:27 +00005735 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005736
Eugene Zelenko7855e772018-04-03 00:11:50 +00005737 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005738 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5739 // (3.9.1) can be converted to a prvalue of the first of the following
5740 // types that can represent all the values of its underlying type:
5741 // int, unsigned int, long int, unsigned long int, long long int, or
5742 // unsigned long long int [...]
5743 // FIXME: Is there some better way to compute this?
5744 if (BT->getKind() == BuiltinType::WChar_S ||
5745 BT->getKind() == BuiltinType::WChar_U ||
Richard Smith3a8244d2018-05-01 05:02:45 +00005746 BT->getKind() == BuiltinType::Char8 ||
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005747 BT->getKind() == BuiltinType::Char16 ||
5748 BT->getKind() == BuiltinType::Char32) {
5749 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5750 uint64_t FromSize = getTypeSize(BT);
5751 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5752 LongLongTy, UnsignedLongLongTy };
5753 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5754 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5755 if (FromSize < ToSize ||
5756 (FromSize == ToSize &&
5757 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5758 return PromoteTypes[Idx];
5759 }
5760 llvm_unreachable("char type should fit into long long");
5761 }
5762 }
5763
5764 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005765 if (Promotable->isSignedIntegerType())
5766 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005767 uint64_t PromotableSize = getIntWidth(Promotable);
5768 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005769 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5770 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5771}
5772
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005773/// Recurses in pointer/array types until it finds an objc retainable
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005774/// type and returns its ownership.
5775Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5776 while (!T.isNull()) {
5777 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5778 return T.getObjCLifetime();
5779 if (T->isArrayType())
5780 T = getBaseElementType(T);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005781 else if (const auto *PT = T->getAs<PointerType>())
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005782 T = PT->getPointeeType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005783 else if (const auto *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005784 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005785 else
5786 break;
5787 }
5788
5789 return Qualifiers::OCL_None;
5790}
5791
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005792static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5793 // Incomplete enum types are not treated as integer types.
5794 // FIXME: In C++, enum types are never integer types.
5795 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5796 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005797 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005798}
5799
Mike Stump11289f42009-09-09 15:08:12 +00005800/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005801/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005802/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005803int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005804 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5805 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005806
5807 // Unwrap enums to their underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005808 if (const auto *ET = dyn_cast<EnumType>(LHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005809 LHSC = getIntegerTypeForEnum(ET);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005810 if (const auto *ET = dyn_cast<EnumType>(RHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005811 RHSC = getIntegerTypeForEnum(ET);
5812
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005813 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005814
Chris Lattner76a00cf2008-04-06 22:59:24 +00005815 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5816 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005817
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005818 unsigned LHSRank = getIntegerRank(LHSC);
5819 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005820
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005821 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5822 if (LHSRank == RHSRank) return 0;
5823 return LHSRank > RHSRank ? 1 : -1;
5824 }
Mike Stump11289f42009-09-09 15:08:12 +00005825
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005826 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5827 if (LHSUnsigned) {
5828 // If the unsigned [LHS] type is larger, return it.
5829 if (LHSRank >= RHSRank)
5830 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005831
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005832 // If the signed type can represent all values of the unsigned type, it
5833 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005834 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005835 return -1;
5836 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005837
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005838 // If the unsigned [RHS] type is larger, return it.
5839 if (RHSRank >= LHSRank)
5840 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005841
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005842 // If the signed type can represent all values of the unsigned type, it
5843 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005844 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005845 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005846}
Anders Carlsson98f07902007-08-17 05:31:46 +00005847
Ben Langmuirf5416742016-02-04 00:55:24 +00005848TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005849 if (CFConstantStringTypeDecl)
5850 return CFConstantStringTypeDecl;
Anders Carlsson6d417272009-11-14 21:45:58 +00005851
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005852 assert(!CFConstantStringTagDecl &&
5853 "tag and typedef should be initialized together");
5854 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5855 CFConstantStringTagDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00005856
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005857 struct {
5858 QualType Type;
5859 const char *Name;
5860 } Fields[5];
5861 unsigned Count = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005862
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005863 /// Objective-C ABI
5864 ///
5865 /// typedef struct __NSConstantString_tag {
Saleem Abdulrasool1f6c41f2018-10-27 06:12:52 +00005866 /// const int *isa;
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005867 /// int flags;
5868 /// const char *str;
5869 /// long length;
5870 /// } __NSConstantString;
5871 ///
5872 /// Swift ABI (4.1, 4.2)
5873 ///
5874 /// typedef struct __NSConstantString_tag {
5875 /// uintptr_t _cfisa;
5876 /// uintptr_t _swift_rc;
5877 /// _Atomic(uint64_t) _cfinfoa;
5878 /// const char *_ptr;
5879 /// uint32_t _length;
5880 /// } __NSConstantString;
5881 ///
5882 /// Swift ABI (5.0)
5883 ///
5884 /// typedef struct __NSConstantString_tag {
5885 /// uintptr_t _cfisa;
5886 /// uintptr_t _swift_rc;
5887 /// _Atomic(uint64_t) _cfinfoa;
5888 /// const char *_ptr;
5889 /// uintptr_t _length;
5890 /// } __NSConstantString;
5891
5892 const auto CFRuntime = getLangOpts().CFRuntime;
5893 if (static_cast<unsigned>(CFRuntime) <
5894 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
5895 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
5896 Fields[Count++] = { IntTy, "flags" };
5897 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
5898 Fields[Count++] = { LongTy, "length" };
5899 } else {
5900 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
5901 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
5902 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
5903 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
5904 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
5905 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
5906 Fields[Count++] = { IntTy, "_ptr" };
5907 else
5908 Fields[Count++] = { getUIntPtrType(), "_ptr" };
5909 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005910
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005911 // Create fields
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005912 for (unsigned i = 0; i < Count; ++i) {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005913 FieldDecl *Field =
5914 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005915 SourceLocation(), &Idents.get(Fields[i].Name),
5916 Fields[i].Type, /*TInfo=*/nullptr,
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005917 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
5918 Field->setAccess(AS_public);
5919 CFConstantStringTagDecl->addDecl(Field);
Anders Carlsson98f07902007-08-17 05:31:46 +00005920 }
Mike Stump11289f42009-09-09 15:08:12 +00005921
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005922 CFConstantStringTagDecl->completeDefinition();
5923 // This type is designed to be compatible with NSConstantString, but cannot
5924 // use the same name, since NSConstantString is an interface.
5925 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5926 CFConstantStringTypeDecl =
5927 buildImplicitTypedef(tagType, "__NSConstantString");
5928
Quentin Colombet043406b2016-02-03 22:41:00 +00005929 return CFConstantStringTypeDecl;
5930}
5931
Ben Langmuirf5416742016-02-04 00:55:24 +00005932RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5933 if (!CFConstantStringTagDecl)
5934 getCFConstantStringDecl(); // Build the tag and the typedef.
5935 return CFConstantStringTagDecl;
5936}
5937
Quentin Colombet043406b2016-02-03 22:41:00 +00005938// getCFConstantStringType - Return the type used for constant CFStrings.
5939QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005940 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005941}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005942
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005943QualType ASTContext::getObjCSuperType() const {
5944 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005945 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005946 TUDecl->addDecl(ObjCSuperTypeDecl);
5947 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5948 }
5949 return ObjCSuperType;
5950}
5951
Douglas Gregor512b0772009-04-23 22:29:11 +00005952void ASTContext::setCFConstantStringType(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005953 const auto *TD = T->getAs<TypedefType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00005954 assert(TD && "Invalid CFConstantStringType");
5955 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005956 const auto *TagType =
Ben Langmuirf5416742016-02-04 00:55:24 +00005957 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5958 assert(TagType && "Invalid CFConstantStringType");
5959 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005960}
5961
Jay Foad39c79802011-01-12 09:06:06 +00005962QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005963 if (BlockDescriptorType)
5964 return getTagDeclType(BlockDescriptorType);
5965
Alp Toker2dea15b2013-12-17 01:22:38 +00005966 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005967 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005968 RD = buildImplicitRecord("__block_descriptor");
5969 RD->startDefinition();
5970
Mike Stumpd0153282009-10-20 02:12:22 +00005971 QualType FieldTypes[] = {
5972 UnsignedLongTy,
5973 UnsignedLongTy,
5974 };
5975
Craig Topperd6d31ac2013-07-15 08:24:27 +00005976 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005977 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005978 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005979 };
5980
5981 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005982 FieldDecl *Field = FieldDecl::Create(
5983 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005984 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5985 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005986 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005987 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005988 }
5989
Alp Toker2dea15b2013-12-17 01:22:38 +00005990 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005991
Alp Toker2dea15b2013-12-17 01:22:38 +00005992 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005993
5994 return getTagDeclType(BlockDescriptorType);
5995}
5996
Jay Foad39c79802011-01-12 09:06:06 +00005997QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005998 if (BlockDescriptorExtendedType)
5999 return getTagDeclType(BlockDescriptorExtendedType);
6000
Alp Toker2dea15b2013-12-17 01:22:38 +00006001 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006002 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00006003 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6004 RD->startDefinition();
6005
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006006 QualType FieldTypes[] = {
6007 UnsignedLongTy,
6008 UnsignedLongTy,
6009 getPointerType(VoidPtrTy),
6010 getPointerType(VoidPtrTy)
6011 };
6012
Craig Topperd6d31ac2013-07-15 08:24:27 +00006013 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006014 "reserved",
6015 "Size",
6016 "CopyFuncPtr",
6017 "DestroyFuncPtr"
6018 };
6019
6020 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006021 FieldDecl *Field = FieldDecl::Create(
6022 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00006023 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6024 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00006025 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00006026 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006027 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006028 }
6029
Alp Toker2dea15b2013-12-17 01:22:38 +00006030 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006031
Alp Toker2dea15b2013-12-17 01:22:38 +00006032 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006033 return getTagDeclType(BlockDescriptorExtendedType);
6034}
6035
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006036TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006037 const auto *BT = dyn_cast<BuiltinType>(T);
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006038
6039 if (!BT) {
6040 if (isa<PipeType>(T))
6041 return TargetInfo::OCLTK_Pipe;
6042
6043 return TargetInfo::OCLTK_Default;
6044 }
6045
6046 switch (BT->getKind()) {
6047#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6048 case BuiltinType::Id: \
6049 return TargetInfo::OCLTK_Image;
6050#include "clang/Basic/OpenCLImageTypes.def"
6051
6052 case BuiltinType::OCLClkEvent:
6053 return TargetInfo::OCLTK_ClkEvent;
6054
6055 case BuiltinType::OCLEvent:
6056 return TargetInfo::OCLTK_Event;
6057
6058 case BuiltinType::OCLQueue:
6059 return TargetInfo::OCLTK_Queue;
6060
6061 case BuiltinType::OCLReserveID:
6062 return TargetInfo::OCLTK_ReserveID;
6063
6064 case BuiltinType::OCLSampler:
6065 return TargetInfo::OCLTK_Sampler;
6066
6067 default:
6068 return TargetInfo::OCLTK_Default;
6069 }
6070}
6071
6072LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6073 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6074}
6075
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006076/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6077/// requires copy/dispose. Note that this must match the logic
6078/// in buildByrefHelpers.
6079bool ASTContext::BlockRequiresCopying(QualType Ty,
6080 const VarDecl *D) {
6081 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00006082 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006083 if (!copyExpr && record->hasTrivialDestructor()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006084
Mike Stump94967902009-10-21 18:16:27 +00006085 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00006086 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006087
Akira Hatanaka7275da02018-02-28 07:15:55 +00006088 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6089 // move or destroy.
6090 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6091 return true;
6092
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006093 if (!Ty->isObjCRetainableType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006094
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006095 Qualifiers qs = Ty.getQualifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00006096
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006097 // If we have lifetime, that dominates.
6098 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006099 switch (lifetime) {
6100 case Qualifiers::OCL_None: llvm_unreachable("impossible");
Fangrui Song6907ce22018-07-30 19:24:48 +00006101
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006102 // These are just bits as far as the runtime is concerned.
6103 case Qualifiers::OCL_ExplicitNone:
6104 case Qualifiers::OCL_Autoreleasing:
6105 return false;
Akira Hatanaka7275da02018-02-28 07:15:55 +00006106
6107 // These cases should have been taken care of when checking the type's
6108 // non-triviality.
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006109 case Qualifiers::OCL_Weak:
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006110 case Qualifiers::OCL_Strong:
Akira Hatanaka7275da02018-02-28 07:15:55 +00006111 llvm_unreachable("impossible");
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006112 }
6113 llvm_unreachable("fell out of lifetime switch!");
6114 }
6115 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6116 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00006117}
6118
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006119bool ASTContext::getByrefLifetime(QualType Ty,
6120 Qualifiers::ObjCLifetime &LifeTime,
6121 bool &HasByrefExtendedLayout) const {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00006122 if (!getLangOpts().ObjC ||
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006123 getLangOpts().getGC() != LangOptions::NonGC)
6124 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006125
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006126 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00006127 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006128 HasByrefExtendedLayout = true;
6129 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006130 } else if ((LifeTime = Ty.getObjCLifetime())) {
6131 // Honor the ARC qualifiers.
6132 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6133 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006134 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00006135 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006136 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006137 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006138 return true;
6139}
6140
Douglas Gregorbab8a962011-09-08 01:46:34 +00006141TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6142 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00006143 ObjCInstanceTypeDecl =
6144 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00006145 return ObjCInstanceTypeDecl;
6146}
6147
Anders Carlsson18acd442007-10-29 06:33:42 +00006148// This returns true if a type has been typedefed to BOOL:
6149// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00006150static bool isTypeTypedefedAsBOOL(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006151 if (const auto *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00006152 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6153 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00006154
Anders Carlssond8499822007-10-29 05:01:08 +00006155 return false;
6156}
6157
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006158/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006159/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00006160CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00006161 if (!type->isIncompleteArrayType() && type->isIncompleteType())
6162 return CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +00006163
Ken Dyck40775002010-01-11 17:06:35 +00006164 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00006165
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006166 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00006167 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00006168 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006169 // Treat arrays as pointers, since that's how they're passed in.
6170 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00006171 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00006172 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00006173}
6174
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006175bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00006176 return getTargetInfo().getCXXABI().isMicrosoft() &&
6177 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00006178 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00006179 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006180}
6181
Richard Smithd9b90092016-07-02 01:32:16 +00006182ASTContext::InlineVariableDefinitionKind
6183ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6184 if (!VD->isInline())
6185 return InlineVariableDefinitionKind::None;
6186
6187 // In almost all cases, it's a weak definition.
6188 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00006189 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00006190 return InlineVariableDefinitionKind::Weak;
6191
6192 // If there's a file-context declaration in this translation unit, it's a
6193 // non-discardable definition.
6194 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00006195 if (D->getLexicalDeclContext()->isFileContext() &&
6196 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00006197 return InlineVariableDefinitionKind::Strong;
6198
6199 // If we've not seen one yet, we don't know.
6200 return InlineVariableDefinitionKind::WeakUnknown;
6201}
6202
Eugene Zelenko7855e772018-04-03 00:11:50 +00006203static std::string charUnitsToString(const CharUnits &CU) {
Ken Dyck40775002010-01-11 17:06:35 +00006204 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006205}
6206
John McCall351762c2011-02-07 10:33:21 +00006207/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00006208/// declaration.
John McCall351762c2011-02-07 10:33:21 +00006209std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6210 std::string S;
6211
David Chisnall950a9512009-11-17 19:33:30 +00006212 const BlockDecl *Decl = Expr->getBlockDecl();
6213 QualType BlockTy =
6214 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
6215 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006216 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00006217 getObjCEncodingForMethodParameter(
6218 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
6219 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006220 else
Alp Toker314cc812014-01-25 16:55:45 +00006221 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00006222 // Compute size of all parameters.
6223 // Start with computing size of a pointer in number of bytes.
6224 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006225 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6226 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006227 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00006228 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006229 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00006230 if (sz.isZero())
6231 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006232 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00006233 ParmOffset += sz;
6234 }
6235 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00006236 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00006237 // Block pointer and offset.
6238 S += "@?0";
Fangrui Song6907ce22018-07-30 19:24:48 +00006239
David Chisnall950a9512009-11-17 19:33:30 +00006240 // Argument types.
6241 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006242 for (auto PVDecl : Decl->parameters()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006243 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006244 if (const auto *AT =
6245 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall950a9512009-11-17 19:33:30 +00006246 // Use array's original type only if it has known number of
6247 // elements.
6248 if (!isa<ConstantArrayType>(AT))
6249 PType = PVDecl->getType();
6250 } else if (PType->isFunctionType())
6251 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006252 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006253 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6254 S, true /*Extended*/);
6255 else
6256 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00006257 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006258 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00006259 }
John McCall351762c2011-02-07 10:33:21 +00006260
6261 return S;
David Chisnall950a9512009-11-17 19:33:30 +00006262}
6263
John McCall843dfcc2016-11-29 21:57:00 +00006264std::string
6265ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6266 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006267 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00006268 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00006269 CharUnits ParmOffset;
6270 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00006271 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00006272 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00006273 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006274 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006275 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006276
6277 assert(sz.isPositive() &&
John McCall843dfcc2016-11-29 21:57:00 +00006278 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00006279 ParmOffset += sz;
6280 }
6281 S += charUnitsToString(ParmOffset);
6282 ParmOffset = CharUnits::Zero();
6283
6284 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00006285 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006286 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006287 if (const auto *AT =
6288 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006289 // Use array's original type only if it has known number of
6290 // elements.
6291 if (!isa<ConstantArrayType>(AT))
6292 PType = PVDecl->getType();
6293 } else if (PType->isFunctionType())
6294 PType = PVDecl->getType();
6295 getObjCEncodingForType(PType, S);
6296 S += charUnitsToString(ParmOffset);
6297 ParmOffset += getObjCEncodingTypeSize(PType);
6298 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006299
John McCall843dfcc2016-11-29 21:57:00 +00006300 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006301}
6302
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006303/// getObjCEncodingForMethodParameter - Return the encoded type for a single
Fangrui Song6907ce22018-07-30 19:24:48 +00006304/// method parameter or return type. If Extended, include class names and
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006305/// block object types.
6306void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6307 QualType T, std::string& S,
6308 bool Extended) const {
6309 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6310 getObjCEncodingForTypeQualifier(QT, S);
6311 // Encode parameter type.
Nico Weberdf129332019-05-10 13:56:56 +00006312 getObjCEncodingForTypeImpl(T, S, /*ExpandPointedToStructures=*/true,
6313 /*ExpandStructures=*/true, /*Field=*/nullptr,
6314 /*OutermostType=*/true,
6315 /*EncodingProperty=*/false,
6316 /*StructField=*/false,
6317 /*EncodeBlockParameters=*/Extended,
6318 /*EncodeClassNames=*/Extended);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006319}
6320
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006321/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006322/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00006323std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6324 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006325 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006326 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006327 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006328 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6329 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006330 // Compute size of all parameters.
6331 // Start with computing size of a pointer in number of bytes.
6332 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006333 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006334 // The first two arguments (self and _cmd) are pointers; account for
6335 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006336 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006337 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006338 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006339 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006340 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006341 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006342 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006343
6344 assert(sz.isPositive() &&
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006345 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006346 ParmOffset += sz;
6347 }
Ken Dyck40775002010-01-11 17:06:35 +00006348 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006349 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006350 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006351
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006352 // Argument types.
6353 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006354 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006355 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006356 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006357 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006358 if (const auto *AT =
6359 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
Steve Naroffe4e55d22009-04-14 00:03:58 +00006360 // Use array's original type only if it has known number of
6361 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006362 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006363 PType = PVDecl->getType();
6364 } else if (PType->isFunctionType())
6365 PType = PVDecl->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00006366 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006367 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006368 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006369 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006370 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006371
John McCall843dfcc2016-11-29 21:57:00 +00006372 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006373}
6374
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006375ObjCPropertyImplDecl *
6376ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6377 const ObjCPropertyDecl *PD,
6378 const Decl *Container) const {
6379 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006380 return nullptr;
Eugene Zelenko7855e772018-04-03 00:11:50 +00006381 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006382 for (auto *PID : CID->property_impls())
6383 if (PID->getPropertyDecl() == PD)
6384 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006385 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006386 const auto *OID = cast<ObjCImplementationDecl>(Container);
Craig Topper36250ad2014-05-12 05:36:57 +00006387 for (auto *PID : OID->property_impls())
6388 if (PID->getPropertyDecl() == PD)
6389 return PID;
6390 }
6391 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006392}
6393
Daniel Dunbar4932b362008-08-28 04:38:10 +00006394/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006395/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006396/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6397/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006398/// Property attributes are stored as a comma-delimited C string. The simple
6399/// attributes readonly and bycopy are encoded as single characters. The
6400/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6401/// encoded as single characters, followed by an identifier. Property types
6402/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006403/// these attributes are defined by the following enumeration:
6404/// @code
6405/// enum PropertyAttributes {
6406/// kPropertyReadOnly = 'R', // property is read-only.
6407/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6408/// kPropertyByref = '&', // property is a reference to the value last assigned
6409/// kPropertyDynamic = 'D', // property is dynamic
6410/// kPropertyGetter = 'G', // followed by getter selector name
6411/// kPropertySetter = 'S', // followed by setter selector name
6412/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006413/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006414/// kPropertyWeak = 'W' // 'weak' property
6415/// kPropertyStrong = 'P' // property GC'able
6416/// kPropertyNonAtomic = 'N' // property non-atomic
6417/// };
6418/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006419std::string
6420ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6421 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006422 // Collect information from the property implementation decl(s).
6423 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006424 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006425
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006426 if (ObjCPropertyImplDecl *PropertyImpDecl =
6427 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6428 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6429 Dynamic = true;
6430 else
6431 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006432 }
6433
6434 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006435 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006436
6437 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006438 // GCC has some special rules regarding encoding of properties which
6439 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006440 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006441
6442 if (PD->isReadOnly()) {
6443 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006444 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6445 S += ",C";
6446 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6447 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006448 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6449 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006450 } else {
6451 switch (PD->getSetterKind()) {
6452 case ObjCPropertyDecl::Assign: break;
6453 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006454 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006455 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006456 }
6457 }
6458
6459 // It really isn't clear at all what this means, since properties
6460 // are "dynamic by default".
6461 if (Dynamic)
6462 S += ",D";
6463
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006464 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6465 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006466
Daniel Dunbar4932b362008-08-28 04:38:10 +00006467 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6468 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006469 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006470 }
6471
6472 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6473 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006474 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006475 }
6476
6477 if (SynthesizePID) {
6478 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6479 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006480 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006481 }
6482
6483 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006484 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006485}
6486
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006487/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006488/// Another legacy compatibility encoding: 32-bit longs are encoded as
6489/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006490/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006491void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006492 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006493 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006494 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006495 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006496 else
Jay Foad39c79802011-01-12 09:06:06 +00006497 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006498 PointeeTy = IntTy;
6499 }
6500 }
6501}
6502
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006503void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006504 const FieldDecl *Field,
6505 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006506 // We follow the behavior of gcc, expanding structures which are
6507 // directly pointed to, and expanding embedded structures. Note that
6508 // these rules are sufficient to prevent recursive encoding of the
6509 // same type.
Nico Weberdf129332019-05-10 13:56:56 +00006510 getObjCEncodingForTypeImpl(T, S, /*ExpandPointedToStructures=*/true,
6511 /*ExpandStructures=*/true, Field,
6512 /*OutermostType=*/true, /*EncodingProperty=*/false,
6513 /*StructField=*/false,
6514 /*EncodeBlockParameters=*/false,
6515 /*EncodeClassNames=*/false,
6516 /*EncodePointerToObjCTypedef=*/false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006517}
6518
Joe Groff98ac7d22014-07-07 22:25:15 +00006519void ASTContext::getObjCEncodingForPropertyType(QualType T,
6520 std::string& S) const {
6521 // Encode result type.
6522 // GCC has some special rules regarding encoding of properties which
6523 // closely resembles encoding of ivars.
Nico Weberdf129332019-05-10 13:56:56 +00006524 getObjCEncodingForTypeImpl(
6525 T, S, /*ExpandPointedToStructures=*/true, /*ExpandStructures=*/true,
6526 /*Field=*/nullptr, /*OutermostType=*/true, /*EncodingProperty=*/true);
Joe Groff98ac7d22014-07-07 22:25:15 +00006527}
6528
John McCall393a78d2012-12-20 02:45:14 +00006529static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
6530 BuiltinType::Kind kind) {
6531 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006532 case BuiltinType::Void: return 'v';
6533 case BuiltinType::Bool: return 'B';
Richard Smith3a8244d2018-05-01 05:02:45 +00006534 case BuiltinType::Char8:
David Chisnallb190a2c2010-06-04 01:10:52 +00006535 case BuiltinType::Char_U:
6536 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006537 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006538 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006539 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006540 case BuiltinType::UInt: return 'I';
6541 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006542 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006543 case BuiltinType::UInt128: return 'T';
6544 case BuiltinType::ULongLong: return 'Q';
6545 case BuiltinType::Char_S:
6546 case BuiltinType::SChar: return 'c';
6547 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006548 case BuiltinType::WChar_S:
6549 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006550 case BuiltinType::Int: return 'i';
6551 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006552 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006553 case BuiltinType::LongLong: return 'q';
6554 case BuiltinType::Int128: return 't';
6555 case BuiltinType::Float: return 'f';
6556 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006557 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006558 case BuiltinType::NullPtr: return '*'; // like char*
6559
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006560 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006561 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006562 case BuiltinType::Half:
Leonard Chanf921d852018-06-04 16:07:52 +00006563 case BuiltinType::ShortAccum:
6564 case BuiltinType::Accum:
6565 case BuiltinType::LongAccum:
6566 case BuiltinType::UShortAccum:
6567 case BuiltinType::UAccum:
6568 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00006569 case BuiltinType::ShortFract:
6570 case BuiltinType::Fract:
6571 case BuiltinType::LongFract:
6572 case BuiltinType::UShortFract:
6573 case BuiltinType::UFract:
6574 case BuiltinType::ULongFract:
6575 case BuiltinType::SatShortAccum:
6576 case BuiltinType::SatAccum:
6577 case BuiltinType::SatLongAccum:
6578 case BuiltinType::SatUShortAccum:
6579 case BuiltinType::SatUAccum:
6580 case BuiltinType::SatULongAccum:
6581 case BuiltinType::SatShortFract:
6582 case BuiltinType::SatFract:
6583 case BuiltinType::SatLongFract:
6584 case BuiltinType::SatUShortFract:
6585 case BuiltinType::SatUFract:
6586 case BuiltinType::SatULongFract:
John McCall393a78d2012-12-20 02:45:14 +00006587 // FIXME: potentially need @encodes for these!
6588 return ' ';
6589
6590 case BuiltinType::ObjCId:
6591 case BuiltinType::ObjCClass:
6592 case BuiltinType::ObjCSel:
6593 llvm_unreachable("@encoding ObjC primitive type");
6594
6595 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006596#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6597 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006598#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00006599#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6600 case BuiltinType::Id:
6601#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006602 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006603 case BuiltinType::OCLClkEvent:
6604 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006605 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006606 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006607 case BuiltinType::Dependent:
6608#define BUILTIN_TYPE(KIND, ID)
6609#define PLACEHOLDER_TYPE(KIND, ID) \
6610 case BuiltinType::KIND:
6611#include "clang/AST/BuiltinTypes.def"
6612 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006613 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006614 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006615}
6616
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006617static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6618 EnumDecl *Enum = ET->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00006619
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006620 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6621 if (!Enum->isFixed())
6622 return 'i';
Fangrui Song6907ce22018-07-30 19:24:48 +00006623
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006624 // The encoding of a fixed enum type matches its fixed underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00006625 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006626 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006627}
6628
Jay Foad39c79802011-01-12 09:06:06 +00006629static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006630 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006631 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006632 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006633 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6634 // The GNU runtime requires more information; bitfields are encoded as b,
6635 // then the offset (in bits) of the first element, then the type of the
6636 // bitfield, then the size in bits. For example, in this structure:
6637 //
6638 // struct
6639 // {
6640 // int integer;
6641 // int flags:2;
6642 // };
6643 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6644 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6645 // information is not especially sensible, but we're stuck with it for
6646 // compatibility with GCC, although providing it breaks anything that
6647 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006648 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006649 uint64_t Offset;
6650
6651 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6652 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6653 IVD);
6654 } else {
6655 const RecordDecl *RD = FD->getParent();
6656 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6657 Offset = RL.getFieldOffset(FD->getFieldIndex());
6658 }
6659
6660 S += llvm::utostr(Offset);
6661
Eugene Zelenko7855e772018-04-03 00:11:50 +00006662 if (const auto *ET = T->getAs<EnumType>())
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006663 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006664 else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006665 const auto *BT = T->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006666 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6667 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006668 }
Richard Smithcaf33902011-10-10 18:28:20 +00006669 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006670}
6671
Daniel Dunbar07d07852009-10-18 21:17:35 +00006672// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006673void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6674 bool ExpandPointedToStructures,
6675 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006676 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006677 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006678 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006679 bool StructField,
6680 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006681 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006682 bool EncodePointerToObjCTypedef,
6683 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006684 CanQualType CT = getCanonicalType(T);
6685 switch (CT->getTypeClass()) {
6686 case Type::Builtin:
6687 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006688 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006689 return EncodeBitField(this, S, T, FD);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006690 if (const auto *BT = dyn_cast<BuiltinType>(CT))
John McCall393a78d2012-12-20 02:45:14 +00006691 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6692 else
6693 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006694 return;
Mike Stump11289f42009-09-09 15:08:12 +00006695
John McCall393a78d2012-12-20 02:45:14 +00006696 case Type::Complex: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006697 const auto *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006698 S += 'j';
Nico Weberdf129332019-05-10 13:56:56 +00006699 getObjCEncodingForTypeImpl(CT->getElementType(), S,
6700 /*ExpandPointedToStructures=*/false,
6701 /*ExpandStructures=*/false, /*Field=*/nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006702 return;
6703 }
John McCall393a78d2012-12-20 02:45:14 +00006704
6705 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006706 const auto *AT = T->castAs<AtomicType>();
John McCall393a78d2012-12-20 02:45:14 +00006707 S += 'A';
Nico Weberdf129332019-05-10 13:56:56 +00006708 getObjCEncodingForTypeImpl(AT->getValueType(), S,
6709 /*ExpandPointedToStructures=*/false,
6710 /*ExpandStructures=*/false, /*Field=*/nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006711 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006712 }
John McCall393a78d2012-12-20 02:45:14 +00006713
6714 // encoding for pointer or reference types.
6715 case Type::Pointer:
6716 case Type::LValueReference:
6717 case Type::RValueReference: {
6718 QualType PointeeTy;
6719 if (isa<PointerType>(CT)) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006720 const auto *PT = T->castAs<PointerType>();
John McCall393a78d2012-12-20 02:45:14 +00006721 if (PT->isObjCSelType()) {
6722 S += ':';
6723 return;
6724 }
6725 PointeeTy = PT->getPointeeType();
6726 } else {
6727 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6728 }
6729
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006730 bool isReadOnly = false;
6731 // For historical/compatibility reasons, the read-only qualifier of the
6732 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6733 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006734 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006735 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006736 if (OutermostType && T.isConstQualified()) {
6737 isReadOnly = true;
6738 S += 'r';
6739 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006740 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006741 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006742 while (P->getAs<PointerType>())
6743 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006744 if (P.isConstQualified()) {
6745 isReadOnly = true;
6746 S += 'r';
6747 }
6748 }
6749 if (isReadOnly) {
6750 // Another legacy compatibility encoding. Some ObjC qualifier and type
6751 // combinations need to be rearranged.
6752 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006753 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006754 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006755 }
Mike Stump11289f42009-09-09 15:08:12 +00006756
Anders Carlssond8499822007-10-29 05:01:08 +00006757 if (PointeeTy->isCharType()) {
6758 // char pointer types should be encoded as '*' unless it is a
6759 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006760 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006761 S += '*';
6762 return;
6763 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00006764 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006765 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6766 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6767 S += '#';
6768 return;
6769 }
6770 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6771 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6772 S += '@';
6773 return;
6774 }
6775 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006776 }
Anders Carlssond8499822007-10-29 05:01:08 +00006777 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006778 getLegacyIntegralTypeEncoding(PointeeTy);
6779
Nico Weberdf129332019-05-10 13:56:56 +00006780 getObjCEncodingForTypeImpl(
6781 PointeeTy, S, /*ExpandPointedToStructures=*/false,
6782 /*ExpandStructures=*/ExpandPointedToStructures, /*Field=*/nullptr,
6783 /*OutermostType=*/false, /*EncodingProperty=*/false,
6784 /*StructField=*/false, /*EncodeBlockParameters=*/false,
6785 /*EncodeClassNames=*/false, /*EncodePointerToObjCTypedef=*/false,
6786 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006787 return;
6788 }
John McCall393a78d2012-12-20 02:45:14 +00006789
6790 case Type::ConstantArray:
6791 case Type::IncompleteArray:
6792 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006793 const auto *AT = cast<ArrayType>(CT);
John McCall393a78d2012-12-20 02:45:14 +00006794
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006795 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006796 // Incomplete arrays are encoded as a pointer to the array element.
6797 S += '^';
6798
Mike Stump11289f42009-09-09 15:08:12 +00006799 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Nico Weberdf129332019-05-10 13:56:56 +00006800 /*ExpandPointedToStructures=*/false,
6801 ExpandStructures, FD);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006802 } else {
6803 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006804
Eugene Zelenko7855e772018-04-03 00:11:50 +00006805 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006806 S += llvm::utostr(CAT->getSize().getZExtValue());
6807 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006808 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006809 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6810 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006811 S += '0';
6812 }
Mike Stump11289f42009-09-09 15:08:12 +00006813
Nico Weberdf129332019-05-10 13:56:56 +00006814 getObjCEncodingForTypeImpl(
6815 AT->getElementType(), S,
6816 /*ExpandPointedToStructures=*/false, ExpandStructures, FD,
6817 /*OutermostType=*/false,
6818 /*EncodingProperty=*/false, /*StructField=*/false,
6819 /*EncodeBlockParameters=*/false, /*EncodeClassNames=*/false,
6820 /*EncodePointerToObjCTypedef=*/false, NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006821 S += ']';
6822 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006823 return;
6824 }
Mike Stump11289f42009-09-09 15:08:12 +00006825
John McCall393a78d2012-12-20 02:45:14 +00006826 case Type::FunctionNoProto:
6827 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006828 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006829 return;
Mike Stump11289f42009-09-09 15:08:12 +00006830
John McCall393a78d2012-12-20 02:45:14 +00006831 case Type::Record: {
6832 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006833 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006834 // Anonymous structures print as '?'
6835 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6836 S += II->getName();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006837 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006838 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006839 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00006840 printTemplateArgumentList(OS, TemplateArgs.asArray(),
6841 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006842 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006843 } else {
6844 S += '?';
6845 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006846 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006847 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006848 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006849 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006850 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006851 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006852 if (FD) {
6853 S += '"';
6854 S += Field->getNameAsString();
6855 S += '"';
6856 }
Mike Stump11289f42009-09-09 15:08:12 +00006857
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006858 // Special case bit-fields.
6859 if (Field->isBitField()) {
Nico Weberdf129332019-05-10 13:56:56 +00006860 getObjCEncodingForTypeImpl(Field->getType(), S,
6861 /*ExpandPointedToStructures=*/false,
6862 /*ExpandStructures=*/true, Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006863 } else {
6864 QualType qt = Field->getType();
6865 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00006866 getObjCEncodingForTypeImpl(
6867 qt, S, /*ExpandPointedToStructures=*/false,
6868 /*ExpandStructures=*/true, FD, /*OutermostType=*/false,
6869 /*EncodingProperty=*/false,
6870 /*StructField=*/true, /*EncodeBlockParameters=*/false,
6871 /*EncodeClassNames=*/false,
6872 /*EncodePointerToObjCTypedef=*/false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006873 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006874 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006875 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006876 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006877 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006878 return;
6879 }
Mike Stump11289f42009-09-09 15:08:12 +00006880
John McCall393a78d2012-12-20 02:45:14 +00006881 case Type::BlockPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006882 const auto *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006883 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006884 if (EncodeBlockParameters) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006885 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00006886
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006887 S += '<';
6888 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006889 getObjCEncodingForTypeImpl(
6890 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
Nico Weberdf129332019-05-10 13:56:56 +00006891 FD, /*OutermostType=*/false, EncodingProperty,
6892 /*StructField=*/false, EncodeBlockParameters, EncodeClassNames,
6893 /*EncodePointerToObjCTypedef=*/false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006894 // Block self
6895 S += "@?";
6896 // Block parameters
Eugene Zelenko7855e772018-04-03 00:11:50 +00006897 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006898 for (const auto &I : FPT->param_types())
6899 getObjCEncodingForTypeImpl(
6900 I, S, ExpandPointedToStructures, ExpandStructures, FD,
Nico Weberdf129332019-05-10 13:56:56 +00006901 /*OutermostType=*/false, EncodingProperty,
6902 /*StructField=*/false, EncodeBlockParameters, EncodeClassNames,
6903 /*EncodePointerToObjCTypedef=*/false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006904 }
6905 S += '>';
6906 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006907 return;
6908 }
Mike Stump11289f42009-09-09 15:08:12 +00006909
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006910 case Type::ObjCObject: {
6911 // hack to match legacy encoding of *id and *Class
6912 QualType Ty = getObjCObjectPointerType(CT);
6913 if (Ty->isObjCIdType()) {
6914 S += "{objc_object=}";
6915 return;
6916 }
6917 else if (Ty->isObjCClassType()) {
6918 S += "{objc_class=}";
6919 return;
6920 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006921 // TODO: Double check to make sure this intentionally falls through.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006922 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006923 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006924
John McCall393a78d2012-12-20 02:45:14 +00006925 case Type::ObjCInterface: {
6926 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006927 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006928 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006929 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006930 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006931 if (ExpandStructures) {
6932 S += '=';
6933 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6934 DeepCollectObjCIvars(OI, true, Ivars);
6935 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006936 const FieldDecl *Field = Ivars[i];
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006937 if (Field->isBitField())
Nico Weberdf129332019-05-10 13:56:56 +00006938 getObjCEncodingForTypeImpl(Field->getType(), S,
6939 /*ExpandPointedToStructures=*/false,
6940 /*ExpandStructures=*/true, Field);
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006941 else
Nico Weberdf129332019-05-10 13:56:56 +00006942 getObjCEncodingForTypeImpl(
6943 Field->getType(), S,
6944 /*ExpandPointedToStructures=*/false,
6945 /*ExpandStructures=*/true, FD, /*OutermostType=*/false,
6946 /*EncodingProperty=*/false,
6947 /*StructField=*/false, /*EncodeBlockParameters=*/false,
6948 /*EncodeClassNames=*/false, EncodePointerToObjCTypedef,
6949 NotEncodedT);
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006950 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006951 }
6952 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006953 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006954 }
Mike Stump11289f42009-09-09 15:08:12 +00006955
John McCall393a78d2012-12-20 02:45:14 +00006956 case Type::ObjCObjectPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006957 const auto *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006958 if (OPT->isObjCIdType()) {
6959 S += '@';
6960 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006961 }
Mike Stump11289f42009-09-09 15:08:12 +00006962
Steve Narofff0c86112009-10-28 22:03:49 +00006963 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6964 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
Nico Weberdf129332019-05-10 13:56:56 +00006965 // Since this is a binary compatibility issue, need to consult with
6966 // runtime folks. Fortunately, this is a *very* obscure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006967 S += '#';
6968 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006969 }
Mike Stump11289f42009-09-09 15:08:12 +00006970
Chris Lattnere7cabb92009-07-13 00:10:46 +00006971 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006972 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006973 ExpandPointedToStructures,
6974 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006975 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006976 // Note that we do extended encoding of protocol qualifer list
6977 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006978 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006979 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006980 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006981 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006982 S += '>';
6983 }
6984 S += '"';
6985 }
6986 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006987 }
Mike Stump11289f42009-09-09 15:08:12 +00006988
Chris Lattnere7cabb92009-07-13 00:10:46 +00006989 QualType PointeeTy = OPT->getPointeeType();
6990 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006991 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6992 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006993 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006994 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006995 // {...};
6996 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006997 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006998 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006999 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
7000 SmallVector<const ObjCIvarDecl*, 32> Ivars;
7001 DeepCollectObjCIvars(OI, true, Ivars);
7002 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00007003 if (Ivars[i] == FD) {
Fariborz Jahanian88890e72013-07-12 16:19:11 +00007004 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007005 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00007006 S += '}';
7007 return;
7008 }
7009 }
7010 }
Nico Weberdf129332019-05-10 13:56:56 +00007011 getObjCEncodingForTypeImpl(
7012 PointeeTy, S,
7013 /*ExpandPointedToStructures=*/false,
7014 /*ExpandStructures=*/ExpandPointedToStructures,
7015 /*Field=*/nullptr,
7016 /*OutermostType=*/false, /*EncodingProperty=*/false,
7017 /*StructField=*/false, /*EncodeBlockParameters=*/false,
7018 /*EncodeClassNames=*/false,
7019 /*EncodePointerToObjCTypedef=*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00007020 return;
7021 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00007022
7023 S += '@';
Fangrui Song6907ce22018-07-30 19:24:48 +00007024 if (OPT->getInterfaceDecl() &&
Bob Wilson5f4e3a72011-11-30 01:57:58 +00007025 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00007026 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007027 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00007028 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00007029 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007030 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00007031 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00007032 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00007033 S += '"';
7034 }
7035 return;
7036 }
Mike Stump11289f42009-09-09 15:08:12 +00007037
John McCalla9e6e8d2010-05-17 23:56:34 +00007038 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00007039 // FIXME: we shoul do better than that. 'M' is available.
7040 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007041 // This matches gcc's encoding, even though technically it is insufficient.
7042 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00007043 case Type::Vector:
7044 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007045 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007046 if (NotEncodedT)
7047 *NotEncodedT = T;
7048 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00007049
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007050 // We could see an undeduced auto type here during error recovery.
7051 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00007052 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007053 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00007054 return;
7055
Xiuli Pan9c14e282016-01-09 12:53:17 +00007056 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00007057#define ABSTRACT_TYPE(KIND, BASE)
7058#define TYPE(KIND, BASE)
7059#define DEPENDENT_TYPE(KIND, BASE) \
7060 case Type::KIND:
7061#define NON_CANONICAL_TYPE(KIND, BASE) \
7062 case Type::KIND:
7063#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7064 case Type::KIND:
7065#include "clang/AST/TypeNodes.def"
7066 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00007067 }
John McCall393a78d2012-12-20 02:45:14 +00007068 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00007069}
7070
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007071void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7072 std::string &S,
7073 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007074 bool includeVBases,
7075 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007076 assert(RDecl && "Expected non-null RecordDecl");
7077 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00007078 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007079 return;
7080
Eugene Zelenko7855e772018-04-03 00:11:50 +00007081 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007082 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7083 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7084
7085 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00007086 for (const auto &BI : CXXRec->bases()) {
7087 if (!BI.isVirtual()) {
7088 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007089 if (base->isEmpty())
7090 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007091 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007092 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7093 std::make_pair(offs, base));
7094 }
7095 }
7096 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007097
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007098 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00007099 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007100 uint64_t offs = layout.getFieldOffset(i);
7101 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00007102 std::make_pair(offs, Field));
7103 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007104 }
7105
7106 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00007107 for (const auto &BI : CXXRec->vbases()) {
7108 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007109 if (base->isEmpty())
7110 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007111 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00007112 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7113 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00007114 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7115 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007116 }
7117 }
7118
7119 CharUnits size;
7120 if (CXXRec) {
7121 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7122 } else {
7123 size = layout.getSize();
7124 }
7125
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007126#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007127 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007128#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007129 std::multimap<uint64_t, NamedDecl *>::iterator
7130 CurLayObj = FieldOrBaseOffsets.begin();
7131
Douglas Gregorf5d6c742012-04-27 22:30:01 +00007132 if (CXXRec && CXXRec->isDynamicClass() &&
7133 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007134 if (FD) {
7135 S += "\"_vptr$";
7136 std::string recname = CXXRec->getNameAsString();
7137 if (recname.empty()) recname = "?";
7138 S += recname;
7139 S += '"';
7140 }
7141 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007142#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007143 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007144#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007145 }
7146
7147 if (!RDecl->hasFlexibleArrayMember()) {
7148 // Mark the end of the structure.
7149 uint64_t offs = toBits(size);
7150 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00007151 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007152 }
7153
7154 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007155#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007156 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007157 if (CurOffs < CurLayObj->first) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007158 uint64_t padding = CurLayObj->first - CurOffs;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007159 // FIXME: There doesn't seem to be a way to indicate in the encoding that
7160 // packing/alignment of members is different that normal, in which case
7161 // the encoding will be out-of-sync with the real layout.
7162 // If the runtime switches to just consider the size of types without
7163 // taking into account alignment, we could make padding explicit in the
7164 // encoding (e.g. using arrays of chars). The encoding strings would be
7165 // longer then though.
7166 CurOffs += padding;
7167 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007168#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007169
7170 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00007171 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007172 break; // reached end of structure.
7173
Eugene Zelenko7855e772018-04-03 00:11:50 +00007174 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007175 // We expand the bases without their virtual bases since those are going
7176 // in the initial structure. Note that this differs from gcc which
7177 // expands virtual bases each time one is encountered in the hierarchy,
7178 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007179 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7180 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007181 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007182#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007183 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007184#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007185 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007186 const auto *field = cast<FieldDecl>(dcl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007187 if (FD) {
7188 S += '"';
7189 S += field->getNameAsString();
7190 S += '"';
7191 }
7192
7193 if (field->isBitField()) {
7194 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007195#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00007196 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007197#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007198 } else {
7199 QualType qt = field->getType();
7200 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00007201 getObjCEncodingForTypeImpl(
7202 qt, S, /*ExpandPointedToStructures=*/false,
7203 /*ExpandStructures=*/true, FD,
7204 /*OutermostType=*/false,
7205 /*EncodingProperty=*/false,
7206 /*StructField=*/true, /*EncodeBlockParameters=*/false,
7207 /*EncodeClassNames=*/false, /*EncodePointerToObjCTypedef=*/false,
7208 NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007209#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007210 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007211#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007212 }
7213 }
7214 }
7215}
7216
Mike Stump11289f42009-09-09 15:08:12 +00007217void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00007218 std::string& S) const {
7219 if (QT & Decl::OBJC_TQ_In)
7220 S += 'n';
7221 if (QT & Decl::OBJC_TQ_Inout)
7222 S += 'N';
7223 if (QT & Decl::OBJC_TQ_Out)
7224 S += 'o';
7225 if (QT & Decl::OBJC_TQ_Bycopy)
7226 S += 'O';
7227 if (QT & Decl::OBJC_TQ_Byref)
7228 S += 'R';
7229 if (QT & Decl::OBJC_TQ_Oneway)
7230 S += 'V';
7231}
7232
Douglas Gregor3ea72692011-08-12 05:46:01 +00007233TypedefDecl *ASTContext::getObjCIdDecl() const {
7234 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007235 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00007236 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007237 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00007238 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00007239 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00007240}
7241
Douglas Gregor52e02802011-08-12 06:17:30 +00007242TypedefDecl *ASTContext::getObjCSelDecl() const {
7243 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007244 QualType T = getPointerType(ObjCBuiltinSelTy);
7245 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00007246 }
7247 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00007248}
7249
Douglas Gregor0a586182011-08-12 05:59:41 +00007250TypedefDecl *ASTContext::getObjCClassDecl() const {
7251 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007252 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00007253 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007254 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00007255 }
Douglas Gregor0a586182011-08-12 05:59:41 +00007256 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00007257}
7258
Douglas Gregord53ae832012-01-17 18:09:05 +00007259ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7260 if (!ObjCProtocolClassDecl) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007261 ObjCProtocolClassDecl
7262 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregord53ae832012-01-17 18:09:05 +00007263 SourceLocation(),
7264 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00007265 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00007266 /*PrevDecl=*/nullptr,
Fangrui Song6907ce22018-07-30 19:24:48 +00007267 SourceLocation(), true);
Douglas Gregord53ae832012-01-17 18:09:05 +00007268 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007269
Douglas Gregord53ae832012-01-17 18:09:05 +00007270 return ObjCProtocolClassDecl;
7271}
7272
Meador Inge5d3fb222012-06-16 03:34:49 +00007273//===----------------------------------------------------------------------===//
7274// __builtin_va_list Construction Functions
7275//===----------------------------------------------------------------------===//
7276
Charles Davisc7d5c942015-09-17 20:55:33 +00007277static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7278 StringRef Name) {
7279 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007280 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00007281 return Context->buildImplicitTypedef(T, Name);
7282}
7283
7284static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7285 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7286}
7287
7288static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7289 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007290}
7291
7292static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7293 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007294 QualType T = Context->getPointerType(Context->VoidTy);
7295 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007296}
7297
Tim Northover9bb857a2013-01-31 12:13:10 +00007298static TypedefDecl *
7299CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007300 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007301 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007302 if (Context->getLangOpts().CPlusPlus) {
7303 // namespace std { struct __va_list {
7304 NamespaceDecl *NS;
7305 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7306 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00007307 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00007308 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007309 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007310 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00007311 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00007312 }
7313
7314 VaListTagDecl->startDefinition();
7315
7316 const size_t NumFields = 5;
7317 QualType FieldTypes[NumFields];
7318 const char *FieldNames[NumFields];
7319
7320 // void *__stack;
7321 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7322 FieldNames[0] = "__stack";
7323
7324 // void *__gr_top;
7325 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7326 FieldNames[1] = "__gr_top";
7327
7328 // void *__vr_top;
7329 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7330 FieldNames[2] = "__vr_top";
7331
7332 // int __gr_offs;
7333 FieldTypes[3] = Context->IntTy;
7334 FieldNames[3] = "__gr_offs";
7335
7336 // int __vr_offs;
7337 FieldTypes[4] = Context->IntTy;
7338 FieldNames[4] = "__vr_offs";
7339
7340 // Create fields
7341 for (unsigned i = 0; i < NumFields; ++i) {
7342 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7343 VaListTagDecl,
7344 SourceLocation(),
7345 SourceLocation(),
7346 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007347 FieldTypes[i], /*TInfo=*/nullptr,
7348 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00007349 /*Mutable=*/false,
7350 ICIS_NoInit);
7351 Field->setAccess(AS_public);
7352 VaListTagDecl->addDecl(Field);
7353 }
7354 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007355 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00007356 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00007357
7358 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007359 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007360}
7361
Meador Inge5d3fb222012-06-16 03:34:49 +00007362static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7363 // typedef struct __va_list_tag {
7364 RecordDecl *VaListTagDecl;
7365
Alp Toker2dea15b2013-12-17 01:22:38 +00007366 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007367 VaListTagDecl->startDefinition();
7368
7369 const size_t NumFields = 5;
7370 QualType FieldTypes[NumFields];
7371 const char *FieldNames[NumFields];
7372
7373 // unsigned char gpr;
7374 FieldTypes[0] = Context->UnsignedCharTy;
7375 FieldNames[0] = "gpr";
7376
7377 // unsigned char fpr;
7378 FieldTypes[1] = Context->UnsignedCharTy;
7379 FieldNames[1] = "fpr";
7380
7381 // unsigned short reserved;
7382 FieldTypes[2] = Context->UnsignedShortTy;
7383 FieldNames[2] = "reserved";
7384
7385 // void* overflow_arg_area;
7386 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7387 FieldNames[3] = "overflow_arg_area";
7388
7389 // void* reg_save_area;
7390 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7391 FieldNames[4] = "reg_save_area";
7392
7393 // Create fields
7394 for (unsigned i = 0; i < NumFields; ++i) {
7395 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7396 SourceLocation(),
7397 SourceLocation(),
7398 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007399 FieldTypes[i], /*TInfo=*/nullptr,
7400 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007401 /*Mutable=*/false,
7402 ICIS_NoInit);
7403 Field->setAccess(AS_public);
7404 VaListTagDecl->addDecl(Field);
7405 }
7406 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007407 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007408 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7409
7410 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007411 TypedefDecl *VaListTagTypedefDecl =
7412 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7413
Meador Inge5d3fb222012-06-16 03:34:49 +00007414 QualType VaListTagTypedefType =
7415 Context->getTypedefType(VaListTagTypedefDecl);
7416
7417 // typedef __va_list_tag __builtin_va_list[1];
7418 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7419 QualType VaListTagArrayType
7420 = Context->getConstantArrayType(VaListTagTypedefType,
7421 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007422 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007423}
7424
7425static TypedefDecl *
7426CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007427 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007428 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007429 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007430 VaListTagDecl->startDefinition();
7431
7432 const size_t NumFields = 4;
7433 QualType FieldTypes[NumFields];
7434 const char *FieldNames[NumFields];
7435
7436 // unsigned gp_offset;
7437 FieldTypes[0] = Context->UnsignedIntTy;
7438 FieldNames[0] = "gp_offset";
7439
7440 // unsigned fp_offset;
7441 FieldTypes[1] = Context->UnsignedIntTy;
7442 FieldNames[1] = "fp_offset";
7443
7444 // void* overflow_arg_area;
7445 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7446 FieldNames[2] = "overflow_arg_area";
7447
7448 // void* reg_save_area;
7449 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7450 FieldNames[3] = "reg_save_area";
7451
7452 // Create fields
7453 for (unsigned i = 0; i < NumFields; ++i) {
7454 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7455 VaListTagDecl,
7456 SourceLocation(),
7457 SourceLocation(),
7458 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007459 FieldTypes[i], /*TInfo=*/nullptr,
7460 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007461 /*Mutable=*/false,
7462 ICIS_NoInit);
7463 Field->setAccess(AS_public);
7464 VaListTagDecl->addDecl(Field);
7465 }
7466 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007467 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007468 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7469
Richard Smith9b88a4c2015-07-27 05:40:23 +00007470 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007471
Richard Smith9b88a4c2015-07-27 05:40:23 +00007472 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007473 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007474 QualType VaListTagArrayType =
7475 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007476 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007477}
7478
7479static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7480 // typedef int __builtin_va_list[4];
7481 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00007482 QualType IntArrayType =
7483 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007484 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007485}
7486
Logan Chien57086ce2012-10-10 06:56:20 +00007487static TypedefDecl *
7488CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007489 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007490 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007491 if (Context->getLangOpts().CPlusPlus) {
7492 // namespace std { struct __va_list {
7493 NamespaceDecl *NS;
7494 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7495 Context->getTranslationUnitDecl(),
7496 /*Inline*/false, SourceLocation(),
7497 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007498 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007499 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007500 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007501 }
7502
7503 VaListDecl->startDefinition();
7504
7505 // void * __ap;
7506 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7507 VaListDecl,
7508 SourceLocation(),
7509 SourceLocation(),
7510 &Context->Idents.get("__ap"),
7511 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007512 /*TInfo=*/nullptr,
7513 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007514 /*Mutable=*/false,
7515 ICIS_NoInit);
7516 Field->setAccess(AS_public);
7517 VaListDecl->addDecl(Field);
7518
7519 // };
7520 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007521 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007522
7523 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007524 QualType T = Context->getRecordType(VaListDecl);
7525 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007526}
7527
Ulrich Weigand47445072013-05-06 16:26:41 +00007528static TypedefDecl *
7529CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007530 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007531 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007532 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007533 VaListTagDecl->startDefinition();
7534
7535 const size_t NumFields = 4;
7536 QualType FieldTypes[NumFields];
7537 const char *FieldNames[NumFields];
7538
7539 // long __gpr;
7540 FieldTypes[0] = Context->LongTy;
7541 FieldNames[0] = "__gpr";
7542
7543 // long __fpr;
7544 FieldTypes[1] = Context->LongTy;
7545 FieldNames[1] = "__fpr";
7546
7547 // void *__overflow_arg_area;
7548 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7549 FieldNames[2] = "__overflow_arg_area";
7550
7551 // void *__reg_save_area;
7552 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7553 FieldNames[3] = "__reg_save_area";
7554
7555 // Create fields
7556 for (unsigned i = 0; i < NumFields; ++i) {
7557 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7558 VaListTagDecl,
7559 SourceLocation(),
7560 SourceLocation(),
7561 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007562 FieldTypes[i], /*TInfo=*/nullptr,
7563 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007564 /*Mutable=*/false,
7565 ICIS_NoInit);
7566 Field->setAccess(AS_public);
7567 VaListTagDecl->addDecl(Field);
7568 }
7569 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007570 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007571 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007572
Richard Smith9b88a4c2015-07-27 05:40:23 +00007573 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007574
7575 // typedef __va_list_tag __builtin_va_list[1];
7576 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007577 QualType VaListTagArrayType =
7578 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007579
Alp Toker56b5cc92013-12-15 10:36:26 +00007580 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007581}
7582
Meador Inge5d3fb222012-06-16 03:34:49 +00007583static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7584 TargetInfo::BuiltinVaListKind Kind) {
7585 switch (Kind) {
7586 case TargetInfo::CharPtrBuiltinVaList:
7587 return CreateCharPtrBuiltinVaListDecl(Context);
7588 case TargetInfo::VoidPtrBuiltinVaList:
7589 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007590 case TargetInfo::AArch64ABIBuiltinVaList:
7591 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007592 case TargetInfo::PowerABIBuiltinVaList:
7593 return CreatePowerABIBuiltinVaListDecl(Context);
7594 case TargetInfo::X86_64ABIBuiltinVaList:
7595 return CreateX86_64ABIBuiltinVaListDecl(Context);
7596 case TargetInfo::PNaClABIBuiltinVaList:
7597 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007598 case TargetInfo::AAPCSABIBuiltinVaList:
7599 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007600 case TargetInfo::SystemZBuiltinVaList:
7601 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007602 }
7603
7604 llvm_unreachable("Unhandled __builtin_va_list type kind");
7605}
7606
7607TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007608 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007609 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007610 assert(BuiltinVaListDecl->isImplicit());
7611 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007612
7613 return BuiltinVaListDecl;
7614}
7615
Richard Smith9b88a4c2015-07-27 05:40:23 +00007616Decl *ASTContext::getVaListTagDecl() const {
7617 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007618 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007619 if (!VaListTagDecl)
7620 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007621
Richard Smith9b88a4c2015-07-27 05:40:23 +00007622 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007623}
7624
Charles Davisc7d5c942015-09-17 20:55:33 +00007625TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7626 if (!BuiltinMSVaListDecl)
7627 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7628
7629 return BuiltinMSVaListDecl;
7630}
7631
Erich Keane41af9712018-04-16 21:30:08 +00007632bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
7633 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
7634}
7635
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007636void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007637 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007638 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007639
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007640 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007641}
7642
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007643/// Retrieve the template name that corresponds to a non-empty
John McCalld28ae272009-12-02 08:04:21 +00007644/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007645TemplateName
7646ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7647 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007648 unsigned size = End - Begin;
7649 assert(size > 1 && "set is not overloaded!");
7650
7651 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7652 size * sizeof(FunctionTemplateDecl*));
Eugene Zelenko7855e772018-04-03 00:11:50 +00007653 auto *OT = new (memory) OverloadedTemplateStorage(size);
John McCalld28ae272009-12-02 08:04:21 +00007654
7655 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007656 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007657 NamedDecl *D = *I;
7658 assert(isa<FunctionTemplateDecl>(D) ||
Richard Smithef53a3e2018-06-06 16:36:56 +00007659 isa<UnresolvedUsingValueDecl>(D) ||
John McCalld28ae272009-12-02 08:04:21 +00007660 (isa<UsingShadowDecl>(D) &&
7661 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7662 *Storage++ = D;
7663 }
7664
7665 return TemplateName(OT);
7666}
7667
Richard Smithb23c5e82019-05-09 03:31:27 +00007668/// Retrieve a template name representing an unqualified-id that has been
7669/// assumed to name a template for ADL purposes.
7670TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
7671 auto *OT = new (*this) AssumedTemplateStorage(Name);
7672 return TemplateName(OT);
7673}
7674
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007675/// Retrieve the template name that represents a qualified
Douglas Gregordc572a32009-03-30 22:58:21 +00007676/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007677TemplateName
7678ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7679 bool TemplateKeyword,
7680 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007681 assert(NNS && "Missing nested-name-specifier in qualified template name");
Fangrui Song6907ce22018-07-30 19:24:48 +00007682
Douglas Gregorc42075a2010-02-04 18:10:26 +00007683 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007684 llvm::FoldingSetNodeID ID;
7685 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7686
Craig Topper36250ad2014-05-12 05:36:57 +00007687 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007688 QualifiedTemplateName *QTN =
7689 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7690 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007691 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007692 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007693 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7694 }
7695
7696 return TemplateName(QTN);
7697}
7698
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007699/// Retrieve the template name that represents a dependent
Douglas Gregordc572a32009-03-30 22:58:21 +00007700/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007701TemplateName
7702ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7703 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007704 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007705 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007706
7707 llvm::FoldingSetNodeID ID;
7708 DependentTemplateName::Profile(ID, NNS, Name);
7709
Craig Topper36250ad2014-05-12 05:36:57 +00007710 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007711 DependentTemplateName *QTN =
7712 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7713
7714 if (QTN)
7715 return TemplateName(QTN);
7716
7717 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7718 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007719 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007720 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007721 } else {
7722 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007723 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007724 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007725 DependentTemplateName *CheckQTN =
7726 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7727 assert(!CheckQTN && "Dependent type name canonicalization broken");
7728 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007729 }
7730
7731 DependentTemplateNames.InsertNode(QTN, InsertPos);
7732 return TemplateName(QTN);
7733}
7734
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007735/// Retrieve the template name that represents a dependent
Douglas Gregor71395fa2009-11-04 00:56:37 +00007736/// template name such as \c MetaFun::template operator+.
Fangrui Song6907ce22018-07-30 19:24:48 +00007737TemplateName
Douglas Gregor71395fa2009-11-04 00:56:37 +00007738ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007739 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007740 assert((!NNS || NNS->isDependent()) &&
7741 "Nested name specifier must be dependent");
Fangrui Song6907ce22018-07-30 19:24:48 +00007742
Douglas Gregor71395fa2009-11-04 00:56:37 +00007743 llvm::FoldingSetNodeID ID;
7744 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007745
7746 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007747 DependentTemplateName *QTN
7748 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007749
Douglas Gregor71395fa2009-11-04 00:56:37 +00007750 if (QTN)
7751 return TemplateName(QTN);
Fangrui Song6907ce22018-07-30 19:24:48 +00007752
Douglas Gregor71395fa2009-11-04 00:56:37 +00007753 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7754 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007755 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007756 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007757 } else {
7758 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007759 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007760 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007761
Douglas Gregorc42075a2010-02-04 18:10:26 +00007762 DependentTemplateName *CheckQTN
7763 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7764 assert(!CheckQTN && "Dependent template name canonicalization broken");
7765 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007766 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007767
Douglas Gregor71395fa2009-11-04 00:56:37 +00007768 DependentTemplateNames.InsertNode(QTN, InsertPos);
7769 return TemplateName(QTN);
7770}
7771
Fangrui Song6907ce22018-07-30 19:24:48 +00007772TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007773ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7774 TemplateName replacement) const {
7775 llvm::FoldingSetNodeID ID;
7776 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007777
7778 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007779 SubstTemplateTemplateParmStorage *subst
7780 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007781
John McCalld9dfe3a2011-06-30 08:33:18 +00007782 if (!subst) {
7783 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7784 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7785 }
7786
7787 return TemplateName(subst);
7788}
7789
Fangrui Song6907ce22018-07-30 19:24:48 +00007790TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007791ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7792 const TemplateArgument &ArgPack) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007793 auto &Self = const_cast<ASTContext &>(*this);
Douglas Gregor5590be02011-01-15 06:45:20 +00007794 llvm::FoldingSetNodeID ID;
7795 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007796
7797 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007798 SubstTemplateTemplateParmPackStorage *Subst
7799 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007800
Douglas Gregor5590be02011-01-15 06:45:20 +00007801 if (!Subst) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007802 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007803 ArgPack.pack_size(),
7804 ArgPack.pack_begin());
7805 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7806 }
7807
7808 return TemplateName(Subst);
7809}
7810
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007811/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007812/// TargetInfo, produce the corresponding type. The unsigned @p Type
7813/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007814CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007815 switch (Type) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007816 case TargetInfo::NoInt: return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007817 case TargetInfo::SignedChar: return SignedCharTy;
7818 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007819 case TargetInfo::SignedShort: return ShortTy;
7820 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7821 case TargetInfo::SignedInt: return IntTy;
7822 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7823 case TargetInfo::SignedLong: return LongTy;
7824 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7825 case TargetInfo::SignedLongLong: return LongLongTy;
7826 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7827 }
7828
David Blaikie83d382b2011-09-23 05:06:16 +00007829 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007830}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007831
7832//===----------------------------------------------------------------------===//
7833// Type Predicates.
7834//===----------------------------------------------------------------------===//
7835
Fariborz Jahanian96207692009-02-18 21:49:28 +00007836/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7837/// garbage collection attribute.
7838///
John McCall553d45a2011-01-12 00:34:59 +00007839Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007840 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007841 return Qualifiers::GCNone;
7842
Erik Pilkingtonfa983902018-10-30 20:31:30 +00007843 assert(getLangOpts().ObjC);
John McCall553d45a2011-01-12 00:34:59 +00007844 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7845
7846 // Default behaviour under objective-C's gc is for ObjC pointers
7847 // (or pointers to them) be treated as though they were declared
7848 // as __strong.
7849 if (GCAttrs == Qualifiers::GCNone) {
7850 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7851 return Qualifiers::Strong;
7852 else if (Ty->isPointerType())
7853 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7854 } else {
7855 // It's not valid to set GC attributes on anything that isn't a
7856 // pointer.
7857#ifndef NDEBUG
7858 QualType CT = Ty->getCanonicalTypeInternal();
Eugene Zelenko7855e772018-04-03 00:11:50 +00007859 while (const auto *AT = dyn_cast<ArrayType>(CT))
John McCall553d45a2011-01-12 00:34:59 +00007860 CT = AT->getElementType();
7861 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7862#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007863 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007864 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007865}
7866
Chris Lattner49af6a42008-04-07 06:51:04 +00007867//===----------------------------------------------------------------------===//
7868// Type Compatibility Testing
7869//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007870
Mike Stump11289f42009-09-09 15:08:12 +00007871/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007872/// compatible.
7873static bool areCompatVectorTypes(const VectorType *LHS,
7874 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007875 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007876 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007877 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007878}
7879
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007880bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7881 QualType SecondVec) {
7882 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7883 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7884
7885 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7886 return true;
7887
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007888 // Treat Neon vector types and most AltiVec vector types as if they are the
7889 // equivalent GCC vector types.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007890 const auto *First = FirstVec->getAs<VectorType>();
7891 const auto *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007892 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007893 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007894 First->getVectorKind() != VectorType::AltiVecPixel &&
7895 First->getVectorKind() != VectorType::AltiVecBool &&
7896 Second->getVectorKind() != VectorType::AltiVecPixel &&
7897 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007898 return true;
7899
7900 return false;
7901}
7902
Steve Naroff8e6aee52009-07-23 01:01:38 +00007903//===----------------------------------------------------------------------===//
7904// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7905//===----------------------------------------------------------------------===//
7906
7907/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7908/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007909bool
7910ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7911 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007912 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007913 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007914 for (auto *PI : rProto->protocols())
7915 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007916 return true;
7917 return false;
7918}
7919
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007920/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7921/// Class<pr1, ...>.
Fangrui Song6907ce22018-07-30 19:24:48 +00007922bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007923 QualType rhs) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007924 const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7925 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007926 assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
Fangrui Song6907ce22018-07-30 19:24:48 +00007927
Aaron Ballman83731462014-03-17 16:14:00 +00007928 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007929 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007930 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007931 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7932 match = true;
7933 break;
7934 }
7935 }
7936 if (!match)
7937 return false;
7938 }
7939 return true;
7940}
7941
Steve Naroff8e6aee52009-07-23 01:01:38 +00007942/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7943/// ObjCQualifiedIDType.
7944bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7945 bool compare) {
7946 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007947 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007948 lhs->isObjCIdType() || lhs->isObjCClassType())
7949 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007950 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007951 rhs->isObjCIdType() || rhs->isObjCClassType())
7952 return true;
7953
7954 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007955 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007956
Steve Naroff8e6aee52009-07-23 01:01:38 +00007957 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007958
Steve Naroff8e6aee52009-07-23 01:01:38 +00007959 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007960 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007961 // make sure we check the class hierarchy.
7962 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007963 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007964 // when comparing an id<P> on lhs with a static type on rhs,
7965 // see if static class implements all of id's protocols, directly or
7966 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007967 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007968 return false;
7969 }
7970 }
7971 // If there are no qualifiers and no interface, we have an 'id'.
7972 return true;
7973 }
Mike Stump11289f42009-09-09 15:08:12 +00007974 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007975 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007976 bool match = false;
7977
7978 // when comparing an id<P> on lhs with a static type on rhs,
7979 // see if static class implements all of id's protocols, directly or
7980 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007981 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007982 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7983 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7984 match = true;
7985 break;
7986 }
7987 }
Mike Stump11289f42009-09-09 15:08:12 +00007988 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007989 // make sure we check the class hierarchy.
7990 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007991 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007992 // when comparing an id<P> on lhs with a static type on rhs,
7993 // see if static class implements all of id's protocols, directly or
7994 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007995 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007996 match = true;
7997 break;
7998 }
7999 }
8000 }
8001 if (!match)
8002 return false;
8003 }
Mike Stump11289f42009-09-09 15:08:12 +00008004
Steve Naroff8e6aee52009-07-23 01:01:38 +00008005 return true;
8006 }
Mike Stump11289f42009-09-09 15:08:12 +00008007
Steve Naroff8e6aee52009-07-23 01:01:38 +00008008 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
8009 assert(rhsQID && "One of the LHS/RHS should be id<x>");
8010
Mike Stump11289f42009-09-09 15:08:12 +00008011 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00008012 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008013 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00008014 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008015 bool match = false;
8016
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008017 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00008018 // see if static class implements all of id's protocols, directly or
8019 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008020 // First, lhs protocols in the qualifier list must be found, direct
8021 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00008022 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008023 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8024 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8025 match = true;
8026 break;
8027 }
8028 }
8029 if (!match)
8030 return false;
8031 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008032
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008033 // Static class's protocols, or its super class or category protocols
8034 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
8035 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
8036 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8037 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8038 // This is rather dubious but matches gcc's behavior. If lhs has
8039 // no type qualifier and its class has no static protocol(s)
8040 // assume that it is mismatch.
8041 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
8042 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00008043 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008044 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00008045 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008046 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8047 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8048 match = true;
8049 break;
8050 }
8051 }
8052 if (!match)
8053 return false;
8054 }
8055 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00008056 return true;
8057 }
8058 return false;
8059}
8060
Eli Friedman47f77112008-08-22 00:56:42 +00008061/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00008062/// compatible for assignment from RHS to LHS. This handles validation of any
8063/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00008064bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
8065 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00008066 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8067 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8068
Steve Naroff1329fa02009-07-15 18:40:39 +00008069 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00008070 if (LHS->isObjCUnqualifiedIdOrClass() ||
8071 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00008072 return true;
8073
Douglas Gregorab209d82015-07-07 03:58:42 +00008074 // Function object that propagates a successful result or handles
8075 // __kindof types.
8076 auto finish = [&](bool succeeded) -> bool {
8077 if (succeeded)
8078 return true;
8079
8080 if (!RHS->isKindOfType())
8081 return false;
8082
8083 // Strip off __kindof and protocol qualifiers, then check whether
8084 // we can assign the other way.
8085 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8086 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8087 };
8088
8089 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8090 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8091 QualType(RHSOPT,0),
8092 false));
8093 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008094
Douglas Gregorab209d82015-07-07 03:58:42 +00008095 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8096 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
8097 QualType(RHSOPT,0)));
8098 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008099
John McCall8b07ec22010-05-15 11:32:37 +00008100 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00008101 if (LHS->getInterface() && RHS->getInterface()) {
8102 return finish(canAssignObjCInterfaces(LHS, RHS));
8103 }
Mike Stump11289f42009-09-09 15:08:12 +00008104
Steve Naroff8e6aee52009-07-23 01:01:38 +00008105 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008106}
8107
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008108/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Fangrui Song6907ce22018-07-30 19:24:48 +00008109/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008110/// arguments in block literals. When passed as arguments, passing 'A*' where
8111/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8112/// not OK. For the return type, the opposite is not OK.
8113bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8114 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008115 const ObjCObjectPointerType *RHSOPT,
8116 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008117
8118 // Function object that propagates a successful result or handles
8119 // __kindof types.
8120 auto finish = [&](bool succeeded) -> bool {
8121 if (succeeded)
8122 return true;
8123
8124 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8125 if (!Expected->isKindOfType())
8126 return false;
8127
8128 // Strip off __kindof and protocol qualifiers, then check whether
8129 // we can assign the other way.
8130 return canAssignObjCInterfacesInBlockPointer(
8131 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8132 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8133 BlockReturnType);
8134 };
8135
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008136 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008137 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00008138
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008139 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008140 return finish(RHSOPT->isObjCBuiltinType() ||
8141 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008142 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008143
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008144 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00008145 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8146 QualType(RHSOPT,0),
8147 false));
Fangrui Song6907ce22018-07-30 19:24:48 +00008148
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008149 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8150 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8151 if (LHS && RHS) { // We have 2 user-defined types.
8152 if (LHS != RHS) {
8153 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008154 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008155 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008156 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008157 }
8158 else
8159 return true;
8160 }
8161 return false;
8162}
8163
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008164/// Comparison routine for Objective-C protocols to be used with
8165/// llvm::array_pod_sort.
8166static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8167 ObjCProtocolDecl * const *rhs) {
8168 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008169}
8170
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008171/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008172/// of protocols inherited from two distinct objective-c pointer objects with
8173/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008174/// It is used to build composite qualifier list of the composite type of
8175/// the conditional expression involving two objective-c pointer objects.
Fangrui Song6907ce22018-07-30 19:24:48 +00008176static
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008177void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008178 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008179 const ObjCObjectPointerType *LHSOPT,
8180 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008181 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008182
John McCall8b07ec22010-05-15 11:32:37 +00008183 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8184 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8185 assert(LHS->getInterface() && "LHS must have an interface base");
8186 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008187
8188 // Add all of the protocols for the LHS.
8189 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8190
8191 // Start with the protocol qualifiers.
8192 for (auto proto : LHS->quals()) {
8193 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008194 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008195
8196 // Also add the protocols associated with the LHS interface.
8197 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8198
Raphael Isemannb23ccec2018-12-10 12:37:46 +00008199 // Add all of the protocols for the RHS.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008200 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8201
8202 // Start with the protocol qualifiers.
8203 for (auto proto : RHS->quals()) {
8204 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008205 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008206
8207 // Also add the protocols associated with the RHS interface.
8208 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8209
8210 // Compute the intersection of the collected protocol sets.
8211 for (auto proto : LHSProtocolSet) {
8212 if (RHSProtocolSet.count(proto))
8213 IntersectionSet.push_back(proto);
8214 }
8215
8216 // Compute the set of protocols that is implied by either the common type or
8217 // the protocols within the intersection.
8218 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8219 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8220
8221 // Remove any implied protocols from the list of inherited protocols.
8222 if (!ImpliedProtocols.empty()) {
8223 IntersectionSet.erase(
8224 std::remove_if(IntersectionSet.begin(),
8225 IntersectionSet.end(),
8226 [&](ObjCProtocolDecl *proto) -> bool {
8227 return ImpliedProtocols.count(proto) > 0;
8228 }),
8229 IntersectionSet.end());
8230 }
8231
8232 // Sort the remaining protocols by name.
8233 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8234 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008235}
8236
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008237/// Determine whether the first type is a subtype of the second.
8238static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8239 QualType rhs) {
8240 // Common case: two object pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008241 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8242 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008243 if (lhsOPT && rhsOPT)
8244 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8245
8246 // Two block pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008247 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8248 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008249 if (lhsBlock && rhsBlock)
8250 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8251
8252 // If either is an unqualified 'id' and the other is a block, it's
8253 // acceptable.
8254 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8255 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8256 return true;
8257
8258 return false;
8259}
8260
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008261// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008262static bool sameObjCTypeArgs(ASTContext &ctx,
8263 const ObjCInterfaceDecl *iface,
8264 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00008265 ArrayRef<QualType> rhsArgs,
8266 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008267 if (lhsArgs.size() != rhsArgs.size())
8268 return false;
8269
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008270 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008271 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008272 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8273 continue;
8274
8275 switch (typeParams->begin()[i]->getVariance()) {
8276 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00008277 if (!stripKindOf ||
8278 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8279 rhsArgs[i].stripObjCKindOfType(ctx))) {
8280 return false;
8281 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008282 break;
8283
8284 case ObjCTypeParamVariance::Covariant:
8285 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8286 return false;
8287 break;
8288
8289 case ObjCTypeParamVariance::Contravariant:
8290 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8291 return false;
8292 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00008293 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008294 }
8295
8296 return true;
8297}
8298
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008299QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008300 const ObjCObjectPointerType *Lptr,
8301 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00008302 const ObjCObjectType *LHS = Lptr->getObjectType();
8303 const ObjCObjectType *RHS = Rptr->getObjectType();
8304 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8305 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008306
8307 if (!LDecl || !RDecl)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008308 return {};
Douglas Gregore83b9562015-07-07 03:57:53 +00008309
Manman Renc46f7d12016-05-06 19:35:02 +00008310 // When either LHS or RHS is a kindof type, we should return a kindof type.
8311 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8312 // kindof(A).
8313 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8314
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008315 // Follow the left-hand side up the class hierarchy until we either hit a
8316 // root or find the RHS. Record the ancestors in case we don't find it.
8317 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8318 LHSAncestors;
8319 while (true) {
8320 // Record this ancestor. We'll need this if the common type isn't in the
8321 // path from the LHS to the root.
8322 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00008323
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008324 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8325 // Get the type arguments.
8326 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8327 bool anyChanges = false;
8328 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8329 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008330 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8331 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008332 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008333 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008334 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8335 // If only one has type arguments, the result will not have type
8336 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008337 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008338 anyChanges = true;
8339 }
8340
8341 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008342 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008343 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8344 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00008345 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008346 anyChanges = true;
8347
8348 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00008349 // If we need to return a kindof type but LHS is not a kindof type, we
8350 // build a new result type.
8351 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008352 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008353 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008354 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008355 return getObjCObjectPointerType(Result);
8356 }
8357
8358 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008359 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008360
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008361 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00008362 QualType LHSSuperType = LHS->getSuperClassType();
8363 if (LHSSuperType.isNull())
8364 break;
8365
8366 LHS = LHSSuperType->castAs<ObjCObjectType>();
8367 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008368
8369 // We didn't find anything by following the LHS to its root; now check
8370 // the RHS against the cached set of ancestors.
8371 while (true) {
8372 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8373 if (KnownLHS != LHSAncestors.end()) {
8374 LHS = KnownLHS->second;
8375
8376 // Get the type arguments.
8377 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8378 bool anyChanges = false;
8379 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8380 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008381 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8382 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008383 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008384 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008385 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8386 // If only one has type arguments, the result will not have type
8387 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008388 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008389 anyChanges = true;
8390 }
8391
8392 // Compute the intersection of protocols.
8393 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8394 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8395 Protocols);
8396 if (!Protocols.empty())
8397 anyChanges = true;
8398
Manman Renc46f7d12016-05-06 19:35:02 +00008399 // If we need to return a kindof type but RHS is not a kindof type, we
8400 // build a new result type.
8401 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008402 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008403 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008404 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008405 return getObjCObjectPointerType(Result);
8406 }
8407
8408 return getObjCObjectPointerType(QualType(RHS, 0));
8409 }
8410
8411 // Find the superclass of the RHS.
8412 QualType RHSSuperType = RHS->getSuperClassType();
8413 if (RHSSuperType.isNull())
8414 break;
8415
8416 RHS = RHSSuperType->castAs<ObjCObjectType>();
8417 }
8418
Eugene Zelenko7855e772018-04-03 00:11:50 +00008419 return {};
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008420}
8421
John McCall8b07ec22010-05-15 11:32:37 +00008422bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8423 const ObjCObjectType *RHS) {
8424 assert(LHS->getInterface() && "LHS is not an interface type");
8425 assert(RHS->getInterface() && "RHS is not an interface type");
8426
Chris Lattner49af6a42008-04-07 06:51:04 +00008427 // Verify that the base decls are compatible: the RHS must be a subclass of
8428 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008429 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8430 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8431 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008432 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008433
Douglas Gregore83b9562015-07-07 03:57:53 +00008434 // If the LHS has protocol qualifiers, determine whether all of them are
8435 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8436 // LHS).
8437 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008438 // OK if conversion of LHS to SuperClass results in narrowing of types
8439 // ; i.e., SuperClass may implement at least one of the protocols
8440 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8441 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8442 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8443 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8444 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8445 // qualifiers.
8446 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008447 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008448 // If there is no protocols associated with RHS, it is not a match.
8449 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008450 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008451
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008452 for (const auto *LHSProto : LHS->quals()) {
8453 bool SuperImplementsProtocol = false;
8454 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8455 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8456 SuperImplementsProtocol = true;
8457 break;
8458 }
8459 if (!SuperImplementsProtocol)
8460 return false;
8461 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008462 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008463
8464 // If the LHS is specialized, we may need to check type arguments.
8465 if (LHS->isSpecialized()) {
8466 // Follow the superclass chain until we've matched the LHS class in the
8467 // hierarchy. This substitutes type arguments through.
8468 const ObjCObjectType *RHSSuper = RHS;
8469 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8470 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8471
8472 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008473 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008474 !sameObjCTypeArgs(*this, LHS->getInterface(),
8475 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008476 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008477 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008478 }
8479 }
8480
8481 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008482}
8483
Steve Naroffb7605152009-02-12 17:52:19 +00008484bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8485 // get the "pointed to" types
Eugene Zelenko7855e772018-04-03 00:11:50 +00008486 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8487 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008488
Steve Naroff7cae42b2009-07-10 23:34:53 +00008489 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008490 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008491
8492 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8493 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008494}
8495
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008496bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8497 return canAssignObjCInterfaces(
8498 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8499 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8500}
8501
Mike Stump11289f42009-09-09 15:08:12 +00008502/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008503/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008504/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008505/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008506bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8507 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008508 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008509 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008510
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008511 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008512}
8513
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008514bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008515 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008516}
8517
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008518bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8519 return !mergeTypes(LHS, RHS, true).isNull();
8520}
8521
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008522/// mergeTransparentUnionType - if T is a transparent union type and a member
8523/// of T is compatible with SubType, return the merged type, else return
8524/// QualType()
8525QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8526 bool OfBlockPointer,
8527 bool Unqualified) {
8528 if (const RecordType *UT = T->getAsUnionType()) {
8529 RecordDecl *UD = UT->getDecl();
8530 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008531 for (const auto *I : UD->fields()) {
8532 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008533 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8534 if (!MT.isNull())
8535 return MT;
8536 }
8537 }
8538 }
8539
Eugene Zelenko7855e772018-04-03 00:11:50 +00008540 return {};
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008541}
8542
Alp Toker9cacbab2014-01-20 20:26:09 +00008543/// mergeFunctionParameterTypes - merge two types which appear as function
8544/// parameter types
8545QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8546 bool OfBlockPointer,
8547 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008548 // GNU extension: two types are compatible if they appear as a function
8549 // argument, one of the types is a transparent union type and the other
8550 // type is compatible with a union member
8551 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8552 Unqualified);
8553 if (!lmerge.isNull())
8554 return lmerge;
8555
8556 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8557 Unqualified);
8558 if (!rmerge.isNull())
8559 return rmerge;
8560
8561 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8562}
8563
Fangrui Song6907ce22018-07-30 19:24:48 +00008564QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008565 bool OfBlockPointer,
8566 bool Unqualified) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008567 const auto *lbase = lhs->getAs<FunctionType>();
8568 const auto *rbase = rhs->getAs<FunctionType>();
8569 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8570 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008571 bool allLTypes = true;
8572 bool allRTypes = true;
8573
8574 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008575 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008576 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008577 QualType RHS = rbase->getReturnType();
8578 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008579 bool UnqualifiedResult = Unqualified;
8580 if (!UnqualifiedResult)
8581 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008582 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008583 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008584 else
Alp Toker314cc812014-01-25 16:55:45 +00008585 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008586 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008587 if (retType.isNull())
8588 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00008589
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008590 if (Unqualified)
8591 retType = retType.getUnqualifiedType();
8592
Alp Toker314cc812014-01-25 16:55:45 +00008593 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8594 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008595 if (Unqualified) {
8596 LRetType = LRetType.getUnqualifiedType();
8597 RRetType = RRetType.getUnqualifiedType();
8598 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008599
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008600 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008601 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008602 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008603 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008604
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008605 // FIXME: double check this
8606 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8607 // rbase->getRegParmAttr() != 0 &&
8608 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008609 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8610 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008611
Douglas Gregor8c940862010-01-18 17:14:39 +00008612 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008613 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008614 return {};
Mike Stump11289f42009-09-09 15:08:12 +00008615
John McCall8c6b56f2010-12-15 01:06:38 +00008616 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008617 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008618 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008619 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008620 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008621
John McCall31168b02011-06-15 23:02:42 +00008622 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008623 return {};
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008624 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008625 return {};
Oren Ben Simhon220671a2018-03-17 13:31:35 +00008626 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008627 return {};
John McCall31168b02011-06-15 23:02:42 +00008628
John McCall8c6b56f2010-12-15 01:06:38 +00008629 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8630 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008631
Rafael Espindola8778c282012-11-29 16:09:03 +00008632 if (lbaseInfo.getNoReturn() != NoReturn)
8633 allLTypes = false;
8634 if (rbaseInfo.getNoReturn() != NoReturn)
8635 allRTypes = false;
8636
John McCall31168b02011-06-15 23:02:42 +00008637 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008638
Eli Friedman47f77112008-08-22 00:56:42 +00008639 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008640 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8641 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008642 // Compatible functions must have the same number of parameters
8643 if (lproto->getNumParams() != rproto->getNumParams())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008644 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008645
8646 // Variadic and non-variadic functions aren't compatible
8647 if (lproto->isVariadic() != rproto->isVariadic())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008648 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008649
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008650 if (lproto->getMethodQuals() != rproto->getMethodQuals())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008651 return {};
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008652
Akira Hatanaka98a49332017-09-22 00:41:05 +00008653 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8654 bool canUseLeft, canUseRight;
8655 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8656 newParamInfos))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008657 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008658
Akira Hatanaka98a49332017-09-22 00:41:05 +00008659 if (!canUseLeft)
8660 allLTypes = false;
8661 if (!canUseRight)
8662 allRTypes = false;
8663
Alp Toker601b22c2014-01-21 23:35:24 +00008664 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008665 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008666 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8667 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8668 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8669 QualType paramType = mergeFunctionParameterTypes(
8670 lParamType, rParamType, OfBlockPointer, Unqualified);
8671 if (paramType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008672 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008673
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008674 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008675 paramType = paramType.getUnqualifiedType();
8676
8677 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008678 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008679 lParamType = lParamType.getUnqualifiedType();
8680 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008681 }
Alp Toker601b22c2014-01-21 23:35:24 +00008682
8683 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008684 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008685 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008686 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008687 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008688
Eli Friedman47f77112008-08-22 00:56:42 +00008689 if (allLTypes) return lhs;
8690 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008691
8692 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8693 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008694 EPI.ExtParameterInfos =
8695 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008696 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008697 }
8698
8699 if (lproto) allRTypes = false;
8700 if (rproto) allLTypes = false;
8701
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008702 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008703 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008704 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008705 if (proto->isVariadic())
8706 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008707 // Check that the types are compatible with the types that
8708 // would result from default argument promotions (C99 6.7.5.3p15).
8709 // The only types actually affected are promotable integer
8710 // types and floats, which would be passed as a different
8711 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008712 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8713 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008714
Eli Friedman448ce402012-08-30 00:44:15 +00008715 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008716 // to pass enum values.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008717 if (const auto *Enum = paramTy->getAs<EnumType>()) {
Alp Toker601b22c2014-01-21 23:35:24 +00008718 paramTy = Enum->getDecl()->getIntegerType();
8719 if (paramTy.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008720 return {};
Eli Friedman448ce402012-08-30 00:44:15 +00008721 }
Alp Toker601b22c2014-01-21 23:35:24 +00008722
8723 if (paramTy->isPromotableIntegerType() ||
8724 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008725 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008726 }
8727
8728 if (allLTypes) return lhs;
8729 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008730
8731 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8732 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008733 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008734 }
8735
8736 if (allLTypes) return lhs;
8737 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008738 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008739}
8740
John McCall433c2e62013-03-21 00:10:07 +00008741/// Given that we have an enum type and a non-enum type, try to merge them.
8742static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8743 QualType other, bool isBlockReturnType) {
8744 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8745 // a signed integer type, or an unsigned integer type.
8746 // Compatibility is based on the underlying type, not the promotion
8747 // type.
8748 QualType underlyingType = ET->getDecl()->getIntegerType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00008749 if (underlyingType.isNull())
8750 return {};
John McCall433c2e62013-03-21 00:10:07 +00008751 if (Context.hasSameType(underlyingType, other))
8752 return other;
8753
8754 // In block return types, we're more permissive and accept any
8755 // integral type of the same size.
8756 if (isBlockReturnType && other->isIntegerType() &&
8757 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8758 return other;
8759
Eugene Zelenko7855e772018-04-03 00:11:50 +00008760 return {};
John McCall433c2e62013-03-21 00:10:07 +00008761}
8762
Fangrui Song6907ce22018-07-30 19:24:48 +00008763QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008764 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008765 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008766 // C++ [expr]: If an expression initially has the type "reference to T", the
8767 // type is adjusted to "T" prior to any further analysis, the expression
8768 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008769 // expression is an lvalue unless the reference is an rvalue reference and
8770 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008771 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8772 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008773
8774 if (Unqualified) {
8775 LHS = LHS.getUnqualifiedType();
8776 RHS = RHS.getUnqualifiedType();
8777 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008778
Eli Friedman47f77112008-08-22 00:56:42 +00008779 QualType LHSCan = getCanonicalType(LHS),
8780 RHSCan = getCanonicalType(RHS);
8781
8782 // If two types are identical, they are compatible.
8783 if (LHSCan == RHSCan)
8784 return LHS;
8785
John McCall8ccfcb52009-09-24 19:53:00 +00008786 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008787 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8788 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008789 if (LQuals != RQuals) {
8790 // If any of these qualifiers are different, we have a type
8791 // mismatch.
8792 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008793 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008794 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8795 LQuals.hasUnaligned() != RQuals.hasUnaligned())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008796 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008797
8798 // Exactly one GC qualifier difference is allowed: __strong is
8799 // okay if the other type has no GC qualifier but is an Objective
8800 // C object pointer (i.e. implicitly strong by default). We fix
8801 // this by pretending that the unqualified type was actually
8802 // qualified __strong.
8803 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8804 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8805 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8806
8807 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008808 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008809
8810 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8811 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8812 }
8813 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8814 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8815 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008816 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008817 }
8818
8819 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008820
Eli Friedmandcca6332009-06-01 01:22:52 +00008821 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8822 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008823
Chris Lattnerfd652912008-01-14 05:45:46 +00008824 // We want to consider the two function types to be the same for these
8825 // comparisons, just force one to the other.
8826 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8827 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008828
8829 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008830 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8831 LHSClass = Type::ConstantArray;
8832 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8833 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008834
John McCall8b07ec22010-05-15 11:32:37 +00008835 // ObjCInterfaces are just specialized ObjCObjects.
8836 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8837 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8838
Nate Begemance4d7fc2008-04-18 23:10:10 +00008839 // Canonicalize ExtVector -> Vector.
8840 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8841 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008842
Chris Lattner95554662008-04-07 05:43:21 +00008843 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008844 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008845 // Note that we only have special rules for turning block enum
8846 // returns into block int returns, not vice-versa.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008847 if (const auto *ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008848 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008849 }
John McCall9dd450b2009-09-21 23:43:11 +00008850 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008851 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008852 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008853 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008854 if (OfBlockPointer && !BlockReturnType) {
8855 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8856 return LHS;
8857 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8858 return RHS;
8859 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008860
Eugene Zelenko7855e772018-04-03 00:11:50 +00008861 return {};
Steve Naroff32e44c02007-10-15 20:41:53 +00008862 }
Eli Friedman47f77112008-08-22 00:56:42 +00008863
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008864 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008865 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008866#define TYPE(Class, Base)
8867#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008868#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008869#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8870#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8871#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008872 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008873
Richard Smith27d807c2013-04-30 13:56:41 +00008874 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008875 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008876 case Type::LValueReference:
8877 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008878 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008879 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008880
John McCall8b07ec22010-05-15 11:32:37 +00008881 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008882 case Type::IncompleteArray:
8883 case Type::VariableArray:
8884 case Type::FunctionProto:
8885 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008886 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008887
Chris Lattnerfd652912008-01-14 05:45:46 +00008888 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008889 {
8890 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008891 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8892 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008893 if (Unqualified) {
8894 LHSPointee = LHSPointee.getUnqualifiedType();
8895 RHSPointee = RHSPointee.getUnqualifiedType();
8896 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008897 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008898 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008899 if (ResultType.isNull())
8900 return {};
Eli Friedman091a9ac2009-06-02 05:28:56 +00008901 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008902 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008903 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008904 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008905 return getPointerType(ResultType);
8906 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008907 case Type::BlockPointer:
8908 {
8909 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008910 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8911 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008912 if (Unqualified) {
8913 LHSPointee = LHSPointee.getUnqualifiedType();
8914 RHSPointee = RHSPointee.getUnqualifiedType();
8915 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008916 if (getLangOpts().OpenCL) {
8917 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8918 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8919 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8920 // 6.12.5) thus the following check is asymmetric.
8921 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008922 return {};
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008923 LHSPteeQual.removeAddressSpace();
8924 RHSPteeQual.removeAddressSpace();
8925 LHSPointee =
8926 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8927 RHSPointee =
8928 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8929 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008930 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8931 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008932 if (ResultType.isNull())
8933 return {};
Steve Naroff68e167d2008-12-10 17:49:55 +00008934 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8935 return LHS;
8936 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8937 return RHS;
8938 return getBlockPointerType(ResultType);
8939 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008940 case Type::Atomic:
8941 {
8942 // Merge two pointer types, while trying to preserve typedef info
8943 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8944 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8945 if (Unqualified) {
8946 LHSValue = LHSValue.getUnqualifiedType();
8947 RHSValue = RHSValue.getUnqualifiedType();
8948 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008949 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
Eli Friedman0dfb8892011-10-06 23:00:33 +00008950 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008951 if (ResultType.isNull())
8952 return {};
Eli Friedman0dfb8892011-10-06 23:00:33 +00008953 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8954 return LHS;
8955 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8956 return RHS;
8957 return getAtomicType(ResultType);
8958 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008959 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008960 {
8961 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8962 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8963 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008964 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008965
8966 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8967 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008968 if (Unqualified) {
8969 LHSElem = LHSElem.getUnqualifiedType();
8970 RHSElem = RHSElem.getUnqualifiedType();
8971 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008972
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008973 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008974 if (ResultType.isNull())
8975 return {};
Jeremy Morse8129c5c2018-06-05 09:18:26 +00008976
8977 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8978 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
8979
8980 // If either side is a variable array, and both are complete, check whether
8981 // the current dimension is definite.
8982 if (LVAT || RVAT) {
8983 auto SizeFetch = [this](const VariableArrayType* VAT,
8984 const ConstantArrayType* CAT)
8985 -> std::pair<bool,llvm::APInt> {
8986 if (VAT) {
8987 llvm::APSInt TheInt;
8988 Expr *E = VAT->getSizeExpr();
8989 if (E && E->isIntegerConstantExpr(TheInt, *this))
8990 return std::make_pair(true, TheInt);
8991 else
8992 return std::make_pair(false, TheInt);
8993 } else if (CAT) {
8994 return std::make_pair(true, CAT->getSize());
8995 } else {
8996 return std::make_pair(false, llvm::APInt());
8997 }
8998 };
8999
9000 bool HaveLSize, HaveRSize;
9001 llvm::APInt LSize, RSize;
9002 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
9003 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
9004 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
9005 return {}; // Definite, but unequal, array dimension
9006 }
9007
Chris Lattner465fa322008-10-05 17:34:18 +00009008 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9009 return LHS;
9010 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9011 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00009012 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
9013 ArrayType::ArraySizeModifier(), 0);
9014 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
9015 ArrayType::ArraySizeModifier(), 0);
Chris Lattner465fa322008-10-05 17:34:18 +00009016 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9017 return LHS;
9018 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9019 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00009020 if (LVAT) {
9021 // FIXME: This isn't correct! But tricky to implement because
9022 // the array's size has to be the size of LHS, but the type
9023 // has to be different.
9024 return LHS;
9025 }
9026 if (RVAT) {
9027 // FIXME: This isn't correct! But tricky to implement because
9028 // the array's size has to be the size of RHS, but the type
9029 // has to be different.
9030 return RHS;
9031 }
Eli Friedman3e62c212008-08-22 01:48:21 +00009032 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
9033 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00009034 return getIncompleteArrayType(ResultType,
9035 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00009036 }
Chris Lattnerfd652912008-01-14 05:45:46 +00009037 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009038 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009039 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009040 case Type::Enum:
Eugene Zelenko7855e772018-04-03 00:11:50 +00009041 return {};
Chris Lattnerfd652912008-01-14 05:45:46 +00009042 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009043 // Only exactly equal builtin types are compatible, which is tested above.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009044 return {};
Daniel Dunbar804c0442009-01-28 21:22:12 +00009045 case Type::Complex:
9046 // Distinct complex types are incompatible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009047 return {};
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009048 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00009049 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00009050 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
9051 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00009052 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009053 return {};
John McCall8b07ec22010-05-15 11:32:37 +00009054 case Type::ObjCObject: {
9055 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00009056 // FIXME: This should be type compatibility, e.g. whether
9057 // "LHS x; RHS x;" at global scope is legal.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009058 const auto *LHSIface = LHS->getAs<ObjCObjectType>();
9059 const auto *RHSIface = RHS->getAs<ObjCObjectType>();
John McCall8b07ec22010-05-15 11:32:37 +00009060 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00009061 return LHS;
9062
Eugene Zelenko7855e772018-04-03 00:11:50 +00009063 return {};
Cedric Venet4fc88b72009-02-21 17:14:49 +00009064 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009065 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009066 if (OfBlockPointer) {
9067 if (canAssignObjCInterfacesInBlockPointer(
9068 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00009069 RHS->getAs<ObjCObjectPointerType>(),
9070 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00009071 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009072 return {};
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009073 }
John McCall9dd450b2009-09-21 23:43:11 +00009074 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
9075 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00009076 return LHS;
9077
Eugene Zelenko7855e772018-04-03 00:11:50 +00009078 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009079 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00009080 assert(LHS != RHS &&
9081 "Equivalent pipe types should have already been handled!");
Eugene Zelenko7855e772018-04-03 00:11:50 +00009082 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009083 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009084
David Blaikie8a40f702012-01-17 06:56:22 +00009085 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00009086}
Ted Kremenekfc581a92007-10-31 17:10:13 +00009087
Akira Hatanaka98a49332017-09-22 00:41:05 +00009088bool ASTContext::mergeExtParameterInfo(
9089 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9090 bool &CanUseFirst, bool &CanUseSecond,
9091 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9092 assert(NewParamInfos.empty() && "param info list not empty");
9093 CanUseFirst = CanUseSecond = true;
9094 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9095 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9096
John McCall18afab72016-03-01 00:49:02 +00009097 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00009098 // we match if and only if the second type also doesn't have them.
9099 if (!FirstHasInfo && !SecondHasInfo)
9100 return true;
John McCall18afab72016-03-01 00:49:02 +00009101
Akira Hatanaka98a49332017-09-22 00:41:05 +00009102 bool NeedParamInfo = false;
9103 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9104 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00009105
Akira Hatanaka98a49332017-09-22 00:41:05 +00009106 for (size_t I = 0; I < E; ++I) {
9107 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9108 if (FirstHasInfo)
9109 FirstParam = FirstFnType->getExtParameterInfo(I);
9110 if (SecondHasInfo)
9111 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00009112
Akira Hatanaka98a49332017-09-22 00:41:05 +00009113 // Cannot merge unless everything except the noescape flag matches.
9114 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00009115 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00009116
9117 bool FirstNoEscape = FirstParam.isNoEscape();
9118 bool SecondNoEscape = SecondParam.isNoEscape();
9119 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9120 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9121 if (NewParamInfos.back().getOpaqueValue())
9122 NeedParamInfo = true;
9123 if (FirstNoEscape != IsNoEscape)
9124 CanUseFirst = false;
9125 if (SecondNoEscape != IsNoEscape)
9126 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00009127 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00009128
9129 if (!NeedParamInfo)
9130 NewParamInfos.clear();
9131
Fariborz Jahanian97676972011-09-28 21:52:05 +00009132 return true;
9133}
9134
Chandler Carruth21c90602015-12-30 03:24:14 +00009135void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9136 ObjCLayouts[CD] = nullptr;
9137}
9138
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009139/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9140/// 'RHS' attributes and returns the merged version; including for function
9141/// return types.
9142QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9143 QualType LHSCan = getCanonicalType(LHS),
9144 RHSCan = getCanonicalType(RHS);
9145 // If two types are identical, they are compatible.
9146 if (LHSCan == RHSCan)
9147 return LHS;
9148 if (RHSCan->isFunctionType()) {
9149 if (!LHSCan->isFunctionType())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009150 return {};
Alp Toker314cc812014-01-25 16:55:45 +00009151 QualType OldReturnType =
9152 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009153 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00009154 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009155 QualType ResReturnType =
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009156 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9157 if (ResReturnType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009158 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009159 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9160 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9161 // In either case, use OldReturnType to build the new function type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009162 const auto *F = LHS->getAs<FunctionType>();
9163 if (const auto *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009164 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9165 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00009166 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00009167 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009168 return ResultType;
9169 }
9170 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009171 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009172 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009173
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009174 // If the qualifiers are different, the types can still be merged.
9175 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9176 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9177 if (LQuals != RQuals) {
9178 // If any of these qualifiers are different, we have a type mismatch.
9179 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9180 LQuals.getAddressSpace() != RQuals.getAddressSpace())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009181 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009182
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009183 // Exactly one GC qualifier difference is allowed: __strong is
9184 // okay if the other type has no GC qualifier but is an Objective
9185 // C object pointer (i.e. implicitly strong by default). We fix
9186 // this by pretending that the unqualified type was actually
9187 // qualified __strong.
9188 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9189 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9190 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
Fangrui Song6907ce22018-07-30 19:24:48 +00009191
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009192 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009193 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009194
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009195 if (GC_L == Qualifiers::Strong)
9196 return LHS;
9197 if (GC_R == Qualifiers::Strong)
9198 return RHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009199 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009200 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009201
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009202 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
9203 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9204 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9205 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9206 if (ResQT == LHSBaseQT)
9207 return LHS;
9208 if (ResQT == RHSBaseQT)
9209 return RHS;
9210 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009211 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009212}
9213
Chris Lattner4ba0cef2008-04-07 07:01:58 +00009214//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009215// Integer Predicates
9216//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00009217
Jay Foad39c79802011-01-12 09:06:06 +00009218unsigned ASTContext::getIntWidth(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009219 if (const auto *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00009220 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00009221 if (T->isBooleanType())
9222 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00009223 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009224 return (unsigned)getTypeSize(T);
9225}
9226
Abramo Bagnara13640492012-09-09 10:21:24 +00009227QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Leonard Chanab80f3c2018-06-14 14:53:51 +00009228 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9229 "Unexpected type");
Fangrui Song6907ce22018-07-30 19:24:48 +00009230
Chris Lattnerec3a1562009-10-17 20:33:28 +00009231 // Turn <4 x signed int> -> <4 x unsigned int>
Eugene Zelenko7855e772018-04-03 00:11:50 +00009232 if (const auto *VTy = T->getAs<VectorType>())
Chris Lattnerec3a1562009-10-17 20:33:28 +00009233 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00009234 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00009235
9236 // For enums, we return the unsigned version of the base type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009237 if (const auto *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009238 T = ETy->getDecl()->getIntegerType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009239
Eugene Zelenko7855e772018-04-03 00:11:50 +00009240 const auto *BTy = T->getAs<BuiltinType>();
Leonard Chanab80f3c2018-06-14 14:53:51 +00009241 assert(BTy && "Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009242 switch (BTy->getKind()) {
9243 case BuiltinType::Char_S:
9244 case BuiltinType::SChar:
9245 return UnsignedCharTy;
9246 case BuiltinType::Short:
9247 return UnsignedShortTy;
9248 case BuiltinType::Int:
9249 return UnsignedIntTy;
9250 case BuiltinType::Long:
9251 return UnsignedLongTy;
9252 case BuiltinType::LongLong:
9253 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00009254 case BuiltinType::Int128:
9255 return UnsignedInt128Ty;
Leonard Chanab80f3c2018-06-14 14:53:51 +00009256
9257 case BuiltinType::ShortAccum:
9258 return UnsignedShortAccumTy;
9259 case BuiltinType::Accum:
9260 return UnsignedAccumTy;
9261 case BuiltinType::LongAccum:
9262 return UnsignedLongAccumTy;
9263 case BuiltinType::SatShortAccum:
9264 return SatUnsignedShortAccumTy;
9265 case BuiltinType::SatAccum:
9266 return SatUnsignedAccumTy;
9267 case BuiltinType::SatLongAccum:
9268 return SatUnsignedLongAccumTy;
9269 case BuiltinType::ShortFract:
9270 return UnsignedShortFractTy;
9271 case BuiltinType::Fract:
9272 return UnsignedFractTy;
9273 case BuiltinType::LongFract:
9274 return UnsignedLongFractTy;
9275 case BuiltinType::SatShortFract:
9276 return SatUnsignedShortFractTy;
9277 case BuiltinType::SatFract:
9278 return SatUnsignedFractTy;
9279 case BuiltinType::SatLongFract:
9280 return SatUnsignedLongFractTy;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009281 default:
Leonard Chanab80f3c2018-06-14 14:53:51 +00009282 llvm_unreachable("Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009283 }
9284}
9285
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009286ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00009287
Richard Smith1fa5d642013-05-11 05:45:24 +00009288void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9289 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00009290
9291//===----------------------------------------------------------------------===//
9292// Builtin Type Computation
9293//===----------------------------------------------------------------------===//
9294
9295/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00009296/// pointer over the consumed characters. This returns the resultant type. If
9297/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9298/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9299/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009300///
9301/// RequiresICE is filled in on return to indicate whether the value is required
9302/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00009303static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00009304 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009305 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00009306 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00009307 // Modifiers.
9308 int HowLong = 0;
9309 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009310 RequiresICE = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009311
Chris Lattnerdc226c22010-10-01 22:42:38 +00009312 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00009313 bool Done = false;
9314 #ifndef NDEBUG
9315 bool IsSpecialLong = false;
9316 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00009317 while (!Done) {
9318 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00009319 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00009320 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009321 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00009322 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009323 case 'S':
9324 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9325 assert(!Signed && "Can't use 'S' modifier multiple times!");
9326 Signed = true;
9327 break;
9328 case 'U':
9329 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00009330 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009331 Unsigned = true;
9332 break;
9333 case 'L':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009334 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009335 assert(HowLong <= 2 && "Can't have LLLL modifier");
9336 ++HowLong;
9337 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009338 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009339 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
9340 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
9341 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009342 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009343 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009344 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009345 if (Context.getTargetInfo().getLongWidth() == 32)
9346 ++HowLong;
9347 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00009348 case 'W':
9349 // This modifier represents int64 type.
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009350 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00009351 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009352 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009353 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009354 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00009355 switch (Context.getTargetInfo().getInt64Type()) {
9356 default:
9357 llvm_unreachable("Unexpected integer type");
9358 case TargetInfo::SignedLong:
9359 HowLong = 1;
9360 break;
9361 case TargetInfo::SignedLongLong:
9362 HowLong = 2;
9363 break;
9364 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00009365 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009366 }
9367 }
9368
9369 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00009370
Chris Lattnerecd79c62009-06-14 00:45:47 +00009371 // Read the base type.
9372 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00009373 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009374 case 'v':
9375 assert(HowLong == 0 && !Signed && !Unsigned &&
9376 "Bad modifiers used with 'v'!");
9377 Type = Context.VoidTy;
9378 break;
Jack Carter24bef982013-08-15 15:16:57 +00009379 case 'h':
9380 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00009381 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00009382 Type = Context.HalfTy;
9383 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009384 case 'f':
9385 assert(HowLong == 0 && !Signed && !Unsigned &&
9386 "Bad modifiers used with 'f'!");
9387 Type = Context.FloatTy;
9388 break;
9389 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009390 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00009391 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009392 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00009393 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009394 else if (HowLong == 2)
9395 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009396 else
9397 Type = Context.DoubleTy;
9398 break;
9399 case 's':
9400 assert(HowLong == 0 && "Bad modifiers used with 's'!");
9401 if (Unsigned)
9402 Type = Context.UnsignedShortTy;
9403 else
9404 Type = Context.ShortTy;
9405 break;
9406 case 'i':
9407 if (HowLong == 3)
9408 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9409 else if (HowLong == 2)
9410 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9411 else if (HowLong == 1)
9412 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9413 else
9414 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9415 break;
9416 case 'c':
9417 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9418 if (Signed)
9419 Type = Context.SignedCharTy;
9420 else if (Unsigned)
9421 Type = Context.UnsignedCharTy;
9422 else
9423 Type = Context.CharTy;
9424 break;
9425 case 'b': // boolean
9426 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9427 Type = Context.BoolTy;
9428 break;
9429 case 'z': // size_t.
9430 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9431 Type = Context.getSizeType();
9432 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00009433 case 'w': // wchar_t.
9434 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9435 Type = Context.getWideCharType();
9436 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009437 case 'F':
9438 Type = Context.getCFConstantStringType();
9439 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00009440 case 'G':
9441 Type = Context.getObjCIdType();
9442 break;
9443 case 'H':
9444 Type = Context.getObjCSelType();
9445 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00009446 case 'M':
9447 Type = Context.getObjCSuperType();
9448 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009449 case 'a':
9450 Type = Context.getBuiltinVaListType();
9451 assert(!Type.isNull() && "builtin va list type not initialized!");
9452 break;
9453 case 'A':
9454 // This is a "reference" to a va_list; however, what exactly
9455 // this means depends on how va_list is defined. There are two
9456 // different kinds of va_list: ones passed by value, and ones
9457 // passed by reference. An example of a by-value va_list is
9458 // x86, where va_list is a char*. An example of by-ref va_list
9459 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9460 // we want this argument to be a char*&; for x86-64, we want
9461 // it to be a __va_list_tag*.
9462 Type = Context.getBuiltinVaListType();
9463 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009464 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009465 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009466 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009467 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009468 break;
9469 case 'V': {
9470 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009471 unsigned NumElements = strtoul(Str, &End, 10);
9472 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009473 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009474
Fangrui Song6907ce22018-07-30 19:24:48 +00009475 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009476 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009477 assert(!RequiresICE && "Can't require vector ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009478
Chris Lattnerdc226c22010-10-01 22:42:38 +00009479 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009480 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009481 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009482 break;
9483 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009484 case 'E': {
9485 char *End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009486
Douglas Gregorfed66992012-06-07 18:08:25 +00009487 unsigned NumElements = strtoul(Str, &End, 10);
9488 assert(End != Str && "Missing vector size");
Fangrui Song6907ce22018-07-30 19:24:48 +00009489
Douglas Gregorfed66992012-06-07 18:08:25 +00009490 Str = End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009491
Douglas Gregorfed66992012-06-07 18:08:25 +00009492 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009493 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009494 Type = Context.getExtVectorType(ElementType, NumElements);
Fangrui Song6907ce22018-07-30 19:24:48 +00009495 break;
Douglas Gregorfed66992012-06-07 18:08:25 +00009496 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009497 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009498 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009499 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009500 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009501 Type = Context.getComplexType(ElementType);
9502 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00009503 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009504 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009505 Type = Context.getPointerDiffType();
9506 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009507 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009508 Type = Context.getFILEType();
9509 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009510 Error = ASTContext::GE_Missing_stdio;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009511 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009512 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009513 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009514 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009515 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009516 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009517 else
9518 Type = Context.getjmp_bufType();
9519
Mike Stump2adb4da2009-07-28 23:47:15 +00009520 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009521 Error = ASTContext::GE_Missing_setjmp;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009522 return {};
Mike Stump2adb4da2009-07-28 23:47:15 +00009523 }
9524 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009525 case 'K':
9526 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9527 Type = Context.getucontext_tType();
9528
9529 if (Type.isNull()) {
9530 Error = ASTContext::GE_Missing_ucontext;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009531 return {};
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009532 }
9533 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009534 case 'p':
9535 Type = Context.getProcessIDType();
9536 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009537 }
Mike Stump11289f42009-09-09 15:08:12 +00009538
Chris Lattnerdc226c22010-10-01 22:42:38 +00009539 // If there are modifiers and if we're allowed to parse them, go for it.
9540 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009541 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009542 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009543 default: Done = true; --Str; break;
9544 case '*':
9545 case '&': {
9546 // Both pointers and references can have their pointee types
9547 // qualified with an address space.
9548 char *End;
9549 unsigned AddrSpace = strtoul(Str, &End, 10);
Matt Arsenaultc65f9662018-08-02 12:14:28 +00009550 if (End != Str) {
9551 // Note AddrSpace == 0 is not the same as an unspecified address space.
9552 Type = Context.getAddrSpaceQualType(
9553 Type,
9554 Context.getLangASForBuiltinAddressSpace(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009555 Str = End;
9556 }
9557 if (c == '*')
9558 Type = Context.getPointerType(Type);
9559 else
9560 Type = Context.getLValueReferenceType(Type);
9561 break;
9562 }
9563 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9564 case 'C':
9565 Type = Type.withConst();
9566 break;
9567 case 'D':
9568 Type = Context.getVolatileType(Type);
9569 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009570 case 'R':
9571 Type = Type.withRestrict();
9572 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009573 }
9574 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009575
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009576 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Fangrui Song6907ce22018-07-30 19:24:48 +00009577 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009578
Chris Lattnerecd79c62009-06-14 00:45:47 +00009579 return Type;
9580}
9581
9582/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009583QualType ASTContext::GetBuiltinType(unsigned Id,
9584 GetBuiltinTypeError &Error,
9585 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009586 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00009587 if (TypeStr[0] == '\0') {
9588 Error = GE_Missing_type;
9589 return {};
9590 }
Mike Stump11289f42009-09-09 15:08:12 +00009591
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009592 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009593
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009594 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009595 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009596 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9597 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009598 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009599 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009600
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009601 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009602
Chris Lattnerecd79c62009-06-14 00:45:47 +00009603 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009604 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009605 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009606 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009607
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009608 // If this argument is required to be an IntegerConstantExpression and the
9609 // caller cares, fill in the bitmask we return.
9610 if (RequiresICE && IntegerConstantArgs)
9611 *IntegerConstantArgs |= 1 << ArgTypes.size();
Fangrui Song6907ce22018-07-30 19:24:48 +00009612
Chris Lattnerecd79c62009-06-14 00:45:47 +00009613 // Do array -> pointer decay. The builtin should use the decayed type.
9614 if (Ty->isArrayType())
9615 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009616
Chris Lattnerecd79c62009-06-14 00:45:47 +00009617 ArgTypes.push_back(Ty);
9618 }
9619
David Majnemerba3e5ec2015-03-13 18:26:17 +00009620 if (Id == Builtin::BI__GetExceptionInfo)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009621 return {};
David Majnemerba3e5ec2015-03-13 18:26:17 +00009622
Chris Lattnerecd79c62009-06-14 00:45:47 +00009623 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9624 "'.' should only occur at end of builtin type list!");
9625
Erich Keane881e83d2019-03-04 14:54:52 +00009626 bool Variadic = (TypeStr[0] == '.');
9627
9628 FunctionType::ExtInfo EI(
9629 getDefaultCallingConvention(Variadic, /*IsCXXMethod=*/false));
John McCall991eb4b2010-12-21 00:44:39 +00009630 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9631
John McCall991eb4b2010-12-21 00:44:39 +00009632
Richard Smith836de6b2016-12-19 23:59:34 +00009633 // We really shouldn't be making a no-proto type here.
9634 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00009635 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00009636
John McCalldb40c7f2010-12-14 08:05:40 +00009637 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00009638 EPI.ExtInfo = EI;
9639 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00009640 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9641 EPI.ExceptionSpec.Type =
9642 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00009643
Jordan Rose5c382722013-03-08 21:51:21 +00009644 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009645}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00009646
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009647static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9648 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009649 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009650 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009651
Richard Smithe2467b72017-11-16 23:54:56 +00009652 // Non-user-provided functions get emitted as weak definitions with every
9653 // use, no matter whether they've been explicitly instantiated etc.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009654 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
Richard Smithe2467b72017-11-16 23:54:56 +00009655 if (!MD->isUserProvided())
9656 return GVA_DiscardableODR;
9657
Yaron Keren4cd211b2017-02-22 14:32:39 +00009658 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009659 switch (FD->getTemplateSpecializationKind()) {
9660 case TSK_Undeclared:
9661 case TSK_ExplicitSpecialization:
9662 External = GVA_StrongExternal;
9663 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009664
Rafael Espindola3ae00052013-05-13 00:12:11 +00009665 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009666 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009667
David Majnemerc3d07332014-05-15 06:25:57 +00009668 // C++11 [temp.explicit]p10:
9669 // [ Note: The intent is that an inline function that is the subject of
9670 // an explicit instantiation declaration will still be implicitly
9671 // instantiated when used so that the body can be considered for
9672 // inlining, but that no out-of-line copy of the inline function would be
9673 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00009674 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00009675 return GVA_AvailableExternally;
9676
Rafael Espindola3ae00052013-05-13 00:12:11 +00009677 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009678 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009679 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009680 }
9681
9682 if (!FD->isInlined())
9683 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00009684
David Majnemer3f021502015-10-08 04:53:31 +00009685 if ((!Context.getLangOpts().CPlusPlus &&
9686 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009687 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00009688 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009689 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9690
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009691 // GNU or C99 inline semantics. Determine whether this symbol should be
9692 // externally visible.
9693 if (FD->isInlineDefinitionExternallyVisible())
9694 return External;
9695
9696 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00009697 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009698 }
9699
David Majnemer54e3ba52014-04-02 23:17:29 +00009700 // Functions specified with extern and inline in -fms-compatibility mode
9701 // forcibly get emitted. While the body of the function cannot be later
9702 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00009703 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00009704 return GVA_StrongODR;
9705
David Majnemer27d69db2014-04-28 22:17:59 +00009706 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009707}
9708
Artem Belevichca2b9512016-05-02 20:30:03 +00009709static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00009710 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009711 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9712 // dllexport/dllimport on inline functions.
9713 if (D->hasAttr<DLLImportAttr>()) {
9714 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9715 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00009716 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009717 if (L == GVA_DiscardableODR)
9718 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00009719 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9720 D->hasAttr<CUDAGlobalAttr>()) {
9721 // Device-side functions with __global__ attribute must always be
9722 // visible externally so they can be launched from host.
9723 if (L == GVA_DiscardableODR || L == GVA_Internal)
9724 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009725 }
9726 return L;
9727}
9728
Richard Smitha4653622017-09-06 20:01:14 +00009729/// Adjust the GVALinkage for a declaration based on what an external AST source
9730/// knows about whether there can be other definitions of this declaration.
9731static GVALinkage
9732adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9733 GVALinkage L) {
9734 ExternalASTSource *Source = Ctx.getExternalSource();
9735 if (!Source)
9736 return L;
9737
9738 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00009739 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00009740 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009741 if (L == GVA_DiscardableODR)
9742 return GVA_StrongODR;
9743 break;
Richard Smitha4653622017-09-06 20:01:14 +00009744
David Blaikie9ffe5a32017-01-30 05:00:26 +00009745 case ExternalASTSource::EK_Always:
9746 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00009747
David Blaikie9ffe5a32017-01-30 05:00:26 +00009748 case ExternalASTSource::EK_ReplyHazy:
9749 break;
9750 }
9751 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009752}
9753
Richard Smitha4653622017-09-06 20:01:14 +00009754GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9755 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9756 adjustGVALinkageForAttributes(*this, FD,
9757 basicGVALinkageForFunction(*this, FD)));
9758}
9759
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009760static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9761 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009762 if (!VD->isExternallyVisible())
9763 return GVA_Internal;
9764
David Majnemer27d69db2014-04-28 22:17:59 +00009765 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00009766 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9767 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9768 LexicalContext = LexicalContext->getLexicalParent();
9769
David Blaikieeb210012017-01-27 23:11:10 +00009770 // ObjC Blocks can create local variables that don't have a FunctionDecl
9771 // LexicalContext.
9772 if (!LexicalContext)
9773 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00009774
David Blaikieeb210012017-01-27 23:11:10 +00009775 // Otherwise, let the static local variable inherit its linkage from the
9776 // nearest enclosing function.
9777 auto StaticLocalLinkage =
9778 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9779
9780 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9781 // be emitted in any object with references to the symbol for the object it
9782 // contains, whether inline or out-of-line."
9783 // Similar behavior is observed with MSVC. An alternative ABI could use
9784 // StrongODR/AvailableExternally to match the function, but none are
9785 // known/supported currently.
9786 if (StaticLocalLinkage == GVA_StrongODR ||
9787 StaticLocalLinkage == GVA_AvailableExternally)
9788 return GVA_DiscardableODR;
9789 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009790 }
9791
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009792 // MSVC treats in-class initialized static data members as definitions.
9793 // By giving them non-strong linkage, out-of-line definitions won't
9794 // cause link errors.
9795 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9796 return GVA_DiscardableODR;
9797
Richard Smithd9b90092016-07-02 01:32:16 +00009798 // Most non-template variables have strong linkage; inline variables are
9799 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9800 GVALinkage StrongLinkage;
9801 switch (Context.getInlineVariableDefinitionKind(VD)) {
9802 case ASTContext::InlineVariableDefinitionKind::None:
9803 StrongLinkage = GVA_StrongExternal;
9804 break;
9805 case ASTContext::InlineVariableDefinitionKind::Weak:
9806 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009807 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009808 break;
9809 case ASTContext::InlineVariableDefinitionKind::Strong:
9810 StrongLinkage = GVA_StrongODR;
9811 break;
9812 }
Richard Smith62f19e72016-06-25 00:15:56 +00009813
Richard Smith8809a0c2013-09-27 20:14:12 +00009814 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009815 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009816 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009817
David Majnemer6d1780c2015-07-17 23:36:49 +00009818 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00009819 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9820 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00009821 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00009822 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009823
Rafael Espindola3ae00052013-05-13 00:12:11 +00009824 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009825 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009826
David Majnemer27d69db2014-04-28 22:17:59 +00009827 case TSK_ExplicitInstantiationDeclaration:
9828 return GVA_AvailableExternally;
9829
Rafael Espindola3ae00052013-05-13 00:12:11 +00009830 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009831 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009832 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009833
9834 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009835}
9836
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009837GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009838 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9839 adjustGVALinkageForAttributes(*this, VD,
9840 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009841}
9842
David Blaikiee6b7c282017-04-11 20:46:34 +00009843bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009844 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009845 if (!VD->isFileVarDecl())
9846 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009847 // Global named register variables (GNU extension) are never emitted.
9848 if (VD->getStorageClass() == SC_Register)
9849 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009850 if (VD->getDescribedVarTemplate() ||
9851 isa<VarTemplatePartialSpecializationDecl>(VD))
9852 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009853 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Smith5205a8c2013-04-01 20:22:16 +00009854 // We never need to emit an uninstantiated function template.
9855 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9856 return false;
Nico Weber66220292016-03-02 17:28:48 +00009857 } else if (isa<PragmaCommentDecl>(D))
9858 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009859 else if (isa<PragmaDetectMismatchDecl>(D))
9860 return true;
Nico Weber66220292016-03-02 17:28:48 +00009861 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009862 return !D->getDeclContext()->isDependentContext();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009863 else if (isa<OMPAllocateDecl>(D))
9864 return !D->getDeclContext()->isDependentContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009865 else if (isa<OMPDeclareReductionDecl>(D))
9866 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009867 else if (isa<ImportDecl>(D))
9868 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009869 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009870 return false;
9871
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009872 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
9873 assert(getExternalSource() && "It's from an AST file; must have a source.");
9874 // On Windows, PCH files are built together with an object file. If this
9875 // declaration comes from such a PCH and DeclMustBeEmitted would return
9876 // true, it would have returned true and the decl would have been emitted
9877 // into that object file, so it doesn't need to be emitted here.
9878 // Note that decls are still emitted if they're referenced, as usual;
9879 // DeclMustBeEmitted is used to decide whether a decl must be emitted even
9880 // if it's not referenced.
9881 //
9882 // Explicit template instantiation definitions are tricky. If there was an
9883 // explicit template instantiation decl in the PCH before, it will look like
9884 // the definition comes from there, even if that was just the declaration.
9885 // (Explicit instantiation defs of variable templates always get emitted.)
9886 bool IsExpInstDef =
9887 isa<FunctionDecl>(D) &&
9888 cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
9889 TSK_ExplicitInstantiationDefinition;
9890
Hans Wennborgb51a7032018-09-14 15:18:30 +00009891 // Implicit member function definitions, such as operator= might not be
9892 // marked as template specializations, since they're not coming from a
9893 // template but synthesized directly on the class.
9894 IsExpInstDef |=
9895 isa<CXXMethodDecl>(D) &&
9896 cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
9897 TSK_ExplicitInstantiationDefinition;
9898
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009899 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
9900 return false;
9901 }
9902
Richard Smith5205a8c2013-04-01 20:22:16 +00009903 // If this is a member of a class template, we do not need to emit it.
9904 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009905 return false;
9906
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009907 // Weak references don't produce any output by themselves.
9908 if (D->hasAttr<WeakRefAttr>())
9909 return false;
9910
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009911 // Aliases and used decls are required.
9912 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9913 return true;
9914
Eugene Zelenko7855e772018-04-03 00:11:50 +00009915 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009916 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009917 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009918 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009919
9920 // Constructors and destructors are required.
9921 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9922 return true;
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009923
John McCall6bd2a892013-01-25 22:31:03 +00009924 // The key function for a class is required. This rule only comes
9925 // into play when inline functions can be key functions, though.
9926 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009927 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
John McCall6bd2a892013-01-25 22:31:03 +00009928 const CXXRecordDecl *RD = MD->getParent();
9929 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9930 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9931 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9932 return true;
9933 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009934 }
9935 }
9936
David Blaikie9ffe5a32017-01-30 05:00:26 +00009937 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9938
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009939 // static, static inline, always_inline, and extern inline functions can
9940 // always be deferred. Normal inline functions can be deferred in C99/C++.
9941 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009942 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009943 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009944
Eugene Zelenko7855e772018-04-03 00:11:50 +00009945 const auto *VD = cast<VarDecl>(D);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009946 assert(VD->isFileVarDecl() && "Expected file scoped var");
9947
Alexey Bataevd01b7492018-08-15 19:45:12 +00009948 // If the decl is marked as `declare target to`, it should be emitted for the
9949 // host and for the device.
9950 if (LangOpts.OpenMP &&
9951 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
9952 return true;
9953
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009954 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9955 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009956 return false;
9957
Richard Smitha0e5e542012-11-12 21:38:00 +00009958 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +00009959 auto Linkage = GetGVALinkageForVariable(VD);
9960 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +00009961 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009962
Richard Smitha4653622017-09-06 20:01:14 +00009963 // We never need to emit a variable that is available in another TU.
9964 if (Linkage == GVA_AvailableExternally)
9965 return false;
9966
Richard Smitha0e5e542012-11-12 21:38:00 +00009967 // Variables that have destruction with side-effects are required.
9968 if (VD->getType().isDestructedType())
9969 return true;
9970
9971 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009972 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009973 // We can get a value-dependent initializer during error recovery.
9974 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009975 return true;
9976
Richard Smithda383632016-08-15 01:33:41 +00009977 // Likewise, variables with tuple-like bindings are required if their
9978 // bindings have side-effects.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009979 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
9980 for (const auto *BD : DD->bindings())
9981 if (const auto *BindingVD = BD->getHoldingVar())
Richard Smithda383632016-08-15 01:33:41 +00009982 if (DeclMustBeEmitted(BindingVD))
9983 return true;
9984
Richard Smitha0e5e542012-11-12 21:38:00 +00009985 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009986}
Charles Davis53c59df2010-08-16 03:33:14 +00009987
Erich Keane281d20b2018-01-08 21:34:17 +00009988void ASTContext::forEachMultiversionedFunctionVersion(
9989 const FunctionDecl *FD,
Erich Keane0fb16482018-08-13 18:33:20 +00009990 llvm::function_ref<void(FunctionDecl *)> Pred) const {
Erich Keane281d20b2018-01-08 21:34:17 +00009991 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
9992 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
Erich Keane7304f0a2018-11-28 20:58:43 +00009993 FD = FD->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +00009994 for (auto *CurDecl :
9995 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
Erich Keane7304f0a2018-11-28 20:58:43 +00009996 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +00009997 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
9998 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
9999 SeenDecls.insert(CurFD);
10000 Pred(CurFD);
10001 }
10002 }
10003}
10004
Reid Kleckner78af0702013-08-27 23:08:25 +000010005CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
10006 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +000010007 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +000010008 if (IsCXXMethod)
10009 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +000010010
Alexey Bataeva7547182016-05-18 09:06:38 +000010011 switch (LangOpts.getDefaultCallingConv()) {
10012 case LangOptions::DCC_None:
10013 break;
10014 case LangOptions::DCC_CDecl:
10015 return CC_C;
10016 case LangOptions::DCC_FastCall:
Erich Keane5759fa72017-10-24 23:12:01 +000010017 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
Alexey Bataeva7547182016-05-18 09:06:38 +000010018 return CC_X86FastCall;
10019 break;
10020 case LangOptions::DCC_StdCall:
10021 if (!IsVariadic)
10022 return CC_X86StdCall;
10023 break;
10024 case LangOptions::DCC_VectorCall:
10025 // __vectorcall cannot be applied to variadic functions.
10026 if (!IsVariadic)
10027 return CC_X86VectorCall;
10028 break;
Erich Keanea957ffb2017-11-02 21:08:00 +000010029 case LangOptions::DCC_RegCall:
10030 // __regcall cannot be applied to variadic functions.
10031 if (!IsVariadic)
10032 return CC_X86RegCall;
10033 break;
Alexey Bataeva7547182016-05-18 09:06:38 +000010034 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000010035 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +000010036}
10037
Jay Foad39c79802011-01-12 09:06:06 +000010038bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +000010039 // Pass through to the C++ ABI object
10040 return ABI->isNearlyEmpty(RD);
10041}
10042
Reid Kleckner96f8f932014-02-05 17:27:08 +000010043VTableContextBase *ASTContext::getVTableContext() {
10044 if (!VTContext.get()) {
10045 if (Target->getCXXABI().isMicrosoft())
10046 VTContext.reset(new MicrosoftVTableContext(*this));
10047 else
10048 VTContext.reset(new ItaniumVTableContext(*this));
10049 }
10050 return VTContext.get();
10051}
10052
Yaxun Liuc18e9ec2019-02-14 02:00:09 +000010053MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
10054 if (!T)
10055 T = Target;
10056 switch (T->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000010057 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +000010058 case TargetCXXABI::GenericItanium:
10059 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +000010060 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +000010061 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000010062 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +000010063 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +000010064 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010065 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +000010066 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010067 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010068 }
David Blaikie83d382b2011-09-23 05:06:16 +000010069 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010070}
10071
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010072CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010073
10074size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +000010075 return ASTRecordLayouts.getMemorySize() +
10076 llvm::capacity_in_bytes(ObjCLayouts) +
10077 llvm::capacity_in_bytes(KeyFunctions) +
10078 llvm::capacity_in_bytes(ObjCImpls) +
10079 llvm::capacity_in_bytes(BlockVarCopyInits) +
10080 llvm::capacity_in_bytes(DeclAttrs) +
10081 llvm::capacity_in_bytes(TemplateOrInstantiation) +
10082 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10083 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10084 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10085 llvm::capacity_in_bytes(OverriddenMethods) +
10086 llvm::capacity_in_bytes(Types) +
Richard Smithf19a8b02019-05-02 00:49:14 +000010087 llvm::capacity_in_bytes(VariableArrayTypes);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010088}
Ted Kremenek540017e2011-10-06 05:00:56 +000010089
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010090/// getIntTypeForBitwidth -
10091/// sets integer QualTy according to specified details:
10092/// bitwidth, signed/unsigned.
10093/// Returns empty type if there is no appropriate target types.
10094QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
10095 unsigned Signed) const {
10096 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10097 CanQualType QualTy = getFromTargetType(Ty);
10098 if (!QualTy && DestWidth == 128)
10099 return Signed ? Int128Ty : UnsignedInt128Ty;
10100 return QualTy;
10101}
10102
10103/// getRealTypeForBitwidth -
10104/// sets floating point QualTy according to specified bitwidth.
10105/// Returns empty type if there is no appropriate target types.
10106QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
10107 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
10108 switch (Ty) {
10109 case TargetInfo::Float:
10110 return FloatTy;
10111 case TargetInfo::Double:
10112 return DoubleTy;
10113 case TargetInfo::LongDouble:
10114 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000010115 case TargetInfo::Float128:
10116 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010117 case TargetInfo::NoFloat:
Eugene Zelenko7855e772018-04-03 00:11:50 +000010118 return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010119 }
10120
10121 llvm_unreachable("Unhandled TargetInfo::RealType value");
10122}
10123
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010124void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10125 if (Number > 1)
10126 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +000010127}
10128
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010129unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010130 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010131 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +000010132}
10133
David Majnemer2206bf52014-03-05 08:57:59 +000010134void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10135 if (Number > 1)
10136 StaticLocalNumbers[VD] = Number;
10137}
10138
10139unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010140 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +000010141 return I != StaticLocalNumbers.end() ? I->second : 1;
10142}
10143
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010144MangleNumberingContext &
10145ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010146 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +000010147 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +000010148 if (!MCtx)
10149 MCtx = createMangleNumberingContext();
10150 return *MCtx;
10151}
10152
Justin Lebar20ebffc2016-10-10 16:26:19 +000010153std::unique_ptr<MangleNumberingContext>
10154ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010155 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +000010156}
10157
David Majnemere7a818f2015-03-06 18:53:55 +000010158const CXXConstructorDecl *
10159ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
10160 return ABI->getCopyConstructorForExceptionObject(
10161 cast<CXXRecordDecl>(RD->getFirstDecl()));
10162}
10163
10164void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
10165 CXXConstructorDecl *CD) {
10166 return ABI->addCopyConstructorForExceptionObject(
10167 cast<CXXRecordDecl>(RD->getFirstDecl()),
10168 cast<CXXConstructorDecl>(CD->getFirstDecl()));
10169}
10170
David Majnemer00350522015-08-31 18:48:39 +000010171void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10172 TypedefNameDecl *DD) {
10173 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10174}
10175
10176TypedefNameDecl *
10177ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10178 return ABI->getTypedefNameForUnnamedTagDecl(TD);
10179}
10180
10181void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10182 DeclaratorDecl *DD) {
10183 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10184}
10185
10186DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10187 return ABI->getDeclaratorForUnnamedTagDecl(TD);
10188}
10189
Ted Kremenek540017e2011-10-06 05:00:56 +000010190void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10191 ParamIndices[D] = index;
10192}
10193
10194unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10195 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
Fangrui Song6907ce22018-07-30 19:24:48 +000010196 assert(I != ParamIndices.end() &&
Ted Kremenek540017e2011-10-06 05:00:56 +000010197 "ParmIndices lacks entry set by ParmVarDecl");
10198 return I->second;
10199}
Fariborz Jahanian615de762013-05-28 17:37:39 +000010200
Richard Smithe6c01442013-06-05 00:46:14 +000010201APValue *
10202ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
10203 bool MayCreate) {
10204 assert(E && E->getStorageDuration() == SD_Static &&
10205 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +000010206 if (MayCreate) {
10207 APValue *&MTVI = MaterializedTemporaryValues[E];
10208 if (!MTVI)
10209 MTVI = new (*this) APValue;
10210 return MTVI;
10211 }
Richard Smithe6c01442013-06-05 00:46:14 +000010212
David Majnemer2dcef9e2015-08-13 23:50:15 +000010213 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +000010214}
10215
Fariborz Jahanian615de762013-05-28 17:37:39 +000010216bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10217 const llvm::Triple &T = getTargetInfo().getTriple();
10218 if (!T.isOSDarwin())
10219 return false;
10220
Bob Wilson2c82c3d2013-11-02 23:27:49 +000010221 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10222 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10223 return false;
10224
Fariborz Jahanian615de762013-05-28 17:37:39 +000010225 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10226 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10227 uint64_t Size = sizeChars.getQuantity();
10228 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10229 unsigned Align = alignChars.getQuantity();
10230 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10231 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10232}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010233
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010234/// Template specializations to abstract away from pointers and TypeLocs.
10235/// @{
10236template <typename T>
Sam McCall814e7972018-11-14 10:33:30 +000010237static ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010238 return ast_type_traits::DynTypedNode::create(*Node);
10239}
10240template <>
10241ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
10242 return ast_type_traits::DynTypedNode::create(Node);
10243}
10244template <>
10245ast_type_traits::DynTypedNode
10246createDynTypedNode(const NestedNameSpecifierLoc &Node) {
10247 return ast_type_traits::DynTypedNode::create(Node);
10248}
10249/// @}
10250
Sam McCall814e7972018-11-14 10:33:30 +000010251/// A \c RecursiveASTVisitor that builds a map from nodes to their
10252/// parents as defined by the \c RecursiveASTVisitor.
10253///
10254/// Note that the relationship described here is purely in terms of AST
10255/// traversal - there are other relationships (for example declaration context)
10256/// in the AST that are better modeled by special matchers.
10257///
10258/// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
10259class ASTContext::ParentMap::ASTVisitor
10260 : public RecursiveASTVisitor<ASTVisitor> {
10261public:
10262 ASTVisitor(ParentMap &Map) : Map(Map) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010263
Sam McCall814e7972018-11-14 10:33:30 +000010264private:
10265 friend class RecursiveASTVisitor<ASTVisitor>;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010266
Sam McCall814e7972018-11-14 10:33:30 +000010267 using VisitorBase = RecursiveASTVisitor<ASTVisitor>;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010268
Sam McCall814e7972018-11-14 10:33:30 +000010269 bool shouldVisitTemplateInstantiations() const { return true; }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010270
Sam McCall814e7972018-11-14 10:33:30 +000010271 bool shouldVisitImplicitCode() const { return true; }
10272
10273 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
10274 typename MapTy>
10275 bool TraverseNode(T Node, MapNodeTy MapNode, BaseTraverseFn BaseTraverse,
10276 MapTy *Parents) {
10277 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010278 return true;
Sam McCall814e7972018-11-14 10:33:30 +000010279 if (ParentStack.size() > 0) {
10280 // FIXME: Currently we add the same parent multiple times, but only
10281 // when no memoization data is available for the type.
10282 // For example when we visit all subexpressions of template
10283 // instantiations; this is suboptimal, but benign: the only way to
10284 // visit those is with hasAncestor / hasParent, and those do not create
10285 // new matches.
10286 // The plan is to enable DynTypedNode to be storable in a map or hash
10287 // map. The main problem there is to implement hash functions /
10288 // comparison operators for all types that DynTypedNode supports that
10289 // do not have pointer identity.
10290 auto &NodeOrVector = (*Parents)[MapNode];
10291 if (NodeOrVector.isNull()) {
10292 if (const auto *D = ParentStack.back().get<Decl>())
10293 NodeOrVector = D;
10294 else if (const auto *S = ParentStack.back().get<Stmt>())
10295 NodeOrVector = S;
10296 else
10297 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
10298 } else {
10299 if (!NodeOrVector.template is<ParentVector *>()) {
10300 auto *Vector = new ParentVector(
10301 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
10302 delete NodeOrVector
10303 .template dyn_cast<ast_type_traits::DynTypedNode *>();
10304 NodeOrVector = Vector;
Manuel Klimek95403e62014-05-21 13:28:59 +000010305 }
Sam McCall814e7972018-11-14 10:33:30 +000010306
10307 auto *Vector = NodeOrVector.template get<ParentVector *>();
10308 // Skip duplicates for types that have memoization data.
10309 // We must check that the type has memoization data before calling
10310 // std::find() because DynTypedNode::operator== can't compare all
10311 // types.
10312 bool Found = ParentStack.back().getMemoizationData() &&
10313 std::find(Vector->begin(), Vector->end(),
10314 ParentStack.back()) != Vector->end();
10315 if (!Found)
10316 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +000010317 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010318 }
Sam McCall814e7972018-11-14 10:33:30 +000010319 ParentStack.push_back(createDynTypedNode(Node));
10320 bool Result = BaseTraverse();
10321 ParentStack.pop_back();
10322 return Result;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010323 }
Sam McCall814e7972018-11-14 10:33:30 +000010324
10325 bool TraverseDecl(Decl *DeclNode) {
10326 return TraverseNode(
10327 DeclNode, DeclNode, [&] { return VisitorBase::TraverseDecl(DeclNode); },
10328 &Map.PointerParents);
Manuel Klimek95403e62014-05-21 13:28:59 +000010329 }
Sam McCall814e7972018-11-14 10:33:30 +000010330
10331 bool TraverseStmt(Stmt *StmtNode) {
10332 return TraverseNode(
10333 StmtNode, StmtNode, [&] { return VisitorBase::TraverseStmt(StmtNode); },
10334 &Map.PointerParents);
10335 }
10336
10337 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
10338 return TraverseNode(
10339 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
10340 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
10341 &Map.OtherParents);
10342 }
10343
10344 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
10345 return TraverseNode(
10346 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
10347 [&] { return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); },
10348 &Map.OtherParents);
10349 }
10350
10351 ParentMap &Map;
10352 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
10353};
10354
10355ASTContext::ParentMap::ParentMap(ASTContext &Ctx) {
10356 ASTVisitor(*this).TraverseAST(Ctx);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010357}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010358
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010359ASTContext::DynTypedNodeList
10360ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
Sam McCall814e7972018-11-14 10:33:30 +000010361 if (!Parents)
10362 // We build the parent map for the traversal scope (usually whole TU), as
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010363 // hasAncestor can escape any subtree.
Sam McCall814e7972018-11-14 10:33:30 +000010364 Parents = llvm::make_unique<ParentMap>(*this);
10365 return Parents->getParents(Node);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010366}
10367
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010368bool
10369ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10370 const ObjCMethodDecl *MethodImpl) {
10371 // No point trying to match an unavailable/deprecated mothod.
10372 if (MethodDecl->hasAttr<UnavailableAttr>()
10373 || MethodDecl->hasAttr<DeprecatedAttr>())
10374 return false;
10375 if (MethodDecl->getObjCDeclQualifier() !=
10376 MethodImpl->getObjCDeclQualifier())
10377 return false;
Alp Toker314cc812014-01-25 16:55:45 +000010378 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010379 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010380
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010381 if (MethodDecl->param_size() != MethodImpl->param_size())
10382 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010383
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010384 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10385 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10386 EF = MethodDecl->param_end();
10387 IM != EM && IF != EF; ++IM, ++IF) {
10388 const ParmVarDecl *DeclVar = (*IF);
10389 const ParmVarDecl *ImplVar = (*IM);
10390 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10391 return false;
10392 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10393 return false;
10394 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010395
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010396 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010397}
Richard Smith053f6c62014-05-16 23:01:30 +000010398
Yaxun Liu402804b2016-12-15 08:09:08 +000010399uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +000010400 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +000010401 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +000010402 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +000010403 else
10404 AS = QT->getPointeeType().getAddressSpace();
10405
10406 return getTargetInfo().getNullPointerValue(AS);
10407}
10408
Alexander Richardson6d989432017-10-15 18:48:14 +000010409unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10410 if (isTargetAddressSpace(AS))
10411 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +000010412 else
Alexander Richardson6d989432017-10-15 18:48:14 +000010413 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +000010414}
10415
Leonard Chanab80f3c2018-06-14 14:53:51 +000010416QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
10417 assert(Ty->isFixedPointType());
10418
10419 if (Ty->isSaturatedFixedPointType()) return Ty;
10420
10421 const auto &BT = Ty->getAs<BuiltinType>();
10422 switch (BT->getKind()) {
10423 default:
10424 llvm_unreachable("Not a fixed point type!");
10425 case BuiltinType::ShortAccum:
10426 return SatShortAccumTy;
10427 case BuiltinType::Accum:
10428 return SatAccumTy;
10429 case BuiltinType::LongAccum:
10430 return SatLongAccumTy;
10431 case BuiltinType::UShortAccum:
10432 return SatUnsignedShortAccumTy;
10433 case BuiltinType::UAccum:
10434 return SatUnsignedAccumTy;
10435 case BuiltinType::ULongAccum:
10436 return SatUnsignedLongAccumTy;
10437 case BuiltinType::ShortFract:
10438 return SatShortFractTy;
10439 case BuiltinType::Fract:
10440 return SatFractTy;
10441 case BuiltinType::LongFract:
10442 return SatLongFractTy;
10443 case BuiltinType::UShortFract:
10444 return SatUnsignedShortFractTy;
10445 case BuiltinType::UFract:
10446 return SatUnsignedFractTy;
10447 case BuiltinType::ULongFract:
10448 return SatUnsignedLongFractTy;
10449 }
10450}
10451
Matt Arsenaultc65f9662018-08-02 12:14:28 +000010452LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
10453 if (LangOpts.OpenCL)
10454 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
10455
10456 if (LangOpts.CUDA)
10457 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
10458
10459 return getLangASFromTargetAS(AS);
10460}
10461
Richard Smith053f6c62014-05-16 23:01:30 +000010462// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10463// doesn't include ASTContext.h
10464template
10465clang::LazyGenerationalUpdatePtr<
10466 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10467clang::LazyGenerationalUpdatePtr<
10468 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10469 const clang::ASTContext &Ctx, Decl *Value);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010470
10471unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10472 assert(Ty->isFixedPointType());
10473
10474 const auto *BT = Ty->getAs<BuiltinType>();
10475 const TargetInfo &Target = getTargetInfo();
10476 switch (BT->getKind()) {
10477 default:
10478 llvm_unreachable("Not a fixed point type!");
10479 case BuiltinType::ShortAccum:
10480 case BuiltinType::SatShortAccum:
10481 return Target.getShortAccumScale();
10482 case BuiltinType::Accum:
10483 case BuiltinType::SatAccum:
10484 return Target.getAccumScale();
10485 case BuiltinType::LongAccum:
10486 case BuiltinType::SatLongAccum:
10487 return Target.getLongAccumScale();
10488 case BuiltinType::UShortAccum:
10489 case BuiltinType::SatUShortAccum:
10490 return Target.getUnsignedShortAccumScale();
10491 case BuiltinType::UAccum:
10492 case BuiltinType::SatUAccum:
10493 return Target.getUnsignedAccumScale();
10494 case BuiltinType::ULongAccum:
10495 case BuiltinType::SatULongAccum:
10496 return Target.getUnsignedLongAccumScale();
10497 case BuiltinType::ShortFract:
10498 case BuiltinType::SatShortFract:
10499 return Target.getShortFractScale();
10500 case BuiltinType::Fract:
10501 case BuiltinType::SatFract:
10502 return Target.getFractScale();
10503 case BuiltinType::LongFract:
10504 case BuiltinType::SatLongFract:
10505 return Target.getLongFractScale();
10506 case BuiltinType::UShortFract:
10507 case BuiltinType::SatUShortFract:
10508 return Target.getUnsignedShortFractScale();
10509 case BuiltinType::UFract:
10510 case BuiltinType::SatUFract:
10511 return Target.getUnsignedFractScale();
10512 case BuiltinType::ULongFract:
10513 case BuiltinType::SatULongFract:
10514 return Target.getUnsignedLongFractScale();
10515 }
10516}
10517
10518unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10519 assert(Ty->isFixedPointType());
10520
10521 const auto *BT = Ty->getAs<BuiltinType>();
10522 const TargetInfo &Target = getTargetInfo();
10523 switch (BT->getKind()) {
10524 default:
10525 llvm_unreachable("Not a fixed point type!");
10526 case BuiltinType::ShortAccum:
10527 case BuiltinType::SatShortAccum:
10528 return Target.getShortAccumIBits();
10529 case BuiltinType::Accum:
10530 case BuiltinType::SatAccum:
10531 return Target.getAccumIBits();
10532 case BuiltinType::LongAccum:
10533 case BuiltinType::SatLongAccum:
10534 return Target.getLongAccumIBits();
10535 case BuiltinType::UShortAccum:
10536 case BuiltinType::SatUShortAccum:
10537 return Target.getUnsignedShortAccumIBits();
10538 case BuiltinType::UAccum:
10539 case BuiltinType::SatUAccum:
10540 return Target.getUnsignedAccumIBits();
10541 case BuiltinType::ULongAccum:
10542 case BuiltinType::SatULongAccum:
10543 return Target.getUnsignedLongAccumIBits();
10544 case BuiltinType::ShortFract:
10545 case BuiltinType::SatShortFract:
10546 case BuiltinType::Fract:
10547 case BuiltinType::SatFract:
10548 case BuiltinType::LongFract:
10549 case BuiltinType::SatLongFract:
10550 case BuiltinType::UShortFract:
10551 case BuiltinType::SatUShortFract:
10552 case BuiltinType::UFract:
10553 case BuiltinType::SatUFract:
10554 case BuiltinType::ULongFract:
10555 case BuiltinType::SatULongFract:
10556 return 0;
10557 }
10558}
Leonard Chana6779422018-08-06 16:42:37 +000010559
10560FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
Erich Keane8e772162019-01-18 19:31:54 +000010561 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
10562 "Can only get the fixed point semantics for a "
10563 "fixed point or integer type.");
Leonard Chan2044ac82019-01-16 18:13:59 +000010564 if (Ty->isIntegerType())
10565 return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty),
10566 Ty->isSignedIntegerType());
10567
Leonard Chana6779422018-08-06 16:42:37 +000010568 bool isSigned = Ty->isSignedFixedPointType();
10569 return FixedPointSemantics(
10570 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
10571 Ty->isSaturatedFixedPointType(),
10572 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
10573}
10574
10575APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
10576 assert(Ty->isFixedPointType());
10577 return APFixedPoint::getMax(getFixedPointSemantics(Ty));
10578}
10579
10580APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
10581 assert(Ty->isFixedPointType());
10582 return APFixedPoint::getMin(getFixedPointSemantics(Ty));
10583}
Leonard Chan2044ac82019-01-16 18:13:59 +000010584
10585QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
10586 assert(Ty->isUnsignedFixedPointType() &&
10587 "Expected unsigned fixed point type");
10588 const auto *BTy = Ty->getAs<BuiltinType>();
10589
10590 switch (BTy->getKind()) {
10591 case BuiltinType::UShortAccum:
10592 return ShortAccumTy;
10593 case BuiltinType::UAccum:
10594 return AccumTy;
10595 case BuiltinType::ULongAccum:
10596 return LongAccumTy;
10597 case BuiltinType::SatUShortAccum:
10598 return SatShortAccumTy;
10599 case BuiltinType::SatUAccum:
10600 return SatAccumTy;
10601 case BuiltinType::SatULongAccum:
10602 return SatLongAccumTy;
10603 case BuiltinType::UShortFract:
10604 return ShortFractTy;
10605 case BuiltinType::UFract:
10606 return FractTy;
10607 case BuiltinType::ULongFract:
10608 return LongFractTy;
10609 case BuiltinType::SatUShortFract:
10610 return SatShortFractTy;
10611 case BuiltinType::SatUFract:
10612 return SatFractTy;
10613 case BuiltinType::SatULongFract:
10614 return SatLongFractTy;
10615 default:
10616 llvm_unreachable("Unexpected unsigned fixed point type");
10617 }
10618}