blob: be7830640e7e5535401d37ad4351789fb9d7af91 [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;
Fangrui Song7264a472019-07-03 08:13:17 +0000231 assert(Comment ==
232 llvm::lower_bound(RawComments, &CommentAtDeclLoc, Compare));
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000233 } else {
234 // Slow path.
Fangrui Song7264a472019-07-03 08:13:17 +0000235 Comment = llvm::lower_bound(RawComments, &CommentAtDeclLoc, Compare);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000236 }
237 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000238
239 // Decompose the location for the declaration and find the beginning of the
240 // file buffer.
241 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
242
243 // First check whether we have a trailing comment.
244 if (Comment != RawComments.end() &&
David L. Jones13d5a872018-03-02 00:07:45 +0000245 ((*Comment)->isDocumentation() || LangOpts.CommentOpts.ParseAllComments)
246 && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000247 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000248 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000249 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000250 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000251 // Check that Doxygen trailing comment comes after the declaration, starts
252 // on the same line and in the same file as the declaration.
253 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
254 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
255 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
256 CommentBeginDecomp.second)) {
Jan Korous1652d812019-05-13 17:52:09 +0000257 (**Comment).setAttached();
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
Jan Korous1652d812019-05-13 17:52:09 +0000299 (**Comment).setAttached();
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000300 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000301}
302
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000303/// If we have a 'templated' declaration for a template, adjust 'D' to
304/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000305/// If we have an implicit instantiation, adjust 'D' to refer to template.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000306static const Decl *adjustDeclToTemplate(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000307 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000308 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000309 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000310 return FTD;
311
312 // Nothing to do if function is not an implicit instantiation.
313 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
314 return D;
315
316 // Function is an implicit instantiation of a function template?
317 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
318 return FTD;
319
320 // Function is instantiated from a member definition of a class template?
321 if (const FunctionDecl *MemberDecl =
322 FD->getInstantiatedFromMemberFunction())
323 return MemberDecl;
324
325 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000326 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000327 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000328 // Static data member is instantiated from a member definition of a class
329 // template?
330 if (VD->isStaticDataMember())
331 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
332 return MemberDecl;
333
334 return D;
335 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000336 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000337 // Is this class declaration part of a class template?
338 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
339 return CTD;
340
341 // Class is an implicit instantiation of a class template or partial
342 // specialization?
Eugene Zelenko7855e772018-04-03 00:11:50 +0000343 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000344 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
345 return D;
346 llvm::PointerUnion<ClassTemplateDecl *,
347 ClassTemplatePartialSpecializationDecl *>
348 PU = CTSD->getSpecializedTemplateOrPartial();
349 return PU.is<ClassTemplateDecl*>() ?
350 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
351 static_cast<const Decl*>(
352 PU.get<ClassTemplatePartialSpecializationDecl *>());
353 }
354
355 // Class is instantiated from a member definition of a class template?
356 if (const MemberSpecializationInfo *Info =
357 CRD->getMemberSpecializationInfo())
358 return Info->getInstantiatedFrom();
359
360 return D;
361 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000362 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000363 // Enum is instantiated from a member definition of a class template?
364 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
365 return MemberDecl;
366
367 return D;
368 }
369 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000370 return D;
371}
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000372
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000373const RawComment *ASTContext::getRawCommentForAnyRedecl(
374 const Decl *D,
375 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000376 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000377
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000378 // Check whether we have cached a comment for this declaration already.
379 {
380 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
381 RedeclComments.find(D);
382 if (Pos != RedeclComments.end()) {
383 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000384 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
385 if (OriginalDecl)
386 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000387 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000388 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000389 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000390 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000391
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000392 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000393 const RawComment *RC = nullptr;
394 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000395 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000396 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000397 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000398 if (Pos != RedeclComments.end()) {
399 const RawCommentAndCacheFlags &Raw = Pos->second;
400 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
401 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000402 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000403 break;
404 }
405 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000406 RC = getRawCommentForDeclNoCache(I);
407 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000408 RawCommentAndCacheFlags Raw;
409 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000410 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
411 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000412 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000413 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000414 } else
415 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000416 Raw.setOriginalDecl(I);
417 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000418 if (RC)
419 break;
420 }
421 }
422
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000423 // If we found a comment, it should be a documentation comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000424 assert(!RC || RC->isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000425
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000426 if (OriginalDecl)
427 *OriginalDecl = OriginalDeclForRC;
428
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000429 // Update cache for every declaration in the redeclaration chain.
430 RawCommentAndCacheFlags Raw;
431 Raw.setRaw(RC);
432 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000433 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000434
Aaron Ballman86c93902014-03-06 23:45:36 +0000435 for (auto I : D->redecls()) {
436 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000437 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
438 R = Raw;
439 }
440
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000441 return RC;
442}
443
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000444static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
445 SmallVectorImpl<const NamedDecl *> &Redeclared) {
446 const DeclContext *DC = ObjCMethod->getDeclContext();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000447 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000448 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
449 if (!ID)
450 return;
451 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000452 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000453 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000454 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000455 ObjCMethod->isInstanceMethod()))
456 Redeclared.push_back(RedeclaredMethod);
457 }
458 }
459}
460
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000461comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
462 const Decl *D) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000463 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000464 ThisDeclInfo->CommentDecl = D;
465 ThisDeclInfo->IsFilled = false;
466 ThisDeclInfo->fill();
467 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000468 if (!ThisDeclInfo->TemplateParameters)
469 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000470 comments::FullComment *CFC =
471 new (*this) comments::FullComment(FC->getBlocks(),
472 ThisDeclInfo);
473 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000474}
475
Richard Smithb39b9d52013-05-21 05:24:00 +0000476comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
477 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000478 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000479}
480
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000481comments::FullComment *ASTContext::getCommentForDecl(
482 const Decl *D,
483 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000484 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000485 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000486 D = adjustDeclToTemplate(D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000487
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000488 const Decl *Canonical = D->getCanonicalDecl();
489 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
490 ParsedComments.find(Canonical);
Fangrui Song6907ce22018-07-30 19:24:48 +0000491
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000492 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000493 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000494 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000495 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000496 return CFC;
497 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000498 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000499 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000500
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000501 const Decl *OriginalDecl;
Fangrui Song6907ce22018-07-30 19:24:48 +0000502
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000503 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000504 if (!RC) {
505 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000506 SmallVector<const NamedDecl*, 8> Overridden;
Eugene Zelenko7855e772018-04-03 00:11:50 +0000507 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000508 if (OMD && OMD->isPropertyAccessor())
509 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
510 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
511 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000512 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000513 addRedeclaredMethods(OMD, Overridden);
514 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000515 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
516 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
517 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000518 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000519 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000520 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000521 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000522 QualType QT = TD->getUnderlyingType();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000523 if (const auto *TT = QT->getAs<TagType>())
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000524 if (const Decl *TD = TT->getDecl())
525 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000526 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000527 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000528 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000529 while (IC->getSuperClass()) {
530 IC = IC->getSuperClass();
531 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
532 return cloneFullComment(FC, D);
533 }
534 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000535 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000536 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
537 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
538 return cloneFullComment(FC, D);
539 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000540 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000541 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000542 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000543 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000544 for (const auto &I : RD->bases()) {
545 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000546 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000547 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000548 if (Ty.isNull())
549 continue;
550 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
551 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
552 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000553
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000554 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
555 return cloneFullComment(FC, D);
556 }
557 }
558 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000559 for (const auto &I : RD->vbases()) {
560 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000561 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000562 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000563 if (Ty.isNull())
564 continue;
565 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
566 if (!(VirtualBase= VirtualBase->getDefinition()))
567 continue;
568 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
569 return cloneFullComment(FC, D);
570 }
571 }
572 }
Craig Topper36250ad2014-05-12 05:36:57 +0000573 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000574 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000575
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000576 // If the RawComment was attached to other redeclaration of this Decl, we
577 // should parse the comment in context of that other Decl. This is important
578 // because comments can contain references to parameter names which can be
579 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000580 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000581 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000582
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000583 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000584 ParsedComments[Canonical] = FC;
585 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000586}
587
Fangrui Song6907ce22018-07-30 19:24:48 +0000588void
589ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000590 TemplateTemplateParmDecl *Parm) {
591 ID.AddInteger(Parm->getDepth());
592 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000593 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000594
595 TemplateParameterList *Params = Parm->getTemplateParameters();
596 ID.AddInteger(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000597 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000598 PEnd = Params->end();
599 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000600 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000601 ID.AddInteger(0);
602 ID.AddBoolean(TTP->isParameterPack());
603 continue;
604 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000605
Eugene Zelenko7855e772018-04-03 00:11:50 +0000606 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000607 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000608 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000609 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000610 if (NTTP->isExpandedParameterPack()) {
611 ID.AddBoolean(true);
612 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000613 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
614 QualType T = NTTP->getExpansionType(I);
615 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
616 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000617 } else
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000618 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000619 continue;
620 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000621
Eugene Zelenko7855e772018-04-03 00:11:50 +0000622 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000623 ID.AddInteger(2);
624 Profile(ID, TTP);
625 }
626}
627
628TemplateTemplateParmDecl *
629ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000630 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000631 // Check if we already have a canonical template template parameter.
632 llvm::FoldingSetNodeID ID;
633 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000634 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000635 CanonicalTemplateTemplateParm *Canonical
636 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
637 if (Canonical)
638 return Canonical->getParam();
Fangrui Song6907ce22018-07-30 19:24:48 +0000639
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000640 // Build a canonical template parameter list.
641 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000642 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000643 CanonParams.reserve(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000644 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000645 PEnd = Params->end();
646 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000647 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000648 CanonParams.push_back(
Fangrui Song6907ce22018-07-30 19:24:48 +0000649 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000650 SourceLocation(),
651 SourceLocation(),
652 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000653 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000654 TTP->isParameterPack()));
Eugene Zelenko7855e772018-04-03 00:11:50 +0000655 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000656 QualType T = getCanonicalType(NTTP->getType());
657 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
658 NonTypeTemplateParmDecl *Param;
659 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000660 SmallVector<QualType, 2> ExpandedTypes;
661 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000662 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
663 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
664 ExpandedTInfos.push_back(
665 getTrivialTypeSourceInfo(ExpandedTypes.back()));
666 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000667
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000668 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000669 SourceLocation(),
670 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000671 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000672 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000673 T,
674 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000675 ExpandedTypes,
676 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000677 } else {
678 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000679 SourceLocation(),
680 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000681 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000682 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000683 T,
684 NTTP->isParameterPack(),
685 TInfo);
686 }
687 CanonParams.push_back(Param);
688
689 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000690 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
691 cast<TemplateTemplateParmDecl>(*P)));
692 }
693
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000694 assert(!TTP->getRequiresClause() &&
695 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000696 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000697
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000698 TemplateTemplateParmDecl *CanonTTP
Fangrui Song6907ce22018-07-30 19:24:48 +0000699 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000700 SourceLocation(), TTP->getDepth(),
Fangrui Song6907ce22018-07-30 19:24:48 +0000701 TTP->getPosition(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000702 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000703 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000704 TemplateParameterList::Create(*this, SourceLocation(),
705 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000706 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000707 SourceLocation(),
708 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000709
710 // Get the new insert position for the node we care about.
711 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000712 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000713 (void)Canonical;
714
715 // Create the canonical template template parameter entry.
716 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
717 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
718 return CanonTTP;
719}
720
Charles Davis53c59df2010-08-16 03:33:14 +0000721CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000722 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000723
John McCall359b8852013-01-25 22:30:49 +0000724 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000725 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000726 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000727 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000728 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000729 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000730 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000731 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000732 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000733 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000734 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000735 return CreateMicrosoftCXXABI(*this);
736 }
David Blaikie8a40f702012-01-17 06:56:22 +0000737 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000738}
739
Alexander Richardson6d989432017-10-15 18:48:14 +0000740static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
741 const LangOptions &LOpts) {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000742 if (LOpts.FakeAddressSpaceMap) {
743 // The fake address space map must have a distinct entry for each
744 // language-specific address space.
745 static const unsigned FakeAddrSpaceMap[] = {
Yaxun Liub34ec822017-04-11 17:24:23 +0000746 0, // Default
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000747 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000748 3, // opencl_local
749 2, // opencl_constant
Yaxun Liub7318e02017-10-13 03:37:48 +0000750 0, // opencl_private
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000751 4, // opencl_generic
752 5, // cuda_device
753 6, // cuda_constant
754 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000755 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000756 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000757 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000758 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000759 }
760}
761
David Tweed31d09b02013-09-13 12:04:22 +0000762static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
763 const LangOptions &LangOpts) {
764 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000765 case LangOptions::ASMM_Target:
766 return TI.useAddressSpaceMapMangling();
767 case LangOptions::ASMM_On:
768 return true;
769 case LangOptions::ASMM_Off:
770 return false;
771 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000772 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000773}
774
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000775ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000776 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000777 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000778 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
779 DependentTemplateSpecializationTypes(this_()),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000780 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000781 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000782 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +0000783 LangOpts.XRayNeverInstrumentFiles,
784 LangOpts.XRayAttrListFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000785 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000786 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000787 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
788 CompCategories(this_()), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000789 TUDecl = TranslationUnitDecl::Create(*this);
Sam McCall814e7972018-11-14 10:33:30 +0000790 TraversalScope = {TUDecl};
Daniel Dunbar221fa942008-08-11 04:54:23 +0000791}
792
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000793ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000794 // Release the DenseMaps associated with DeclContext objects.
795 // FIXME: Is this the ideal solution?
796 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000797
Manuel Klimeka7328992013-06-03 13:51:33 +0000798 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000799 for (auto &Pair : Deallocations)
800 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000801
Ted Kremenek076baeb2010-06-08 23:00:58 +0000802 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000803 // because they can contain DenseMaps.
804 for (llvm::DenseMap<const ObjCContainerDecl*,
805 const ASTRecordLayout*>::iterator
806 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
807 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000808 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Douglas Gregor5b11d492010-07-25 17:53:33 +0000809 R->Destroy(*this);
810
Ted Kremenek076baeb2010-06-08 23:00:58 +0000811 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
812 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
813 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000814 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Ted Kremenek076baeb2010-06-08 23:00:58 +0000815 R->Destroy(*this);
816 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000817
Douglas Gregor561eceb2010-08-30 16:49:28 +0000818 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
819 AEnd = DeclAttrs.end();
820 A != AEnd; ++A)
821 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000822
David Majnemere694f3e2015-08-14 14:43:50 +0000823 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
824 MaterializedTemporaryValues)
825 MTVPair.second->~APValue();
826
Richard Smith423f46f2016-07-20 21:38:26 +0000827 for (const auto &Value : ModuleInitializers)
828 Value.second->~PerModuleInitializers();
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000829
830 for (APValue *Value : APValueCleanups)
831 Value->~APValue();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000832}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000833
Sam McCall814e7972018-11-14 10:33:30 +0000834class ASTContext::ParentMap {
835 /// Contains parents of a node.
836 using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
837
838 /// Maps from a node to its parents. This is used for nodes that have
839 /// pointer identity only, which are more common and we can save space by
840 /// only storing a unique pointer to them.
841 using ParentMapPointers = llvm::DenseMap<
842 const void *,
843 llvm::PointerUnion4<const Decl *, const Stmt *,
844 ast_type_traits::DynTypedNode *, ParentVector *>>;
845
846 /// Parent map for nodes without pointer identity. We store a full
847 /// DynTypedNode for all keys.
848 using ParentMapOtherNodes = llvm::DenseMap<
849 ast_type_traits::DynTypedNode,
850 llvm::PointerUnion4<const Decl *, const Stmt *,
851 ast_type_traits::DynTypedNode *, ParentVector *>>;
852
853 ParentMapPointers PointerParents;
854 ParentMapOtherNodes OtherParents;
855 class ASTVisitor;
856
857 static ast_type_traits::DynTypedNode
858 getSingleDynTypedNodeFromParentMap(ParentMapPointers::mapped_type U) {
859 if (const auto *D = U.dyn_cast<const Decl *>())
860 return ast_type_traits::DynTypedNode::create(*D);
861 if (const auto *S = U.dyn_cast<const Stmt *>())
862 return ast_type_traits::DynTypedNode::create(*S);
863 return *U.get<ast_type_traits::DynTypedNode *>();
864 }
865
866 template <typename NodeTy, typename MapTy>
867 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
868 const MapTy &Map) {
869 auto I = Map.find(Node);
870 if (I == Map.end()) {
871 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
872 }
873 if (const auto *V = I->second.template dyn_cast<ParentVector *>()) {
874 return llvm::makeArrayRef(*V);
875 }
876 return getSingleDynTypedNodeFromParentMap(I->second);
877 }
878
879public:
880 ParentMap(ASTContext &Ctx);
881 ~ParentMap() {
882 for (const auto &Entry : PointerParents) {
883 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
884 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
885 } else if (Entry.second.is<ParentVector *>()) {
886 delete Entry.second.get<ParentVector *>();
887 }
888 }
889 for (const auto &Entry : OtherParents) {
890 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
891 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
892 } else if (Entry.second.is<ParentVector *>()) {
893 delete Entry.second.get<ParentVector *>();
894 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000895 }
896 }
Sam McCall814e7972018-11-14 10:33:30 +0000897
898 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node) {
899 if (Node.getNodeKind().hasPointerIdentity())
900 return getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
901 return getDynNodeFromMap(Node, OtherParents);
Manuel Klimek95403e62014-05-21 13:28:59 +0000902 }
Sam McCall814e7972018-11-14 10:33:30 +0000903};
904
905void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
906 TraversalScope = TopLevelDecls;
907 Parents.reset();
Manuel Klimek95403e62014-05-21 13:28:59 +0000908}
909
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000910void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000911 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000912}
913
Mike Stump11289f42009-09-09 15:08:12 +0000914void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000915ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000916 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000917}
918
Chris Lattner4eb445d2007-01-26 01:27:23 +0000919void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000920 llvm::errs() << "\n*** AST Context Stats:\n";
921 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000922
Douglas Gregora30d0462009-05-26 14:40:08 +0000923 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000924#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000925#define ABSTRACT_TYPE(Name, Parent)
926#include "clang/AST/TypeNodes.def"
927 0 // Extra
928 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000929
Chris Lattner4eb445d2007-01-26 01:27:23 +0000930 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
931 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000932 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000933 }
934
Douglas Gregora30d0462009-05-26 14:40:08 +0000935 unsigned Idx = 0;
936 unsigned TotalBytes = 0;
937#define TYPE(Name, Parent) \
938 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000939 llvm::errs() << " " << counts[Idx] << " " << #Name \
Bruno Ricci58e03222018-08-06 15:17:32 +0000940 << " types, " << sizeof(Name##Type) << " each " \
941 << "(" << counts[Idx] * sizeof(Name##Type) \
942 << " bytes)\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000943 TotalBytes += counts[Idx] * sizeof(Name##Type); \
944 ++Idx;
945#define ABSTRACT_TYPE(Name, Parent)
946#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000947
Chandler Carruth3c147a72011-07-04 05:32:14 +0000948 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
949
Douglas Gregor7454c562010-07-02 20:37:36 +0000950 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000951 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
952 << NumImplicitDefaultConstructors
953 << " implicit default constructors created\n";
954 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
955 << NumImplicitCopyConstructors
956 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000957 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000958 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
959 << NumImplicitMoveConstructors
960 << " implicit move constructors created\n";
961 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
962 << NumImplicitCopyAssignmentOperators
963 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000964 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000965 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
966 << NumImplicitMoveAssignmentOperators
967 << " implicit move assignment operators created\n";
968 llvm::errs() << NumImplicitDestructorsDeclared << "/"
969 << NumImplicitDestructors
970 << " implicit destructors created\n";
971
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000972 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000973 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000974 ExternalSource->PrintStats();
975 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000976
Douglas Gregor5b11d492010-07-25 17:53:33 +0000977 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000978}
979
Richard Smith42413142015-05-15 20:05:43 +0000980void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
981 bool NotifyListeners) {
982 if (NotifyListeners)
983 if (auto *Listener = getASTMutationListener())
984 Listener->RedefinedHiddenDefinition(ND, M);
985
Richard Smith13897eb2018-09-12 23:37:00 +0000986 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
Richard Smith42413142015-05-15 20:05:43 +0000987}
988
989void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
Richard Smith20fbdb32018-09-12 02:13:46 +0000990 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
Richard Smith42413142015-05-15 20:05:43 +0000991 if (It == MergedDefModules.end())
992 return;
993
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000994 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000995 llvm::DenseSet<Module*> Found;
996 for (Module *&M : Merged)
997 if (!Found.insert(M).second)
998 M = nullptr;
999 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1000}
1001
Richard Smithdc1f0422016-07-20 19:10:16 +00001002void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1003 if (LazyInitializers.empty())
1004 return;
1005
1006 auto *Source = Ctx.getExternalSource();
1007 assert(Source && "lazy initializers but no external source");
1008
1009 auto LazyInits = std::move(LazyInitializers);
1010 LazyInitializers.clear();
1011
1012 for (auto ID : LazyInits)
1013 Initializers.push_back(Source->GetExternalDecl(ID));
1014
1015 assert(LazyInitializers.empty() &&
1016 "GetExternalDecl for lazy module initializer added more inits");
1017}
1018
1019void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1020 // One special case: if we add a module initializer that imports another
1021 // module, and that module's only initializer is an ImportDecl, simplify.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001022 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001023 auto It = ModuleInitializers.find(ID->getImportedModule());
1024
1025 // Maybe the ImportDecl does nothing at all. (Common case.)
1026 if (It == ModuleInitializers.end())
1027 return;
1028
1029 // Maybe the ImportDecl only imports another ImportDecl.
1030 auto &Imported = *It->second;
1031 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1032 Imported.resolve(*this);
1033 auto *OnlyDecl = Imported.Initializers.front();
1034 if (isa<ImportDecl>(OnlyDecl))
1035 D = OnlyDecl;
1036 }
1037 }
1038
1039 auto *&Inits = ModuleInitializers[M];
1040 if (!Inits)
1041 Inits = new (*this) PerModuleInitializers;
1042 Inits->Initializers.push_back(D);
1043}
1044
1045void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1046 auto *&Inits = ModuleInitializers[M];
1047 if (!Inits)
1048 Inits = new (*this) PerModuleInitializers;
1049 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1050 IDs.begin(), IDs.end());
1051}
1052
Eugene Zelenko7855e772018-04-03 00:11:50 +00001053ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001054 auto It = ModuleInitializers.find(M);
Fangrui Song6907ce22018-07-30 19:24:48 +00001055 if (It == ModuleInitializers.end())
Richard Smithdc1f0422016-07-20 19:10:16 +00001056 return None;
1057
1058 auto *Inits = It->second;
1059 Inits->resolve(*this);
1060 return Inits->Initializers;
1061}
1062
Richard Smithf19e1272015-03-07 00:04:49 +00001063ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1064 if (!ExternCContext)
1065 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1066
1067 return ExternCContext;
1068}
1069
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001070BuiltinTemplateDecl *
1071ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1072 const IdentifierInfo *II) const {
1073 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1074 BuiltinTemplate->setImplicit();
1075 TUDecl->addDecl(BuiltinTemplate);
1076
1077 return BuiltinTemplate;
1078}
1079
1080BuiltinTemplateDecl *
1081ASTContext::getMakeIntegerSeqDecl() const {
1082 if (!MakeIntegerSeqDecl)
1083 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1084 getMakeIntegerSeqName());
1085 return MakeIntegerSeqDecl;
1086}
1087
Eric Fiselier6ad68552016-07-01 01:24:09 +00001088BuiltinTemplateDecl *
1089ASTContext::getTypePackElementDecl() const {
1090 if (!TypePackElementDecl)
1091 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1092 getTypePackElementName());
1093 return TypePackElementDecl;
1094}
1095
Alp Toker2dea15b2013-12-17 01:22:38 +00001096RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1097 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001098 SourceLocation Loc;
1099 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001100 if (getLangOpts().CPlusPlus)
1101 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1102 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001103 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001104 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1105 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001106 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001107 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1108 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001109 return NewDecl;
1110}
1111
1112TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1113 StringRef Name) const {
1114 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1115 TypedefDecl *NewDecl = TypedefDecl::Create(
1116 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1117 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1118 NewDecl->setImplicit();
1119 return NewDecl;
1120}
1121
Douglas Gregor801c99d2011-08-12 06:49:56 +00001122TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001123 if (!Int128Decl)
1124 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001125 return Int128Decl;
1126}
1127
1128TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001129 if (!UInt128Decl)
1130 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001131 return UInt128Decl;
1132}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001133
John McCall48f2d582009-10-23 23:03:21 +00001134void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001135 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001136 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001137 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001138}
1139
Artem Belevichb5bc9232015-09-22 17:23:22 +00001140void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1141 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001142 assert((!this->Target || this->Target == &Target) &&
1143 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001144 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001145
Douglas Gregore8bbc122011-09-02 00:18:52 +00001146 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001147 this->AuxTarget = AuxTarget;
1148
Douglas Gregore8bbc122011-09-02 00:18:52 +00001149 ABI.reset(createCXXABI(Target));
1150 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001151 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Fangrui Song6907ce22018-07-30 19:24:48 +00001152
Chris Lattner970e54e2006-11-12 00:37:36 +00001153 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001154 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001155
Chris Lattner970e54e2006-11-12 00:37:36 +00001156 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001157 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001158 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001159 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001160 InitBuiltinType(CharTy, BuiltinType::Char_S);
1161 else
1162 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001163 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001164 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1165 InitBuiltinType(ShortTy, BuiltinType::Short);
1166 InitBuiltinType(IntTy, BuiltinType::Int);
1167 InitBuiltinType(LongTy, BuiltinType::Long);
1168 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001169
Chris Lattner970e54e2006-11-12 00:37:36 +00001170 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001171 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1172 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1173 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1174 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1175 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001176
Chris Lattner970e54e2006-11-12 00:37:36 +00001177 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001178 InitBuiltinType(FloatTy, BuiltinType::Float);
1179 InitBuiltinType(DoubleTy, BuiltinType::Double);
1180 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001181
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001182 // GNU extension, __float128 for IEEE quadruple precision
1183 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1184
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001185 // C11 extension ISO/IEC TS 18661-3
1186 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1187
Leonard Chanf921d852018-06-04 16:07:52 +00001188 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
Leonard Chanab80f3c2018-06-14 14:53:51 +00001189 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1190 InitBuiltinType(AccumTy, BuiltinType::Accum);
1191 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1192 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1193 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1194 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1195 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1196 InitBuiltinType(FractTy, BuiltinType::Fract);
1197 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1198 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1199 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1200 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1201 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1202 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1203 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1204 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1205 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1206 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1207 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1208 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1209 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1210 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1211 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1212 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
Leonard Chanf921d852018-06-04 16:07:52 +00001213
Chris Lattnerf122cef2009-04-30 02:43:43 +00001214 // GNU extension, 128-bit integers.
1215 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1216 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1217
Hans Wennborg0d81e012013-05-10 10:08:40 +00001218 // C++ 3.9.1p5
1219 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1220 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1221 else // -fshort-wchar makes wchar_t be unsigned.
1222 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1223 if (LangOpts.CPlusPlus && LangOpts.WChar)
1224 WideCharTy = WCharTy;
1225 else {
1226 // C99 (or C++ using -fno-wchar).
1227 WideCharTy = getFromTargetType(Target.getWCharType());
1228 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001229
James Molloy36365542012-05-04 10:55:22 +00001230 WIntTy = getFromTargetType(Target.getWIntType());
1231
Richard Smith3a8244d2018-05-01 05:02:45 +00001232 // C++20 (proposed)
1233 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1234
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001235 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1236 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1237 else // C99
1238 Char16Ty = getFromTargetType(Target.getChar16Type());
1239
1240 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1241 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1242 else // C99
1243 Char32Ty = getFromTargetType(Target.getChar32Type());
1244
Douglas Gregor4619e432008-12-05 23:32:09 +00001245 // Placeholder type for type-dependent expressions whose type is
1246 // completely unknown. No code should ever check a type against
1247 // DependentTy and users should never see it; however, it is here to
1248 // help diagnose failures to properly check for type-dependent
1249 // expressions.
1250 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001251
John McCall36e7fe32010-10-12 00:20:44 +00001252 // Placeholder type for functions.
1253 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1254
John McCall0009fcc2011-04-26 20:42:42 +00001255 // Placeholder type for bound members.
1256 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1257
John McCall526ab472011-10-25 17:37:35 +00001258 // Placeholder type for pseudo-objects.
1259 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1260
John McCall31996342011-04-07 08:22:57 +00001261 // "any" type; useful for debugger-like clients.
1262 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1263
John McCall8a6b59a2011-10-17 18:09:15 +00001264 // Placeholder type for unbridged ARC casts.
1265 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1266
Eli Friedman34866c72012-08-31 00:14:07 +00001267 // Placeholder type for builtin functions.
1268 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1269
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001270 // Placeholder type for OMP array sections.
1271 if (LangOpts.OpenMP)
1272 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1273
Chris Lattner970e54e2006-11-12 00:37:36 +00001274 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001275 FloatComplexTy = getComplexType(FloatTy);
1276 DoubleComplexTy = getComplexType(DoubleTy);
1277 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001278 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001279
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001280 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001281 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1282 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001283 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001284
Alexey Bader954ba212016-04-08 13:40:33 +00001285 if (LangOpts.OpenCL) {
1286#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1287 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001288#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001289
Guy Benyei61054192013-02-07 10:55:47 +00001290 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001291 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001292 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1293 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001294 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001295
1296#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1297 InitBuiltinType(Id##Ty, BuiltinType::Id);
1298#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001299 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001300
Ted Kremeneke65b0862012-03-06 20:05:56 +00001301 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001302 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1303 SignedCharTy : BoolTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001304
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001305 ObjCConstantStringType = QualType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001306
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001307 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001308
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001309 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001310 if (LangOpts.OpenCLVersion >= 200) {
1311 auto Q = VoidTy.getQualifiers();
1312 Q.setAddressSpace(LangAS::opencl_generic);
1313 VoidPtrTy = getPointerType(getCanonicalType(
1314 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1315 } else {
1316 VoidPtrTy = getPointerType(VoidTy);
1317 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001318
1319 // nullptr type (C++0x 2.14.7)
1320 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001321
1322 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1323 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001324
1325 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001326 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001327}
1328
David Blaikie9c902b52011-09-25 23:23:43 +00001329DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001330 return SourceMgr.getDiagnostics();
1331}
1332
Douglas Gregor561eceb2010-08-30 16:49:28 +00001333AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1334 AttrVec *&Result = DeclAttrs[D];
1335 if (!Result) {
1336 void *Mem = Allocate(sizeof(AttrVec));
1337 Result = new (Mem) AttrVec;
1338 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001339
Douglas Gregor561eceb2010-08-30 16:49:28 +00001340 return *Result;
1341}
1342
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001343/// Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001344void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001345 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1346 if (Pos != DeclAttrs.end()) {
1347 Pos->second->~AttrVec();
1348 DeclAttrs.erase(Pos);
1349 }
1350}
1351
Larisse Voufo39a1e502013-08-06 01:03:05 +00001352// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001353MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001354ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001355 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001356 return getTemplateOrSpecializationInfo(Var)
1357 .dyn_cast<MemberSpecializationInfo *>();
1358}
1359
1360ASTContext::TemplateOrSpecializationInfo
1361ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1362 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1363 TemplateOrInstantiation.find(Var);
1364 if (Pos == TemplateOrInstantiation.end())
Eugene Zelenko7855e772018-04-03 00:11:50 +00001365 return {};
Mike Stump11289f42009-09-09 15:08:12 +00001366
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001367 return Pos->second;
1368}
1369
Mike Stump11289f42009-09-09 15:08:12 +00001370void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001371ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001372 TemplateSpecializationKind TSK,
1373 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001374 assert(Inst->isStaticDataMember() && "Not a static data member");
1375 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001376 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1377 Tmpl, TSK, PointOfInstantiation));
1378}
1379
1380void
1381ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1382 TemplateOrSpecializationInfo TSI) {
1383 assert(!TemplateOrInstantiation[Inst] &&
1384 "Already noted what the variable was instantiated from");
1385 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001386}
1387
John McCalle61f2ba2009-11-18 02:36:19 +00001388NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001389ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1390 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001391 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001392 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001393
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001394 return Pos->second;
1395}
1396
1397void
Richard Smithd8a9e372016-12-18 21:39:37 +00001398ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001399 assert((isa<UsingDecl>(Pattern) ||
1400 isa<UnresolvedUsingValueDecl>(Pattern) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001401 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
John McCallb96ec562009-12-04 22:46:56 +00001402 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001403 assert((isa<UsingDecl>(Inst) ||
1404 isa<UnresolvedUsingValueDecl>(Inst) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001405 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
Richard Smithd8a9e372016-12-18 21:39:37 +00001406 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001407 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1408 InstantiatedFromUsingDecl[Inst] = Pattern;
1409}
1410
1411UsingShadowDecl *
1412ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1413 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1414 = InstantiatedFromUsingShadowDecl.find(Inst);
1415 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001416 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001417
1418 return Pos->second;
1419}
1420
1421void
1422ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1423 UsingShadowDecl *Pattern) {
1424 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1425 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001426}
1427
Anders Carlsson5da84842009-09-01 04:26:58 +00001428FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1429 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1430 = InstantiatedFromUnnamedFieldDecl.find(Field);
1431 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001432 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001433
Anders Carlsson5da84842009-09-01 04:26:58 +00001434 return Pos->second;
1435}
1436
1437void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1438 FieldDecl *Tmpl) {
1439 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1440 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1441 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1442 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001443
Anders Carlsson5da84842009-09-01 04:26:58 +00001444 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1445}
1446
Douglas Gregor832940b2010-03-02 23:58:15 +00001447ASTContext::overridden_cxx_method_iterator
1448ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001449 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001450}
1451
1452ASTContext::overridden_cxx_method_iterator
1453ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001454 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001455}
1456
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001457unsigned
1458ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001459 auto Range = overridden_methods(Method);
1460 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001461}
1462
Clement Courbet6ecaec82016-07-05 07:49:31 +00001463ASTContext::overridden_method_range
1464ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001465 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1466 OverriddenMethods.find(Method->getCanonicalDecl());
1467 if (Pos == OverriddenMethods.end())
1468 return overridden_method_range(nullptr, nullptr);
1469 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001470}
1471
Fangrui Song6907ce22018-07-30 19:24:48 +00001472void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
Douglas Gregor832940b2010-03-02 23:58:15 +00001473 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001474 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001475 OverriddenMethods[Method].push_back(Overridden);
1476}
1477
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001478void ASTContext::getOverriddenMethods(
1479 const NamedDecl *D,
1480 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001481 assert(D);
1482
Eugene Zelenko7855e772018-04-03 00:11:50 +00001483 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001484 Overridden.append(overridden_methods_begin(CXXMethod),
1485 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001486 return;
1487 }
1488
Eugene Zelenko7855e772018-04-03 00:11:50 +00001489 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001490 if (!Method)
1491 return;
1492
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001493 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1494 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001495 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001496}
1497
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001498void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1499 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1500 assert(!Import->isFromASTFile() && "Non-local import declaration");
1501 if (!FirstLocalImport) {
1502 FirstLocalImport = Import;
1503 LastLocalImport = Import;
1504 return;
1505 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001506
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001507 LastLocalImport->NextLocalImport = Import;
1508 LastLocalImport = Import;
1509}
1510
Chris Lattner53cfe802007-07-18 17:52:12 +00001511//===----------------------------------------------------------------------===//
1512// Type Sizing and Analysis
1513//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001514
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001515/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1516/// scalar floating point type.
1517const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001518 const auto *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001519 assert(BT && "Not a floating point type!");
1520 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001521 default: llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001522 case BuiltinType::Float16:
1523 case BuiltinType::Half:
1524 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001525 case BuiltinType::Float: return Target->getFloatFormat();
1526 case BuiltinType::Double: return Target->getDoubleFormat();
Alexey Bataeve509af32019-07-09 14:09:53 +00001527 case BuiltinType::LongDouble:
Fangrui Song3fbd8fd2019-07-09 19:36:22 +00001528 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
Alexey Bataeve509af32019-07-09 14:09:53 +00001529 return AuxTarget->getLongDoubleFormat();
1530 return Target->getLongDoubleFormat();
1531 case BuiltinType::Float128:
Fangrui Song3fbd8fd2019-07-09 19:36:22 +00001532 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
Alexey Bataeve509af32019-07-09 14:09:53 +00001533 return AuxTarget->getFloat128Format();
1534 return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001535 }
1536}
1537
Rafael Espindola71eccb32013-08-08 19:53:46 +00001538CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001539 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001540
John McCall94268702010-10-08 18:24:19 +00001541 bool UseAlignAttrOnly = false;
1542 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1543 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001544
John McCall94268702010-10-08 18:24:19 +00001545 // __attribute__((aligned)) can increase or decrease alignment
1546 // *except* on a struct or struct member, where it only increases
1547 // alignment unless 'packed' is also specified.
1548 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001549 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001550 // ignore that possibility; Sema should diagnose it.
1551 if (isa<FieldDecl>(D)) {
1552 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1553 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1554 } else {
1555 UseAlignAttrOnly = true;
1556 }
1557 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001558 else if (isa<FieldDecl>(D))
Fangrui Song6907ce22018-07-30 19:24:48 +00001559 UseAlignAttrOnly =
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001560 D->hasAttr<PackedAttr>() ||
1561 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001562
John McCall4e819612011-01-20 07:57:12 +00001563 // If we're using the align attribute only, just ignore everything
1564 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001565 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001566 // do nothing
Eugene Zelenko7855e772018-04-03 00:11:50 +00001567 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001568 QualType T = VD->getType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001569 if (const auto *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001570 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001571 T = RT->getPointeeType();
1572 else
1573 T = getPointerType(RT->getPointeeType());
1574 }
Richard Smithf6d70302014-06-10 23:34:28 +00001575 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001576 if (T->isFunctionType())
1577 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1578 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001579 // Adjust alignments of declarations with array type by the
1580 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001581 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001582 unsigned MinWidth = Target->getLargeArrayMinWidth();
1583 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001584 if (isa<VariableArrayType>(arrayType))
1585 Align = std::max(Align, Target->getLargeArrayAlign());
1586 else if (isa<ConstantArrayType>(arrayType) &&
1587 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1588 Align = std::max(Align, Target->getLargeArrayAlign());
1589 }
John McCall33ddac02011-01-19 10:06:00 +00001590 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001591 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001592 if (BaseT.getQualifiers().hasUnaligned())
1593 Align = Target->getCharWidth();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001594 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Tom Tanb7c6d952019-05-02 00:38:14 +00001595 if (VD->hasGlobalStorage() && !ForAlignof) {
1596 uint64_t TypeSize = getTypeSize(T.getTypePtr());
1597 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1598 }
Ulrich Weigandfa806422013-05-06 16:23:57 +00001599 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001600 }
John McCall4e819612011-01-20 07:57:12 +00001601
1602 // Fields can be subject to extra alignment constraints, like if
1603 // the field is packed, the struct is packed, or the struct has a
1604 // a max-field-alignment constraint (#pragma pack). So calculate
1605 // the actual alignment of the field within the struct, and then
1606 // (as we're expected to) constrain that by the alignment of the type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001607 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001608 const RecordDecl *Parent = Field->getParent();
1609 // We can only produce a sensible answer if the record is valid.
1610 if (!Parent->isInvalidDecl()) {
1611 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001612
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001613 // Start with the record's overall alignment.
1614 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001615
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001616 // Use the GCD of that and the offset within the record.
1617 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1618 if (Offset > 0) {
1619 // Alignment is always a power of 2, so the GCD will be a power of 2,
1620 // which means we get to do this crazy thing instead of Euclid's.
1621 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1622 if (LowBitOfOffset < FieldAlign)
1623 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1624 }
1625
1626 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001627 }
Charles Davis3fc51072010-02-23 04:52:00 +00001628 }
Chris Lattner68061312009-01-24 21:53:27 +00001629 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001630
Ken Dyckcc56c542011-01-15 18:38:59 +00001631 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001632}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001633
John McCallf1249922012-08-21 04:10:00 +00001634// getTypeInfoDataSizeInChars - Return the size of a type, in
1635// chars. If the type is a record, its data size is returned. This is
1636// the size of the memcpy that's performed when assigning this type
1637// using a trivial copy/move assignment operator.
1638std::pair<CharUnits, CharUnits>
1639ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1640 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1641
1642 // In C++, objects can sometimes be allocated into the tail padding
1643 // of a base-class subobject. We decide whether that's possible
1644 // during class layout, so here we can just trust the layout results.
1645 if (getLangOpts().CPlusPlus) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001646 if (const auto *RT = T->getAs<RecordType>()) {
John McCallf1249922012-08-21 04:10:00 +00001647 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1648 sizeAndAlign.first = layout.getDataSize();
1649 }
1650 }
1651
1652 return sizeAndAlign;
1653}
1654
Richard Trieu04d2d942013-05-14 21:59:17 +00001655/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1656/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1657std::pair<CharUnits, CharUnits>
1658static getConstantArrayInfoInChars(const ASTContext &Context,
1659 const ConstantArrayType *CAT) {
1660 std::pair<CharUnits, CharUnits> EltInfo =
1661 Context.getTypeInfoInChars(CAT->getElementType());
1662 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001663 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1664 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001665 "Overflow in array type char size evaluation");
1666 uint64_t Width = EltInfo.first.getQuantity() * Size;
1667 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001668 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1669 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001670 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001671 return std::make_pair(CharUnits::fromQuantity(Width),
1672 CharUnits::fromQuantity(Align));
1673}
1674
John McCall87fe5d52010-05-20 01:18:31 +00001675std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001676ASTContext::getTypeInfoInChars(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001677 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
Richard Trieu04d2d942013-05-14 21:59:17 +00001678 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001679 TypeInfo Info = getTypeInfo(T);
1680 return std::make_pair(toCharUnitsFromBits(Info.Width),
1681 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001682}
1683
1684std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001685ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001686 return getTypeInfoInChars(T.getTypePtr());
1687}
1688
David Majnemer34b57492014-07-30 01:30:47 +00001689bool ASTContext::isAlignmentRequired(const Type *T) const {
1690 return getTypeInfo(T).AlignIsRequired;
1691}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001692
David Majnemer34b57492014-07-30 01:30:47 +00001693bool ASTContext::isAlignmentRequired(QualType T) const {
1694 return isAlignmentRequired(T.getTypePtr());
1695}
1696
Richard Smithb2f0f052016-10-10 18:54:32 +00001697unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1698 // An alignment on a typedef overrides anything else.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001699 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001700 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1701 return Align;
1702
1703 // If we have an (array of) complete type, we're done.
1704 T = getBaseElementType(T);
1705 if (!T->isIncompleteType())
1706 return getTypeAlign(T);
1707
1708 // If we had an array type, its element type might be a typedef
1709 // type with an alignment attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001710 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001711 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1712 return Align;
1713
1714 // Otherwise, see if the declaration of the type had an attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001715 if (const auto *TT = T->getAs<TagType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001716 return TT->getDecl()->getMaxAlignment();
1717
1718 return 0;
1719}
1720
David Majnemer34b57492014-07-30 01:30:47 +00001721TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001722 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1723 if (I != MemoizedTypeInfo.end())
1724 return I->second;
1725
1726 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1727 TypeInfo TI = getTypeInfoImpl(T);
1728 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001729 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001730}
1731
1732/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1733/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001734///
1735/// FIXME: Pointers into different addr spaces could have different sizes and
1736/// alignment requirements: getPointerInfo should take an AddrSpace, this
1737/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001738TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1739 uint64_t Width = 0;
1740 unsigned Align = 8;
1741 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001742 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001743 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001744#define TYPE(Class, Base)
1745#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001746#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001747#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001748#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1749 case Type::Class: \
1750 assert(!T->isDependentType() && "should not see dependent types here"); \
1751 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001752#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001753 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001754
Chris Lattner355332d2007-07-13 22:27:08 +00001755 case Type::FunctionNoProto:
1756 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001757 // GCC extension: alignof(function) = 32 bits
1758 Width = 0;
1759 Align = 32;
1760 break;
1761
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001762 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001763 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001764 Width = 0;
1765 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1766 break;
1767
Steve Naroff5c131802007-08-30 01:06:46 +00001768 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001769 const auto *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001770
David Majnemer34b57492014-07-30 01:30:47 +00001771 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001772 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001773 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001774 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001775 Width = EltInfo.Width * Size;
1776 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001777 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1778 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001779 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001780 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001781 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001782 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001783 case Type::Vector: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001784 const auto *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001785 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1786 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001787 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001788 // If the alignment is not a power of 2, round up to the next power of 2.
1789 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001790 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001791 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001792 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001793 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001794 // Adjust the alignment based on the target max.
1795 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1796 if (TargetVectorAlign && TargetVectorAlign < Align)
1797 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001798 break;
1799 }
Chris Lattner647fb222007-07-18 18:26:58 +00001800
Chris Lattner7570e9c2008-03-08 08:52:55 +00001801 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001802 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001803 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001804 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001805 // GCC extension: alignof(void) = 8 bits.
1806 Width = 0;
1807 Align = 8;
1808 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001809 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001810 Width = Target->getBoolWidth();
1811 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001812 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001813 case BuiltinType::Char_S:
1814 case BuiltinType::Char_U:
1815 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001816 case BuiltinType::SChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00001817 case BuiltinType::Char8:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001818 Width = Target->getCharWidth();
1819 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001820 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001821 case BuiltinType::WChar_S:
1822 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001823 Width = Target->getWCharWidth();
1824 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001825 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001826 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001827 Width = Target->getChar16Width();
1828 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001829 break;
1830 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001831 Width = Target->getChar32Width();
1832 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001833 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001834 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001835 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001836 Width = Target->getShortWidth();
1837 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001838 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001839 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001840 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001841 Width = Target->getIntWidth();
1842 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001843 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001844 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001845 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001846 Width = Target->getLongWidth();
1847 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001848 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001849 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001850 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001851 Width = Target->getLongLongWidth();
1852 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001853 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001854 case BuiltinType::Int128:
1855 case BuiltinType::UInt128:
1856 Width = 128;
1857 Align = 128; // int128_t is 128-bit aligned on all targets.
1858 break;
Leonard Chanf921d852018-06-04 16:07:52 +00001859 case BuiltinType::ShortAccum:
1860 case BuiltinType::UShortAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001861 case BuiltinType::SatShortAccum:
1862 case BuiltinType::SatUShortAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001863 Width = Target->getShortAccumWidth();
1864 Align = Target->getShortAccumAlign();
1865 break;
1866 case BuiltinType::Accum:
1867 case BuiltinType::UAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001868 case BuiltinType::SatAccum:
1869 case BuiltinType::SatUAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001870 Width = Target->getAccumWidth();
1871 Align = Target->getAccumAlign();
1872 break;
1873 case BuiltinType::LongAccum:
1874 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001875 case BuiltinType::SatLongAccum:
1876 case BuiltinType::SatULongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001877 Width = Target->getLongAccumWidth();
1878 Align = Target->getLongAccumAlign();
1879 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00001880 case BuiltinType::ShortFract:
1881 case BuiltinType::UShortFract:
1882 case BuiltinType::SatShortFract:
1883 case BuiltinType::SatUShortFract:
1884 Width = Target->getShortFractWidth();
1885 Align = Target->getShortFractAlign();
1886 break;
1887 case BuiltinType::Fract:
1888 case BuiltinType::UFract:
1889 case BuiltinType::SatFract:
1890 case BuiltinType::SatUFract:
1891 Width = Target->getFractWidth();
1892 Align = Target->getFractAlign();
1893 break;
1894 case BuiltinType::LongFract:
1895 case BuiltinType::ULongFract:
1896 case BuiltinType::SatLongFract:
1897 case BuiltinType::SatULongFract:
1898 Width = Target->getLongFractWidth();
1899 Align = Target->getLongFractAlign();
1900 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001901 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001902 case BuiltinType::Half:
Alexey Bataev123ad192019-02-27 20:29:45 +00001903 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
1904 !getLangOpts().OpenMPIsDevice) {
1905 Width = Target->getHalfWidth();
1906 Align = Target->getHalfAlign();
1907 } else {
1908 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1909 "Expected OpenMP device compilation.");
1910 Width = AuxTarget->getHalfWidth();
1911 Align = AuxTarget->getHalfAlign();
1912 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001913 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001914 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001915 Width = Target->getFloatWidth();
1916 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001917 break;
1918 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001919 Width = Target->getDoubleWidth();
1920 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001921 break;
1922 case BuiltinType::LongDouble:
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001923 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1924 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
1925 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
1926 Width = AuxTarget->getLongDoubleWidth();
1927 Align = AuxTarget->getLongDoubleAlign();
1928 } else {
1929 Width = Target->getLongDoubleWidth();
1930 Align = Target->getLongDoubleAlign();
1931 }
Chris Lattner6a4f7452007-12-19 19:23:28 +00001932 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001933 case BuiltinType::Float128:
Alexey Bataev123ad192019-02-27 20:29:45 +00001934 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
1935 !getLangOpts().OpenMPIsDevice) {
1936 Width = Target->getFloat128Width();
1937 Align = Target->getFloat128Align();
1938 } else {
1939 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1940 "Expected OpenMP device compilation.");
1941 Width = AuxTarget->getFloat128Width();
1942 Align = AuxTarget->getFloat128Align();
1943 }
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001944 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001945 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001946 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1947 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001948 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001949 case BuiltinType::ObjCId:
1950 case BuiltinType::ObjCClass:
1951 case BuiltinType::ObjCSel:
Fangrui Song6907ce22018-07-30 19:24:48 +00001952 Width = Target->getPointerWidth(0);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001953 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001954 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001955 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001956 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001957 case BuiltinType::OCLClkEvent:
1958 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001959 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00001960#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1961 case BuiltinType::Id:
1962#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001963#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1964 case BuiltinType::Id:
1965#include "clang/Basic/OpenCLExtensionTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00001966 AS = getTargetAddressSpace(
1967 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001968 Width = Target->getPointerWidth(AS);
1969 Align = Target->getPointerAlign(AS);
1970 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001971 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001972 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001973 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001974 Width = Target->getPointerWidth(0);
1975 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001976 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001977 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001978 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001979 Width = Target->getPointerWidth(AS);
1980 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001981 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001982 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001983 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001984 // alignof and sizeof should never enter this code path here, so we go
1985 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001986 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001987 Width = Target->getPointerWidth(AS);
1988 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001989 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001990 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001991 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001992 Width = Target->getPointerWidth(AS);
1993 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001994 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001995 case Type::MemberPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001996 const auto *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00001997 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
1998 Width = MPI.Width;
1999 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00002000 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002001 }
Chris Lattner647fb222007-07-18 18:26:58 +00002002 case Type::Complex: {
2003 // Complex types have the same alignment as their elements, but twice the
2004 // size.
David Majnemer34b57492014-07-30 01:30:47 +00002005 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2006 Width = EltInfo.Width * 2;
2007 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00002008 break;
2009 }
John McCall8b07ec22010-05-15 11:32:37 +00002010 case Type::ObjCObject:
2011 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00002012 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002013 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002014 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00002015 case Type::ObjCInterface: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002016 const auto *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00002017 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00002018 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002019 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00002020 break;
2021 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002022 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002023 case Type::Enum: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002024 const auto *TT = cast<TagType>(T);
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00002025
2026 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00002027 Width = 8;
2028 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00002029 break;
2030 }
Mike Stump11289f42009-09-09 15:08:12 +00002031
Eugene Zelenko7855e772018-04-03 00:11:50 +00002032 if (const auto *ET = dyn_cast<EnumType>(TT)) {
David Majnemer475b25e2015-01-21 10:54:38 +00002033 const EnumDecl *ED = ET->getDecl();
2034 TypeInfo Info =
2035 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2036 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2037 Info.Align = AttrAlign;
2038 Info.AlignIsRequired = true;
2039 }
2040 return Info;
2041 }
Chris Lattner8b23c252008-04-06 22:05:18 +00002042
Eugene Zelenko7855e772018-04-03 00:11:50 +00002043 const auto *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00002044 const RecordDecl *RD = RT->getDecl();
2045 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00002046 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002047 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00002048 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00002049 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00002050 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002051
Chris Lattner63d2b362009-10-22 05:17:15 +00002052 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00002053 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2054 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00002055
Richard Smith600b5262017-01-26 20:40:47 +00002056 case Type::Auto:
2057 case Type::DeducedTemplateSpecialization: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002058 const auto *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00002059 assert(!A->getDeducedType().isNull() &&
2060 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00002061 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00002062 }
2063
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002064 case Type::Paren:
2065 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2066
Leonard Chanc72aaf62019-05-07 03:20:17 +00002067 case Type::MacroQualified:
2068 return getTypeInfo(
2069 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2070
Manman Rene6be26c2016-09-13 17:25:08 +00002071 case Type::ObjCTypeParam:
2072 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2073
Douglas Gregoref462e62009-04-30 17:32:17 +00002074 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00002075 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00002076 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00002077 // If the typedef has an aligned attribute on it, it overrides any computed
2078 // alignment we have. This violates the GCC documentation (which says that
2079 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00002080 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00002081 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00002082 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00002083 } else {
David Majnemer34b57492014-07-30 01:30:47 +00002084 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00002085 AlignIsRequired = Info.AlignIsRequired;
2086 }
David Majnemer34b57492014-07-30 01:30:47 +00002087 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00002088 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00002089 }
Douglas Gregoref462e62009-04-30 17:32:17 +00002090
Abramo Bagnara6150c882010-05-11 21:36:43 +00002091 case Type::Elaborated:
2092 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00002093
John McCall81904512011-01-06 01:58:22 +00002094 case Type::Attributed:
2095 return getTypeInfo(
2096 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2097
Eli Friedman0dfb8892011-10-06 23:00:33 +00002098 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00002099 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00002100 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2101 Width = Info.Width;
2102 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00002103
JF Bastien801fca22018-05-09 03:51:12 +00002104 if (!Width) {
2105 // An otherwise zero-sized type should still generate an
2106 // atomic operation.
2107 Width = Target->getCharWidth();
2108 assert(Align);
2109 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2110 // If the size of the type doesn't exceed the platform's max
2111 // atomic promotion width, make the size and alignment more
2112 // favorable to atomic operations:
2113
John McCalla8ec7eb2013-03-07 21:37:17 +00002114 // Round the size up to a power of 2.
2115 if (!llvm::isPowerOf2_64(Width))
2116 Width = llvm::NextPowerOf2(Width);
2117
2118 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002119 Align = static_cast<unsigned>(Width);
2120 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00002121 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00002122 break;
2123
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002124 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00002125 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2126 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002127 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00002128 }
Mike Stump11289f42009-09-09 15:08:12 +00002129
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002130 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00002131 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00002132}
2133
Momchil Velikov20208cc2018-07-30 17:48:23 +00002134unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2135 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2136 if (I != MemoizedUnadjustedAlign.end())
2137 return I->second;
2138
2139 unsigned UnadjustedAlign;
2140 if (const auto *RT = T->getAs<RecordType>()) {
2141 const RecordDecl *RD = RT->getDecl();
2142 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2143 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2144 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2145 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2146 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2147 } else {
John Brawn6c49f582019-05-22 11:42:54 +00002148 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
Momchil Velikov20208cc2018-07-30 17:48:23 +00002149 }
2150
2151 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2152 return UnadjustedAlign;
2153}
2154
Alexey Bataev00396512015-07-02 03:40:19 +00002155unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2156 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2157 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2158 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2159 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2160 getTargetInfo().getABI() == "elfv1-qpx" &&
2161 T->isSpecificBuiltinType(BuiltinType::Double))
2162 SimdAlign = 256;
2163 return SimdAlign;
2164}
2165
Ken Dyckcc56c542011-01-15 18:38:59 +00002166/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2167CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2168 return CharUnits::fromQuantity(BitSize / getCharWidth());
2169}
2170
Ken Dyckb0fcc592011-02-11 01:54:29 +00002171/// toBits - Convert a size in characters to a size in characters.
2172int64_t ASTContext::toBits(CharUnits CharSize) const {
2173 return CharSize.getQuantity() * getCharWidth();
2174}
2175
Ken Dyck8c89d592009-12-22 14:23:30 +00002176/// getTypeSizeInChars - Return the size of the specified type, in characters.
2177/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002178CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002179 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002180}
Jay Foad39c79802011-01-12 09:06:06 +00002181CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002182 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002183}
2184
Fangrui Song6907ce22018-07-30 19:24:48 +00002185/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002186/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002187CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002188 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002189}
Jay Foad39c79802011-01-12 09:06:06 +00002190CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002191 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002192}
2193
Momchil Velikov20208cc2018-07-30 17:48:23 +00002194/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2195/// type, in characters, before alignment adustments. This method does
2196/// not work on incomplete types.
2197CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2198 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2199}
2200CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2201 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2202}
2203
Chris Lattnera3402cd2009-01-27 18:08:34 +00002204/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2205/// type for the current target in bits. This can be different than the ABI
2206/// alignment in cases where it is beneficial for performance to overalign
2207/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002208unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002209 TypeInfo TI = getTypeInfo(T);
2210 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002211
David Majnemere1544562015-04-24 01:25:05 +00002212 T = T->getBaseElementTypeUnsafe();
2213
2214 // The preferred alignment of member pointers is that of a pointer.
2215 if (T->isMemberPointerType())
2216 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2217
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002218 if (!Target->allowsLargerPreferedTypeAlignment())
2219 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002220
Eli Friedman7ab09572009-05-25 21:27:19 +00002221 // Double and long long should be naturally aligned if possible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002222 if (const auto *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002223 T = CT->getElementType().getTypePtr();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002224 if (const auto *ET = T->getAs<EnumType>())
David Majnemer475b25e2015-01-21 10:54:38 +00002225 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002226 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002227 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2228 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002229 // Don't increase the alignment if an alignment attribute was specified on a
2230 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002231 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002232 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002233
Chris Lattnera3402cd2009-01-27 18:08:34 +00002234 return ABIAlign;
2235}
2236
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002237/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2238/// for __attribute__((aligned)) on this target, to be used if no alignment
2239/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002240unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002241 return getTargetInfo().getDefaultAlignForAttributeAligned();
2242}
2243
Ulrich Weigandfa806422013-05-06 16:23:57 +00002244/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2245/// to a global variable of the specified type.
2246unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
Tom Tanb7c6d952019-05-02 00:38:14 +00002247 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2248 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
Ulrich Weigandfa806422013-05-06 16:23:57 +00002249}
2250
2251/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2252/// should be given to a global variable of the specified type.
2253CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2254 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2255}
2256
David Majnemer08ef2ba2015-06-23 20:34:18 +00002257CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2258 CharUnits Offset = CharUnits::Zero();
2259 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2260 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2261 Offset += Layout->getBaseClassOffset(Base);
2262 Layout = &getASTRecordLayout(Base);
2263 }
2264 return Offset;
2265}
2266
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002267/// DeepCollectObjCIvars -
2268/// This routine first collects all declared, but not synthesized, ivars in
2269/// super class and then collects all ivars, including those synthesized for
2270/// current class. This routine is used for implementation of current class
2271/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002272void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2273 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002274 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002275 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2276 DeepCollectObjCIvars(SuperClass, false, Ivars);
2277 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002278 for (const auto *I : OI->ivars())
2279 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002280 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002281 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Fangrui Song6907ce22018-07-30 19:24:48 +00002282 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002283 Iv= Iv->getNextIvar())
2284 Ivars.push_back(Iv);
2285 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002286}
2287
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002288/// CollectInheritedProtocols - Collect all protocols in current class and
2289/// those inherited by it.
2290void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002291 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002292 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002293 // We can use protocol_iterator here instead of
Fangrui Song6907ce22018-07-30 19:24:48 +00002294 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002295 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002296 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002297 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002298
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002299 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002300 for (const auto *Cat : OI->visible_categories())
2301 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002302
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002303 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2304 while (SD) {
2305 CollectInheritedProtocols(SD, Protocols);
2306 SD = SD->getSuperClass();
2307 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002308 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002309 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002310 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002311 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002312 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002313 // Insert the protocol.
2314 if (!Protocols.insert(
2315 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2316 return;
2317
2318 for (auto *Proto : OP->protocols())
2319 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002320 }
2321}
2322
Erich Keane8a6b7402017-11-30 16:37:02 +00002323static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2324 const RecordDecl *RD) {
2325 assert(RD->isUnion() && "Must be union type");
2326 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2327
2328 for (const auto *Field : RD->fields()) {
2329 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2330 return false;
2331 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2332 if (FieldSize != UnionSize)
2333 return false;
2334 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002335 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002336}
2337
Benjamin Kramer802e6252017-12-24 12:46:22 +00002338static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002339 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2340
2341 if (!RD->field_empty())
2342 return false;
2343
2344 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2345 return ClassDecl->isEmpty();
2346
2347 return true;
2348}
2349
2350static llvm::Optional<int64_t>
2351structHasUniqueObjectRepresentations(const ASTContext &Context,
2352 const RecordDecl *RD) {
2353 assert(!RD->isUnion() && "Must be struct/class type");
2354 const auto &Layout = Context.getASTRecordLayout(RD);
2355
2356 int64_t CurOffsetInBits = 0;
2357 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2358 if (ClassDecl->isDynamicClass())
2359 return llvm::None;
2360
2361 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2362 for (const auto Base : ClassDecl->bases()) {
2363 // Empty types can be inherited from, and non-empty types can potentially
2364 // have tail padding, so just make sure there isn't an error.
2365 if (!isStructEmpty(Base.getType())) {
2366 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2367 Context, Base.getType()->getAs<RecordType>()->getDecl());
2368 if (!Size)
2369 return llvm::None;
2370 Bases.emplace_back(Base.getType(), Size.getValue());
2371 }
2372 }
2373
Fangrui Song1d38c132018-09-30 21:41:11 +00002374 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2375 const std::pair<QualType, int64_t> &R) {
2376 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2377 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2378 });
Erich Keane8a6b7402017-11-30 16:37:02 +00002379
2380 for (const auto Base : Bases) {
2381 int64_t BaseOffset = Context.toBits(
2382 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2383 int64_t BaseSize = Base.second;
2384 if (BaseOffset != CurOffsetInBits)
2385 return llvm::None;
2386 CurOffsetInBits = BaseOffset + BaseSize;
2387 }
2388 }
2389
2390 for (const auto *Field : RD->fields()) {
2391 if (!Field->getType()->isReferenceType() &&
2392 !Context.hasUniqueObjectRepresentations(Field->getType()))
2393 return llvm::None;
2394
2395 int64_t FieldSizeInBits =
2396 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2397 if (Field->isBitField()) {
2398 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2399
2400 if (BitfieldSize > FieldSizeInBits)
2401 return llvm::None;
2402 FieldSizeInBits = BitfieldSize;
2403 }
2404
2405 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2406
2407 if (FieldOffsetInBits != CurOffsetInBits)
2408 return llvm::None;
2409
2410 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2411 }
2412
2413 return CurOffsetInBits;
2414}
2415
2416bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2417 // C++17 [meta.unary.prop]:
2418 // The predicate condition for a template specialization
2419 // has_unique_object_representations<T> shall be
2420 // satisfied if and only if:
2421 // (9.1) - T is trivially copyable, and
2422 // (9.2) - any two objects of type T with the same value have the same
2423 // object representation, where two objects
2424 // of array or non-union class type are considered to have the same value
2425 // if their respective sequences of
2426 // direct subobjects have the same values, and two objects of union type
2427 // are considered to have the same
2428 // value if they have the same active member and the corresponding members
2429 // have the same value.
2430 // The set of scalar types for which this condition holds is
2431 // implementation-defined. [ Note: If a type has padding
2432 // bits, the condition does not hold; otherwise, the condition holds true
2433 // for unsigned integral types. -- end note ]
2434 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2435
2436 // Arrays are unique only if their element type is unique.
2437 if (Ty->isArrayType())
2438 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2439
2440 // (9.1) - T is trivially copyable...
2441 if (!Ty.isTriviallyCopyableType(*this))
2442 return false;
2443
2444 // All integrals and enums are unique.
2445 if (Ty->isIntegralOrEnumerationType())
2446 return true;
2447
2448 // All other pointers are unique.
2449 if (Ty->isPointerType())
2450 return true;
2451
2452 if (Ty->isMemberPointerType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002453 const auto *MPT = Ty->getAs<MemberPointerType>();
Erich Keane8a6b7402017-11-30 16:37:02 +00002454 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2455 }
2456
2457 if (Ty->isRecordType()) {
2458 const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
2459
Erich Keanebd2197c2017-12-12 16:02:06 +00002460 if (Record->isInvalidDecl())
2461 return false;
2462
Erich Keane8a6b7402017-11-30 16:37:02 +00002463 if (Record->isUnion())
2464 return unionHasUniqueObjectRepresentations(*this, Record);
2465
2466 Optional<int64_t> StructSize =
2467 structHasUniqueObjectRepresentations(*this, Record);
2468
2469 return StructSize &&
2470 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2471 }
2472
2473 // FIXME: More cases to handle here (list by rsmith):
2474 // vectors (careful about, eg, vector of 3 foo)
2475 // _Complex int and friends
2476 // _Atomic T
2477 // Obj-C block pointers
2478 // Obj-C object pointers
2479 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2480 // clk_event_t, queue_t, reserve_id_t)
2481 // There're also Obj-C class types and the Obj-C selector type, but I think it
2482 // makes sense for those to return false here.
2483
2484 return false;
2485}
2486
Jay Foad39c79802011-01-12 09:06:06 +00002487unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002488 unsigned count = 0;
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002489 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002490 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002491 count += Ext->ivar_size();
Fangrui Song6907ce22018-07-30 19:24:48 +00002492
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002493 // Count ivar defined in this class's implementation. This
2494 // includes synthesized ivars.
2495 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002496 count += ImplDecl->ivar_size();
2497
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002498 return count;
2499}
2500
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002501bool ASTContext::isSentinelNullExpr(const Expr *E) {
2502 if (!E)
2503 return false;
2504
2505 // nullptr_t is always treated as null.
2506 if (E->getType()->isNullPtrType()) return true;
2507
2508 if (E->getType()->isAnyPointerType() &&
2509 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2510 Expr::NPC_ValueDependentIsNull))
2511 return true;
2512
2513 // Unfortunately, __null has type 'int'.
2514 if (isa<GNUNullExpr>(E)) return true;
2515
2516 return false;
2517}
2518
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002519/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002520/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002521ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2522 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2523 I = ObjCImpls.find(D);
2524 if (I != ObjCImpls.end())
2525 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002526 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002527}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002528
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002529/// Get the implementation of ObjCCategoryDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002530/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002531ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2532 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2533 I = ObjCImpls.find(D);
2534 if (I != ObjCImpls.end())
2535 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002536 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002537}
2538
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002539/// Set the implementation of ObjCInterfaceDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002540void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2541 ObjCImplementationDecl *ImplD) {
2542 assert(IFaceD && ImplD && "Passed null params");
2543 ObjCImpls[IFaceD] = ImplD;
2544}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002545
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002546/// Set the implementation of ObjCCategoryDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002547void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2548 ObjCCategoryImplDecl *ImplD) {
2549 assert(CatD && ImplD && "Passed null params");
2550 ObjCImpls[CatD] = ImplD;
2551}
2552
Chandler Carruth21c90602015-12-30 03:24:14 +00002553const ObjCMethodDecl *
2554ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2555 return ObjCMethodRedecls.lookup(MD);
2556}
2557
2558void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2559 const ObjCMethodDecl *Redecl) {
2560 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2561 ObjCMethodRedecls[MD] = Redecl;
2562}
2563
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002564const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2565 const NamedDecl *ND) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002566 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002567 return ID;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002568 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002569 return CD->getClassInterface();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002570 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002571 return IMD->getClassInterface();
2572
Craig Topper36250ad2014-05-12 05:36:57 +00002573 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002574}
2575
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002576/// Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002577/// none exists.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002578ASTContext::BlockVarCopyInit
2579ASTContext::getBlockVarCopyInit(const VarDecl*VD) const {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002580 assert(VD && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002581 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002582 "getBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002583 auto I = BlockVarCopyInits.find(VD);
2584 if (I != BlockVarCopyInits.end())
2585 return I->second;
2586 return {nullptr, false};
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002587}
2588
JF Bastien0d702a72019-04-30 00:11:53 +00002589/// Set the copy initialization expression of a block var decl.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002590void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2591 bool CanThrow) {
2592 assert(VD && CopyExpr && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002593 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002594 "setBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002595 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002596}
2597
John McCallbcd03502009-12-07 02:54:59 +00002598TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002599 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002600 if (!DataSize)
2601 DataSize = TypeLoc::getFullDataSizeForType(T);
2602 else
2603 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002604 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002605
Eugene Zelenko7855e772018-04-03 00:11:50 +00002606 auto *TInfo =
John McCallbcd03502009-12-07 02:54:59 +00002607 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2608 new (TInfo) TypeSourceInfo(T);
2609 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002610}
2611
John McCallbcd03502009-12-07 02:54:59 +00002612TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002613 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002614 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002615 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002616 return DI;
2617}
2618
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002619const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002620ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002621 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002622}
2623
2624const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002625ASTContext::getASTObjCImplementationLayout(
2626 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002627 return getObjCLayout(D->getClassInterface(), D);
2628}
2629
Chris Lattner983a8bb2007-07-13 22:13:22 +00002630//===----------------------------------------------------------------------===//
2631// Type creation/memoization methods
2632//===----------------------------------------------------------------------===//
2633
Jay Foad39c79802011-01-12 09:06:06 +00002634QualType
John McCall33ddac02011-01-19 10:06:00 +00002635ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2636 unsigned fastQuals = quals.getFastQualifiers();
2637 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002638
2639 // Check if we've already instantiated this type.
2640 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002641 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002642 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002643 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2644 assert(eq->getQualifiers() == quals);
2645 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002646 }
2647
John McCall33ddac02011-01-19 10:06:00 +00002648 // If the base type is not canonical, make the appropriate canonical type.
2649 QualType canon;
2650 if (!baseType->isCanonicalUnqualified()) {
2651 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002652 canonSplit.Quals.addConsistentQualifiers(quals);
2653 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002654
2655 // Re-find the insert position.
2656 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2657 }
2658
Eugene Zelenko7855e772018-04-03 00:11:50 +00002659 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
John McCall33ddac02011-01-19 10:06:00 +00002660 ExtQualNodes.InsertNode(eq, insertPos);
2661 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002662}
2663
Alexander Richardson6d989432017-10-15 18:48:14 +00002664QualType ASTContext::getAddrSpaceQualType(QualType T,
2665 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002666 QualType CanT = getCanonicalType(T);
2667 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002668 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002669
John McCall8ccfcb52009-09-24 19:53:00 +00002670 // If we are composing extended qualifiers together, merge together
2671 // into one ExtQuals node.
2672 QualifierCollector Quals;
2673 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002674
John McCall8ccfcb52009-09-24 19:53:00 +00002675 // If this type already has an address space specified, it cannot get
2676 // another one.
2677 assert(!Quals.hasAddressSpace() &&
2678 "Type cannot be in multiple addr spaces!");
2679 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002680
John McCall8ccfcb52009-09-24 19:53:00 +00002681 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002682}
2683
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002684QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2685 // If we are composing extended qualifiers together, merge together
2686 // into one ExtQuals node.
2687 QualifierCollector Quals;
2688 const Type *TypeNode = Quals.strip(T);
2689
2690 // If the qualifier doesn't have an address space just return it.
2691 if (!Quals.hasAddressSpace())
2692 return T;
2693
2694 Quals.removeAddressSpace();
2695
2696 // Removal of the address space can mean there are no longer any
2697 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2698 // or required.
2699 if (Quals.hasNonFastQualifiers())
2700 return getExtQualType(TypeNode, Quals);
2701 else
2702 return QualType(TypeNode, Quals.getFastQualifiers());
2703}
2704
Chris Lattnerd60183d2009-02-18 22:53:11 +00002705QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002706 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002707 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002708 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002709 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002710
Eugene Zelenko7855e772018-04-03 00:11:50 +00002711 if (const auto *ptr = T->getAs<PointerType>()) {
John McCall53fa7142010-12-24 02:08:15 +00002712 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002713 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002714 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2715 return getPointerType(ResultType);
2716 }
2717 }
Mike Stump11289f42009-09-09 15:08:12 +00002718
John McCall8ccfcb52009-09-24 19:53:00 +00002719 // If we are composing extended qualifiers together, merge together
2720 // into one ExtQuals node.
2721 QualifierCollector Quals;
2722 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002723
John McCall8ccfcb52009-09-24 19:53:00 +00002724 // If this type already has an ObjCGC specified, it cannot get
2725 // another one.
2726 assert(!Quals.hasObjCGCAttr() &&
2727 "Type cannot have multiple ObjCGCs!");
2728 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002729
John McCall8ccfcb52009-09-24 19:53:00 +00002730 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002731}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002732
John McCall4f5019e2010-12-19 02:44:49 +00002733const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2734 FunctionType::ExtInfo Info) {
2735 if (T->getExtInfo() == Info)
2736 return T;
2737
2738 QualType Result;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002739 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002740 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002741 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002742 const auto *FPT = cast<FunctionProtoType>(T);
John McCall4f5019e2010-12-19 02:44:49 +00002743 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2744 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002745 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002746 }
2747
2748 return cast<FunctionType>(Result.getTypePtr());
2749}
2750
Richard Smith2a7d4812013-05-04 07:00:32 +00002751void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2752 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002753 FD = FD->getMostRecentDecl();
2754 while (true) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002755 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smith2a7d4812013-05-04 07:00:32 +00002756 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002757 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002758 if (FunctionDecl *Next = FD->getPreviousDecl())
2759 FD = Next;
2760 else
2761 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002762 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002763 if (ASTMutationListener *L = getASTMutationListener())
2764 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002765}
2766
Richard Smith0b3a4622014-11-13 20:01:57 +00002767/// Get a function type and produce the equivalent function type with the
2768/// specified exception specification. Type sugar that can be present on a
2769/// declaration of a function with an exception specification is permitted
2770/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002771QualType ASTContext::getFunctionTypeWithExceptionSpec(
2772 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002773 // Might have some parens.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002774 if (const auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002775 return getParenType(
2776 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002777
Leonard Chandc5d9752019-05-10 18:05:15 +00002778 // Might be wrapped in a macro qualified type.
2779 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
2780 return getMacroQualifiedType(
2781 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
2782 MQT->getMacroIdentifier());
2783
Richard Smith0b3a4622014-11-13 20:01:57 +00002784 // Might have a calling-convention attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002785 if (const auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002786 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002787 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002788 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2789 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002790
2791 // Anything else must be a function type. Rebuild it with the new exception
2792 // specification.
Stephan Bergmann84dcc8f2019-02-13 09:39:17 +00002793 const auto *Proto = Orig->getAs<FunctionProtoType>();
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002794 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002795 Proto->getReturnType(), Proto->getParamTypes(),
2796 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2797}
2798
Richard Smithdfe85e22016-12-15 02:35:39 +00002799bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2800 QualType U) {
2801 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002802 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002803 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2804 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002805}
2806
Richard Smith0b3a4622014-11-13 20:01:57 +00002807void ASTContext::adjustExceptionSpec(
2808 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2809 bool AsWritten) {
2810 // Update the type.
2811 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002812 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002813 FD->setType(Updated);
2814
2815 if (!AsWritten)
2816 return;
2817
2818 // Update the type in the type source information too.
2819 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2820 // If the type and the type-as-written differ, we may need to update
2821 // the type-as-written too.
2822 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002823 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002824
2825 // FIXME: When we get proper type location information for exceptions,
2826 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2827 // up the TypeSourceInfo;
2828 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2829 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2830 "TypeLoc size mismatch from updating exception specification");
2831 TSInfo->overrideType(Updated);
2832 }
2833}
2834
Chris Lattnerc6395932007-06-22 20:56:16 +00002835/// getComplexType - Return the uniqued reference to the type for a complex
2836/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002837QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002838 // Unique pointers, to guarantee there is only one pointer of a particular
2839 // structure.
2840 llvm::FoldingSetNodeID ID;
2841 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002842
Craig Topper36250ad2014-05-12 05:36:57 +00002843 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002844 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2845 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002846
Chris Lattnerc6395932007-06-22 20:56:16 +00002847 // If the pointee type isn't canonical, this won't be a canonical type either,
2848 // so fill in the canonical type field.
2849 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002850 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002851 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002852
Chris Lattnerc6395932007-06-22 20:56:16 +00002853 // Get the new insert position for the node we care about.
2854 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002855 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002856 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002857 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002858 Types.push_back(New);
2859 ComplexTypes.InsertNode(New, InsertPos);
2860 return QualType(New, 0);
2861}
2862
Chris Lattner970e54e2006-11-12 00:37:36 +00002863/// getPointerType - Return the uniqued reference to the type for a pointer to
2864/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002865QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002866 // Unique pointers, to guarantee there is only one pointer of a particular
2867 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002868 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002869 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002870
Craig Topper36250ad2014-05-12 05:36:57 +00002871 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002872 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002873 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002874
Chris Lattner7ccecb92006-11-12 08:50:50 +00002875 // If the pointee type isn't canonical, this won't be a canonical type either,
2876 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002877 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002878 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002879 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002880
Bob Wilsonc8541f22013-03-15 17:12:43 +00002881 // Get the new insert position for the node we care about.
2882 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002883 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002884 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002885 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002886 Types.push_back(New);
2887 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002888 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002889}
2890
Reid Kleckner0503a872013-12-05 01:23:43 +00002891QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2892 llvm::FoldingSetNodeID ID;
2893 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002894 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002895 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2896 if (AT)
2897 return QualType(AT, 0);
2898
2899 QualType Canonical = getCanonicalType(New);
2900
2901 // Get the new insert position for the node we care about.
2902 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002903 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002904
2905 AT = new (*this, TypeAlignment)
2906 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2907 Types.push_back(AT);
2908 AdjustedTypes.InsertNode(AT, InsertPos);
2909 return QualType(AT, 0);
2910}
2911
Reid Kleckner8a365022013-06-24 17:51:48 +00002912QualType ASTContext::getDecayedType(QualType T) const {
2913 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2914
Reid Kleckner8a365022013-06-24 17:51:48 +00002915 QualType Decayed;
2916
2917 // C99 6.7.5.3p7:
2918 // A declaration of a parameter as "array of type" shall be
2919 // adjusted to "qualified pointer to type", where the type
2920 // qualifiers (if any) are those specified within the [ and ] of
2921 // the array type derivation.
2922 if (T->isArrayType())
2923 Decayed = getArrayDecayedType(T);
2924
2925 // C99 6.7.5.3p8:
2926 // A declaration of a parameter as "function returning type"
2927 // shall be adjusted to "pointer to function returning type", as
2928 // in 6.3.2.1.
2929 if (T->isFunctionType())
2930 Decayed = getPointerType(T);
2931
Reid Kleckner0503a872013-12-05 01:23:43 +00002932 llvm::FoldingSetNodeID ID;
2933 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002934 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002935 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2936 if (AT)
2937 return QualType(AT, 0);
2938
Reid Kleckner8a365022013-06-24 17:51:48 +00002939 QualType Canonical = getCanonicalType(Decayed);
2940
2941 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002942 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002943 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002944
Reid Kleckner0503a872013-12-05 01:23:43 +00002945 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2946 Types.push_back(AT);
2947 AdjustedTypes.InsertNode(AT, InsertPos);
2948 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002949}
2950
Mike Stump11289f42009-09-09 15:08:12 +00002951/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002952/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002953QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002954 assert(T->isFunctionType() && "block of function types only");
2955 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002956 // structure.
2957 llvm::FoldingSetNodeID ID;
2958 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002959
Craig Topper36250ad2014-05-12 05:36:57 +00002960 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002961 if (BlockPointerType *PT =
2962 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2963 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002964
2965 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002966 // type either so fill in the canonical type field.
2967 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002968 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002969 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002970
Steve Naroffec33ed92008-08-27 16:04:49 +00002971 // Get the new insert position for the node we care about.
2972 BlockPointerType *NewIP =
2973 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002974 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002975 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002976 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002977 Types.push_back(New);
2978 BlockPointerTypes.InsertNode(New, InsertPos);
2979 return QualType(New, 0);
2980}
2981
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002982/// getLValueReferenceType - Return the uniqued reference to the type for an
2983/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002984QualType
2985ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002986 assert(getCanonicalType(T) != OverloadTy &&
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002987 "Unresolved overloaded function type");
Fangrui Song6907ce22018-07-30 19:24:48 +00002988
Bill Wendling3708c182007-05-27 10:15:43 +00002989 // Unique pointers, to guarantee there is only one pointer of a particular
2990 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002991 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002992 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002993
Craig Topper36250ad2014-05-12 05:36:57 +00002994 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002995 if (LValueReferenceType *RT =
2996 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002997 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002998
Eugene Zelenko7855e772018-04-03 00:11:50 +00002999 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003000
Bill Wendling3708c182007-05-27 10:15:43 +00003001 // If the referencee type isn't canonical, this won't be a canonical type
3002 // either, so fill in the canonical type field.
3003 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003004 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3005 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3006 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003007
Bill Wendling3708c182007-05-27 10:15:43 +00003008 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003009 LValueReferenceType *NewIP =
3010 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003011 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00003012 }
3013
Eugene Zelenko7855e772018-04-03 00:11:50 +00003014 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3015 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00003016 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003017 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00003018
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003019 return QualType(New, 0);
3020}
3021
3022/// getRValueReferenceType - Return the uniqued reference to the type for an
3023/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00003024QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003025 // Unique pointers, to guarantee there is only one pointer of a particular
3026 // structure.
3027 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00003028 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003029
Craig Topper36250ad2014-05-12 05:36:57 +00003030 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003031 if (RValueReferenceType *RT =
3032 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3033 return QualType(RT, 0);
3034
Eugene Zelenko7855e772018-04-03 00:11:50 +00003035 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003036
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003037 // If the referencee type isn't canonical, this won't be a canonical type
3038 // either, so fill in the canonical type field.
3039 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003040 if (InnerRef || !T.isCanonical()) {
3041 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3042 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003043
3044 // Get the new insert position for the node we care about.
3045 RValueReferenceType *NewIP =
3046 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003047 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003048 }
3049
Eugene Zelenko7855e772018-04-03 00:11:50 +00003050 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003051 Types.push_back(New);
3052 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00003053 return QualType(New, 0);
3054}
3055
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003056/// getMemberPointerType - Return the uniqued reference to the type for a
3057/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00003058QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003059 // Unique pointers, to guarantee there is only one pointer of a particular
3060 // structure.
3061 llvm::FoldingSetNodeID ID;
3062 MemberPointerType::Profile(ID, T, Cls);
3063
Craig Topper36250ad2014-05-12 05:36:57 +00003064 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003065 if (MemberPointerType *PT =
3066 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3067 return QualType(PT, 0);
3068
3069 // If the pointee or class type isn't canonical, this won't be a canonical
3070 // type either, so fill in the canonical type field.
3071 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00003072 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003073 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3074
3075 // Get the new insert position for the node we care about.
3076 MemberPointerType *NewIP =
3077 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003078 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003079 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003080 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003081 Types.push_back(New);
3082 MemberPointerTypes.InsertNode(New, InsertPos);
3083 return QualType(New, 0);
3084}
3085
Mike Stump11289f42009-09-09 15:08:12 +00003086/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00003087/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00003088QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00003089 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003090 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003091 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00003092 assert((EltTy->isDependentType() ||
3093 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00003094 "Constant array of VLAs is illegal!");
3095
Chris Lattnere2df3f92009-05-13 04:12:56 +00003096 // Convert the array size into a canonical width matching the pointer size for
3097 // the target.
3098 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00003099 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00003100
Chris Lattner23b7eb62007-06-15 23:05:46 +00003101 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00003102 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00003103
Craig Topper36250ad2014-05-12 05:36:57 +00003104 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003105 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003106 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003107 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003108
John McCall33ddac02011-01-19 10:06:00 +00003109 // If the element type isn't canonical or has qualifiers, this won't
3110 // be a canonical type either, so fill in the canonical type field.
3111 QualType Canon;
3112 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3113 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003114 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003115 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003116 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003117
Chris Lattner36f8e652007-01-27 08:31:04 +00003118 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00003119 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003120 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003121 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00003122 }
Mike Stump11289f42009-09-09 15:08:12 +00003123
Eugene Zelenko7855e772018-04-03 00:11:50 +00003124 auto *New = new (*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003125 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00003126 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00003127 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003128 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00003129}
3130
John McCall06549462011-01-18 08:40:38 +00003131/// getVariableArrayDecayedType - Turns the given type, which may be
3132/// variably-modified, into the corresponding type with all the known
3133/// sizes replaced with [*].
3134QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3135 // Vastly most common case.
3136 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003137
John McCall06549462011-01-18 08:40:38 +00003138 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003139
John McCall06549462011-01-18 08:40:38 +00003140 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003141 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00003142 switch (ty->getTypeClass()) {
3143#define TYPE(Class, Base)
3144#define ABSTRACT_TYPE(Class, Base)
3145#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3146#include "clang/AST/TypeNodes.def"
3147 llvm_unreachable("didn't desugar past all non-canonical types?");
3148
3149 // These types should never be variably-modified.
3150 case Type::Builtin:
3151 case Type::Complex:
3152 case Type::Vector:
Erich Keanef702b022018-07-13 19:46:04 +00003153 case Type::DependentVector:
John McCall06549462011-01-18 08:40:38 +00003154 case Type::ExtVector:
3155 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003156 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00003157 case Type::ObjCObject:
3158 case Type::ObjCInterface:
3159 case Type::ObjCObjectPointer:
3160 case Type::Record:
3161 case Type::Enum:
3162 case Type::UnresolvedUsing:
3163 case Type::TypeOfExpr:
3164 case Type::TypeOf:
3165 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00003166 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00003167 case Type::DependentName:
3168 case Type::InjectedClassName:
3169 case Type::TemplateSpecialization:
3170 case Type::DependentTemplateSpecialization:
3171 case Type::TemplateTypeParm:
3172 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00003173 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003174 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00003175 case Type::PackExpansion:
3176 llvm_unreachable("type should never be variably-modified");
3177
3178 // These types can be variably-modified but should never need to
3179 // further decay.
3180 case Type::FunctionNoProto:
3181 case Type::FunctionProto:
3182 case Type::BlockPointer:
3183 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00003184 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00003185 return type;
3186
3187 // These types can be variably-modified. All these modifications
3188 // preserve structure except as noted by comments.
3189 // TODO: if we ever care about optimizing VLAs, there are no-op
3190 // optimizations available here.
3191 case Type::Pointer:
3192 result = getPointerType(getVariableArrayDecayedType(
3193 cast<PointerType>(ty)->getPointeeType()));
3194 break;
3195
3196 case Type::LValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003197 const auto *lv = cast<LValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003198 result = getLValueReferenceType(
3199 getVariableArrayDecayedType(lv->getPointeeType()),
3200 lv->isSpelledAsLValue());
3201 break;
3202 }
3203
3204 case Type::RValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003205 const auto *lv = cast<RValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003206 result = getRValueReferenceType(
3207 getVariableArrayDecayedType(lv->getPointeeType()));
3208 break;
3209 }
3210
Eli Friedman0dfb8892011-10-06 23:00:33 +00003211 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003212 const auto *at = cast<AtomicType>(ty);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003213 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3214 break;
3215 }
3216
John McCall06549462011-01-18 08:40:38 +00003217 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003218 const auto *cat = cast<ConstantArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003219 result = getConstantArrayType(
3220 getVariableArrayDecayedType(cat->getElementType()),
3221 cat->getSize(),
3222 cat->getSizeModifier(),
3223 cat->getIndexTypeCVRQualifiers());
3224 break;
3225 }
3226
3227 case Type::DependentSizedArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003228 const auto *dat = cast<DependentSizedArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003229 result = getDependentSizedArrayType(
3230 getVariableArrayDecayedType(dat->getElementType()),
3231 dat->getSizeExpr(),
3232 dat->getSizeModifier(),
3233 dat->getIndexTypeCVRQualifiers(),
3234 dat->getBracketsRange());
3235 break;
3236 }
3237
3238 // Turn incomplete types into [*] types.
3239 case Type::IncompleteArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003240 const auto *iat = cast<IncompleteArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003241 result = getVariableArrayType(
3242 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003243 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003244 ArrayType::Normal,
3245 iat->getIndexTypeCVRQualifiers(),
3246 SourceRange());
3247 break;
3248 }
3249
3250 // Turn VLA types into [*] types.
3251 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003252 const auto *vat = cast<VariableArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003253 result = getVariableArrayType(
3254 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003255 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003256 ArrayType::Star,
3257 vat->getIndexTypeCVRQualifiers(),
3258 vat->getBracketsRange());
3259 break;
3260 }
3261 }
3262
3263 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003264 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003265}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003266
Steve Naroffcadebd02007-08-30 18:14:25 +00003267/// getVariableArrayType - Returns a non-unique reference to the type for a
3268/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003269QualType ASTContext::getVariableArrayType(QualType EltTy,
3270 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003271 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003272 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003273 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003274 // Since we don't unique expressions, it isn't possible to unique VLA's
3275 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003276 QualType Canon;
Fangrui Song6907ce22018-07-30 19:24:48 +00003277
John McCall33ddac02011-01-19 10:06:00 +00003278 // Be sure to pull qualifiers off the element type.
3279 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3280 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003281 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003282 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003283 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003284 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003285
Eugene Zelenko7855e772018-04-03 00:11:50 +00003286 auto *New = new (*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003287 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003288
3289 VariableArrayTypes.push_back(New);
3290 Types.push_back(New);
3291 return QualType(New, 0);
3292}
3293
Douglas Gregor4619e432008-12-05 23:32:09 +00003294/// getDependentSizedArrayType - Returns a non-unique reference to
3295/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003296/// type.
John McCall33ddac02011-01-19 10:06:00 +00003297QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3298 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003299 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003300 unsigned elementTypeQuals,
3301 SourceRange brackets) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003302 assert((!numElements || numElements->isTypeDependent() ||
John McCall33ddac02011-01-19 10:06:00 +00003303 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003304 "Size must be type- or value-dependent!");
3305
John McCall33ddac02011-01-19 10:06:00 +00003306 // Dependently-sized array types that do not have a specified number
3307 // of elements will have their sizes deduced from a dependent
3308 // initializer. We do no canonicalization here at all, which is okay
3309 // because they can't be used in most locations.
3310 if (!numElements) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003311 auto *newType
John McCall33ddac02011-01-19 10:06:00 +00003312 = new (*this, TypeAlignment)
3313 DependentSizedArrayType(*this, elementType, QualType(),
3314 numElements, ASM, elementTypeQuals,
3315 brackets);
3316 Types.push_back(newType);
3317 return QualType(newType, 0);
3318 }
3319
3320 // Otherwise, we actually build a new type every time, but we
3321 // also build a canonical type.
3322
3323 SplitQualType canonElementType = getCanonicalType(elementType).split();
3324
Craig Topper36250ad2014-05-12 05:36:57 +00003325 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003326 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003327 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003328 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003329 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003330
John McCall33ddac02011-01-19 10:06:00 +00003331 // Look for an existing type with these properties.
3332 DependentSizedArrayType *canonTy =
3333 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003334
John McCall33ddac02011-01-19 10:06:00 +00003335 // If we don't have one, build one.
3336 if (!canonTy) {
3337 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003338 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003339 QualType(), numElements, ASM, elementTypeQuals,
3340 brackets);
3341 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3342 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003343 }
3344
John McCall33ddac02011-01-19 10:06:00 +00003345 // Apply qualifiers from the element type to the array.
3346 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003347 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003348
David Majnemer16a74702015-07-24 05:54:19 +00003349 // If we didn't need extra canonicalization for the element type or the size
3350 // expression, then just use that as our result.
3351 if (QualType(canonElementType.Ty, 0) == elementType &&
3352 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003353 return canon;
3354
3355 // Otherwise, we need to build a type which follows the spelling
3356 // of the element type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00003357 auto *sugaredType
John McCall33ddac02011-01-19 10:06:00 +00003358 = new (*this, TypeAlignment)
3359 DependentSizedArrayType(*this, elementType, canon, numElements,
3360 ASM, elementTypeQuals, brackets);
3361 Types.push_back(sugaredType);
3362 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003363}
3364
John McCall33ddac02011-01-19 10:06:00 +00003365QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003366 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003367 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003368 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003369 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003370
Craig Topper36250ad2014-05-12 05:36:57 +00003371 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003372 if (IncompleteArrayType *iat =
3373 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3374 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003375
3376 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003377 // either, so fill in the canonical type field. We also have to pull
3378 // qualifiers off the element type.
3379 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003380
John McCall33ddac02011-01-19 10:06:00 +00003381 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3382 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003383 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003384 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003385 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003386
3387 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003388 IncompleteArrayType *existing =
3389 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3390 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003391 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003392
Eugene Zelenko7855e772018-04-03 00:11:50 +00003393 auto *newType = new (*this, TypeAlignment)
John McCall33ddac02011-01-19 10:06:00 +00003394 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003395
John McCall33ddac02011-01-19 10:06:00 +00003396 IncompleteArrayTypes.InsertNode(newType, insertPos);
3397 Types.push_back(newType);
3398 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003399}
3400
Steve Naroff91fcddb2007-07-18 18:00:27 +00003401/// getVectorType - Return the unique reference to a vector type of
3402/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003403QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003404 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003405 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003406
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003407 // Check if we've already instantiated a vector of this type.
3408 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003409 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003410
Craig Topper36250ad2014-05-12 05:36:57 +00003411 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003412 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3413 return QualType(VTP, 0);
3414
3415 // If the element type isn't canonical, this won't be a canonical type either,
3416 // so fill in the canonical type field.
3417 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003418 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003419 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003420
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003421 // Get the new insert position for the node we care about.
3422 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003423 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003424 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003425 auto *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003426 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003427 VectorTypes.InsertNode(New, InsertPos);
3428 Types.push_back(New);
3429 return QualType(New, 0);
3430}
3431
Erich Keanef702b022018-07-13 19:46:04 +00003432QualType
3433ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3434 SourceLocation AttrLoc,
3435 VectorType::VectorKind VecKind) const {
3436 llvm::FoldingSetNodeID ID;
3437 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3438 VecKind);
3439 void *InsertPos = nullptr;
3440 DependentVectorType *Canon =
3441 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3442 DependentVectorType *New;
3443
3444 if (Canon) {
3445 New = new (*this, TypeAlignment) DependentVectorType(
3446 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3447 } else {
3448 QualType CanonVecTy = getCanonicalType(VecType);
3449 if (CanonVecTy == VecType) {
3450 New = new (*this, TypeAlignment) DependentVectorType(
3451 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3452
3453 DependentVectorType *CanonCheck =
3454 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3455 assert(!CanonCheck &&
3456 "Dependent-sized vector_size canonical type broken");
3457 (void)CanonCheck;
3458 DependentVectorTypes.InsertNode(New, InsertPos);
3459 } else {
3460 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3461 SourceLocation());
3462 New = new (*this, TypeAlignment) DependentVectorType(
3463 *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
3464 }
3465 }
3466
3467 Types.push_back(New);
3468 return QualType(New, 0);
3469}
3470
Nate Begemance4d7fc2008-04-18 23:10:10 +00003471/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003472/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003473QualType
3474ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003475 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003476
Steve Naroff91fcddb2007-07-18 18:00:27 +00003477 // Check if we've already instantiated a vector of this type.
3478 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003479 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003480 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003481 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003482 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3483 return QualType(VTP, 0);
3484
3485 // If the element type isn't canonical, this won't be a canonical type either,
3486 // so fill in the canonical type field.
3487 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003488 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003489 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003490
Steve Naroff91fcddb2007-07-18 18:00:27 +00003491 // Get the new insert position for the node we care about.
3492 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003493 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003494 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003495 auto *New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003496 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003497 VectorTypes.InsertNode(New, InsertPos);
3498 Types.push_back(New);
3499 return QualType(New, 0);
3500}
3501
Jay Foad39c79802011-01-12 09:06:06 +00003502QualType
3503ASTContext::getDependentSizedExtVectorType(QualType vecType,
3504 Expr *SizeExpr,
3505 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003506 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003507 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003508 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003509
Craig Topper36250ad2014-05-12 05:36:57 +00003510 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003511 DependentSizedExtVectorType *Canon
3512 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3513 DependentSizedExtVectorType *New;
3514 if (Canon) {
3515 // We already have a canonical version of this array type; use it as
3516 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003517 New = new (*this, TypeAlignment)
3518 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3519 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003520 } else {
3521 QualType CanonVecTy = getCanonicalType(vecType);
3522 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003523 New = new (*this, TypeAlignment)
3524 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3525 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003526
3527 DependentSizedExtVectorType *CanonCheck
3528 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3529 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3530 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003531 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3532 } else {
3533 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3534 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003535 New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003536 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003537 }
3538 }
Mike Stump11289f42009-09-09 15:08:12 +00003539
Douglas Gregor758a8692009-06-17 21:51:59 +00003540 Types.push_back(New);
3541 return QualType(New, 0);
3542}
3543
Fangrui Song6907ce22018-07-30 19:24:48 +00003544QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3545 Expr *AddrSpaceExpr,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003546 SourceLocation AttrLoc) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003547 assert(AddrSpaceExpr->isInstantiationDependent());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003548
3549 QualType canonPointeeType = getCanonicalType(PointeeType);
3550
3551 void *insertPos = nullptr;
3552 llvm::FoldingSetNodeID ID;
3553 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3554 AddrSpaceExpr);
3555
3556 DependentAddressSpaceType *canonTy =
3557 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3558
3559 if (!canonTy) {
3560 canonTy = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003561 DependentAddressSpaceType(*this, canonPointeeType,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003562 QualType(), AddrSpaceExpr, AttrLoc);
3563 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3564 Types.push_back(canonTy);
3565 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003566
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003567 if (canonPointeeType == PointeeType &&
3568 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
Fangrui Song6907ce22018-07-30 19:24:48 +00003569 return QualType(canonTy, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003570
Eugene Zelenko7855e772018-04-03 00:11:50 +00003571 auto *sugaredType
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003572 = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003573 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003574 AddrSpaceExpr, AttrLoc);
3575 Types.push_back(sugaredType);
Fangrui Song6907ce22018-07-30 19:24:48 +00003576 return QualType(sugaredType, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003577}
3578
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003579/// Determine whether \p T is canonical as the result type of a function.
John McCall18afab72016-03-01 00:49:02 +00003580static bool isCanonicalResultType(QualType T) {
3581 return T.isCanonical() &&
3582 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3583 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3584}
3585
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003586/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003587QualType
3588ASTContext::getFunctionNoProtoType(QualType ResultTy,
3589 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003590 // Unique functions, to guarantee there is only one function of a particular
3591 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003592 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003593 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003594
Craig Topper36250ad2014-05-12 05:36:57 +00003595 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003596 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003597 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003598 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003599
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003600 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003601 if (!isCanonicalResultType(ResultTy)) {
3602 Canonical =
3603 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003604
Chris Lattner47955de2007-01-27 08:37:20 +00003605 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003606 FunctionNoProtoType *NewIP =
3607 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003608 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003609 }
Mike Stump11289f42009-09-09 15:08:12 +00003610
Eugene Zelenko7855e772018-04-03 00:11:50 +00003611 auto *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003612 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003613 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003614 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003615 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003616}
3617
Douglas Gregora602a152015-10-01 20:20:47 +00003618CanQualType
3619ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3620 CanQualType CanResultType = getCanonicalType(ResultType);
3621
3622 // Canonical result types do not have ARC lifetime qualifiers.
3623 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3624 Qualifiers Qs = CanResultType.getQualifiers();
3625 Qs.removeObjCLifetime();
3626 return CanQualType::CreateUnsafe(
3627 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3628 }
3629
3630 return CanResultType;
3631}
3632
Richard Smith3c4f8d22016-10-16 17:54:23 +00003633static bool isCanonicalExceptionSpecification(
3634 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3635 if (ESI.Type == EST_None)
3636 return true;
3637 if (!NoexceptInType)
3638 return false;
3639
3640 // C++17 onwards: exception specification is part of the type, as a simple
3641 // boolean "can this function type throw".
3642 if (ESI.Type == EST_BasicNoexcept)
3643 return true;
3644
Richard Smitheaf11ad2018-05-03 03:58:32 +00003645 // A noexcept(expr) specification is (possibly) canonical if expr is
3646 // value-dependent.
3647 if (ESI.Type == EST_DependentNoexcept)
3648 return true;
3649
Richard Smith3c4f8d22016-10-16 17:54:23 +00003650 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003651 // expansions (so we can't tell whether it's non-throwing) and all its
3652 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003653 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003654 bool AnyPackExpansions = false;
3655 for (QualType ET : ESI.Exceptions) {
3656 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003657 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003658 if (ET->getAs<PackExpansionType>())
3659 AnyPackExpansions = true;
3660 }
3661 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003662 }
3663
Richard Smith3c4f8d22016-10-16 17:54:23 +00003664 return false;
3665}
3666
Richard Smith304b1242016-10-18 20:13:25 +00003667QualType ASTContext::getFunctionTypeInternal(
3668 QualType ResultTy, ArrayRef<QualType> ArgArray,
3669 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003670 size_t NumArgs = ArgArray.size();
3671
Richard Smith2a2cda52016-10-18 19:29:18 +00003672 // Unique functions, to guarantee there is only one function of a particular
3673 // structure.
3674 llvm::FoldingSetNodeID ID;
3675 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3676 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003677
Richard Smith2a2cda52016-10-18 19:29:18 +00003678 QualType Canonical;
3679 bool Unique = false;
3680
3681 void *InsertPos = nullptr;
3682 if (FunctionProtoType *FPT =
3683 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3684 QualType Existing = QualType(FPT, 0);
3685
3686 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3687 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003688 // noexcept expression, or we're just looking for a canonical type.
3689 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003690 // sugar node to hold the concrete expression.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003691 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003692 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3693 return Existing;
3694
3695 // We need a new type sugar node for this one, to hold the new noexcept
3696 // expression. We do no canonicalization here, but that's OK since we don't
3697 // expect to see the same noexcept expression much more than once.
3698 Canonical = getCanonicalType(Existing);
3699 Unique = true;
3700 }
3701
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003702 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003703 bool IsCanonicalExceptionSpec =
3704 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3705
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003706 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003707 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003708 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003709 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003710 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003711 isCanonical = false;
3712
Richard Smith304b1242016-10-18 20:13:25 +00003713 if (OnlyWantCanonical)
3714 assert(isCanonical &&
3715 "given non-canonical parameters constructing canonical type");
3716
Richard Smith2a2cda52016-10-18 19:29:18 +00003717 // If this type isn't canonical, get the canonical version of it if we don't
3718 // already have it. The exception spec is only partially part of the
3719 // canonical type, and only in C++17 onwards.
3720 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003721 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003722 CanonicalArgs.reserve(NumArgs);
3723 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003724 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003725
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003726 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003727 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003728 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003729
3730 if (IsCanonicalExceptionSpec) {
3731 // Exception spec is already OK.
3732 } else if (NoexceptInType) {
3733 switch (EPI.ExceptionSpec.Type) {
3734 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3735 // We don't know yet. It shouldn't matter what we pick here; no-one
3736 // should ever look at this.
3737 LLVM_FALLTHROUGH;
Richard Smitheaf11ad2018-05-03 03:58:32 +00003738 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003739 CanonicalEPI.ExceptionSpec.Type = EST_None;
3740 break;
3741
Richard Smith2a2cda52016-10-18 19:29:18 +00003742 // A dynamic exception specification is almost always "not noexcept",
3743 // with the exception that a pack expansion might expand to no types.
3744 case EST_Dynamic: {
3745 bool AnyPacks = false;
3746 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3747 if (ET->getAs<PackExpansionType>())
3748 AnyPacks = true;
3749 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3750 }
3751 if (!AnyPacks)
3752 CanonicalEPI.ExceptionSpec.Type = EST_None;
3753 else {
3754 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3755 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3756 }
3757 break;
3758 }
3759
Erich Keaned02f4a12019-05-30 17:31:54 +00003760 case EST_DynamicNone:
3761 case EST_BasicNoexcept:
3762 case EST_NoexceptTrue:
3763 case EST_NoThrow:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003764 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3765 break;
3766
Richard Smitheaf11ad2018-05-03 03:58:32 +00003767 case EST_DependentNoexcept:
3768 llvm_unreachable("dependent noexcept is already canonical");
Richard Smith3c4f8d22016-10-16 17:54:23 +00003769 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003770 } else {
3771 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3772 }
John McCalldb40c7f2010-12-14 08:05:40 +00003773
Douglas Gregora602a152015-10-01 20:20:47 +00003774 // Adjust the canonical function result type.
3775 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003776 Canonical =
3777 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003778
Chris Lattnerfd4de792007-01-27 01:15:32 +00003779 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003780 FunctionProtoType *NewIP =
3781 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003782 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003783 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003784
Bruno Ricci26a25362018-10-02 11:46:38 +00003785 // Compute the needed size to hold this FunctionProtoType and the
3786 // various trailing objects.
3787 auto ESH = FunctionProtoType::getExceptionSpecSize(
3788 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
3789 size_t Size = FunctionProtoType::totalSizeToAlloc<
3790 QualType, FunctionType::FunctionTypeExtraBitfields,
3791 FunctionType::ExceptionType, Expr *, FunctionDecl *,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003792 FunctionProtoType::ExtParameterInfo, Qualifiers>(
Bruno Ricci26a25362018-10-02 11:46:38 +00003793 NumArgs, FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
3794 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003795 EPI.ExtParameterInfos ? NumArgs : 0,
3796 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
John McCall18afab72016-03-01 00:49:02 +00003797
Bruno Ricci26a25362018-10-02 11:46:38 +00003798 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003799 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003800 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003801 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003802 if (!Unique)
3803 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003804 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003805}
Chris Lattneref51c202006-11-10 07:17:23 +00003806
Joey Goulye3c85de2016-12-01 11:30:49 +00003807QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003808 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003809 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003810
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00003811 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00003812 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003813 return QualType(PT, 0);
3814
3815 // If the pipe element type isn't canonical, this won't be a canonical type
3816 // either, so fill in the canonical type field.
3817 QualType Canonical;
3818 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003819 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003820
3821 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003822 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003823 assert(!NewIP && "Shouldn't be in the map!");
3824 (void)NewIP;
3825 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003826 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003827 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003828 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003829 return QualType(New, 0);
3830}
3831
Anastasia Stulova59055b92018-05-09 13:23:26 +00003832QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
3833 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3834 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3835 : Ty;
3836}
3837
Joey Goulye3c85de2016-12-01 11:30:49 +00003838QualType ASTContext::getReadPipeType(QualType T) const {
3839 return getPipeType(T, true);
3840}
3841
Joey Gouly5788b782016-11-18 14:10:54 +00003842QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003843 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003844}
3845
John McCalle78aac42010-03-10 03:28:59 +00003846#ifndef NDEBUG
3847static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3848 if (!isa<CXXRecordDecl>(D)) return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00003849 const auto *RD = cast<CXXRecordDecl>(D);
John McCalle78aac42010-03-10 03:28:59 +00003850 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3851 return true;
3852 if (RD->getDescribedClassTemplate() &&
3853 !isa<ClassTemplateSpecializationDecl>(RD))
3854 return true;
3855 return false;
3856}
3857#endif
3858
3859/// getInjectedClassNameType - Return the unique reference to the
3860/// injected class name type for the specified templated declaration.
3861QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003862 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003863 assert(NeedsInjectedClassNameType(Decl));
3864 if (Decl->TypeForDecl) {
3865 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003866 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003867 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3868 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3869 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3870 } else {
John McCall424cec92011-01-19 06:33:43 +00003871 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003872 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003873 Decl->TypeForDecl = newType;
3874 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003875 }
3876 return QualType(Decl->TypeForDecl, 0);
3877}
3878
Douglas Gregor83a586e2008-04-13 21:07:44 +00003879/// getTypeDeclType - Return the unique reference to the type for the
3880/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003881QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003882 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003883 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003884
Eugene Zelenko7855e772018-04-03 00:11:50 +00003885 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003886 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003887
John McCall96f0b5f2010-03-10 06:48:02 +00003888 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3889 "Template type parameter types are always available.");
3890
Eugene Zelenko7855e772018-04-03 00:11:50 +00003891 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003892 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003893 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003894 return getRecordType(Record);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003895 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003896 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003897 return getEnumType(Enum);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003898 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003899 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3900 Decl->TypeForDecl = newType;
3901 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003902 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003903 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003904
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003905 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003906}
3907
Chris Lattner32d920b2007-01-26 02:01:53 +00003908/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003909/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003910QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003911ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3912 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003913 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003914
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003915 if (Canonical.isNull())
3916 Canonical = getCanonicalType(Decl->getUnderlyingType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00003917 auto *newType = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003918 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003919 Decl->TypeForDecl = newType;
3920 Types.push_back(newType);
3921 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003922}
3923
Jay Foad39c79802011-01-12 09:06:06 +00003924QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003925 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3926
Douglas Gregorec9fd132012-01-14 16:38:05 +00003927 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003928 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00003929 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003930
Eugene Zelenko7855e772018-04-03 00:11:50 +00003931 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003932 Decl->TypeForDecl = newType;
3933 Types.push_back(newType);
3934 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003935}
3936
Jay Foad39c79802011-01-12 09:06:06 +00003937QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003938 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3939
Douglas Gregorec9fd132012-01-14 16:38:05 +00003940 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003941 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00003942 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003943
Eugene Zelenko7855e772018-04-03 00:11:50 +00003944 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003945 Decl->TypeForDecl = newType;
3946 Types.push_back(newType);
3947 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003948}
3949
Richard Smithe43e2b32018-08-20 21:47:29 +00003950QualType ASTContext::getAttributedType(attr::Kind attrKind,
John McCall81904512011-01-06 01:58:22 +00003951 QualType modifiedType,
3952 QualType equivalentType) {
3953 llvm::FoldingSetNodeID id;
3954 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3955
Craig Topper36250ad2014-05-12 05:36:57 +00003956 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003957 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3958 if (type) return QualType(type, 0);
3959
3960 QualType canon = getCanonicalType(equivalentType);
3961 type = new (*this, TypeAlignment)
Leonard Chanc72aaf62019-05-07 03:20:17 +00003962 AttributedType(canon, attrKind, modifiedType, equivalentType);
John McCall81904512011-01-06 01:58:22 +00003963
3964 Types.push_back(type);
3965 AttributedTypes.InsertNode(type, insertPos);
3966
3967 return QualType(type, 0);
3968}
3969
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003970/// Retrieve a substitution-result type.
John McCallcebee162009-10-18 09:09:24 +00003971QualType
3972ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003973 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003974 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003975 && "replacement types must always be canonical");
3976
3977 llvm::FoldingSetNodeID ID;
3978 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003979 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003980 SubstTemplateTypeParmType *SubstParm
3981 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3982
3983 if (!SubstParm) {
3984 SubstParm = new (*this, TypeAlignment)
3985 SubstTemplateTypeParmType(Parm, Replacement);
3986 Types.push_back(SubstParm);
3987 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3988 }
3989
3990 return QualType(SubstParm, 0);
3991}
3992
Fangrui Song6907ce22018-07-30 19:24:48 +00003993/// Retrieve a
Douglas Gregorada4b792011-01-14 02:55:32 +00003994QualType ASTContext::getSubstTemplateTypeParmPackType(
3995 const TemplateTypeParmType *Parm,
3996 const TemplateArgument &ArgPack) {
3997#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003998 for (const auto &P : ArgPack.pack_elements()) {
3999 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4000 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00004001 }
4002#endif
Fangrui Song6907ce22018-07-30 19:24:48 +00004003
Douglas Gregorada4b792011-01-14 02:55:32 +00004004 llvm::FoldingSetNodeID ID;
4005 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00004006 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00004007 if (SubstTemplateTypeParmPackType *SubstParm
4008 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4009 return QualType(SubstParm, 0);
Fangrui Song6907ce22018-07-30 19:24:48 +00004010
Douglas Gregorada4b792011-01-14 02:55:32 +00004011 QualType Canon;
4012 if (!Parm->isCanonicalUnqualified()) {
4013 Canon = getCanonicalType(QualType(Parm, 0));
4014 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4015 ArgPack);
4016 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4017 }
4018
Eugene Zelenko7855e772018-04-03 00:11:50 +00004019 auto *SubstParm
Douglas Gregorada4b792011-01-14 02:55:32 +00004020 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4021 ArgPack);
4022 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00004023 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00004024 return QualType(SubstParm, 0);
Douglas Gregorada4b792011-01-14 02:55:32 +00004025}
4026
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004027/// Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00004028/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00004029/// name.
Mike Stump11289f42009-09-09 15:08:12 +00004030QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00004031 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00004032 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00004033 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00004034 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00004035 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004036 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00004037 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4038
4039 if (TypeParm)
4040 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004041
Chandler Carruth08836322011-05-01 00:51:33 +00004042 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00004043 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00004044 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004045
Fangrui Song6907ce22018-07-30 19:24:48 +00004046 TemplateTypeParmType *TypeCheck
Douglas Gregorc42075a2010-02-04 18:10:26 +00004047 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4048 assert(!TypeCheck && "Template type parameter canonical type broken");
4049 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00004050 } else
John McCall90d1c2d2009-09-24 23:30:46 +00004051 TypeParm = new (*this, TypeAlignment)
4052 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00004053
4054 Types.push_back(TypeParm);
4055 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4056
4057 return QualType(TypeParm, 0);
4058}
4059
John McCalle78aac42010-03-10 03:28:59 +00004060TypeSourceInfo *
4061ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4062 SourceLocation NameLoc,
4063 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004064 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004065 assert(!Name.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004066 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004067 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00004068
4069 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00004070 TemplateSpecializationTypeLoc TL =
4071 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00004072 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00004073 TL.setTemplateNameLoc(NameLoc);
4074 TL.setLAngleLoc(Args.getLAngleLoc());
4075 TL.setRAngleLoc(Args.getRAngleLoc());
4076 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4077 TL.setArgLocInfo(i, Args[i].getLocInfo());
4078 return DI;
4079}
4080
Mike Stump11289f42009-09-09 15:08:12 +00004081QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00004082ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00004083 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004084 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004085 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004086 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00004087
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004088 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004089 ArgVec.reserve(Args.size());
4090 for (const TemplateArgumentLoc &Arg : Args.arguments())
4091 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00004092
David Majnemer6fbeee32016-07-07 04:43:07 +00004093 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00004094}
4095
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004096#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00004097static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4098 for (const TemplateArgument &Arg : Args)
4099 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004100 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004101
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004102 return true;
4103}
4104#endif
4105
John McCall0ad16662009-10-29 08:12:44 +00004106QualType
4107ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00004108 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004109 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004110 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004111 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00004112 // Look through qualified template names.
4113 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4114 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004115
4116 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00004117 Template.getAsTemplateDecl() &&
4118 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004119 QualType CanonType;
4120 if (!Underlying.isNull())
4121 CanonType = getCanonicalType(Underlying);
4122 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004123 // We can get here with an alias template when the specialization contains
4124 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00004125 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004126 "Caller must compute aliased type");
4127 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004128 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00004129 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00004130
Douglas Gregora8e02e72009-07-28 23:00:59 +00004131 // Allocate the (non-canonical) template specialization type, but don't
4132 // try to unique it: these types typically have location information that
4133 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004134 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00004135 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004136 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00004137 TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004138 auto *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00004139 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004140 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00004141
Douglas Gregor8bf42052009-02-09 18:46:07 +00004142 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00004143 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00004144}
4145
David Majnemer6fbeee32016-07-07 04:43:07 +00004146QualType ASTContext::getCanonicalTemplateSpecializationType(
4147 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004148 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004149 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004150
Douglas Gregore29139c2011-03-03 17:04:51 +00004151 // Look through qualified template names.
4152 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4153 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004154
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004155 // Build the canonical template specialization type.
4156 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004157 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00004158 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004159 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00004160 for (const TemplateArgument &Arg : Args)
4161 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004162
4163 // Determine whether this canonical template specialization type already
4164 // exists.
4165 llvm::FoldingSetNodeID ID;
4166 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004167 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004168
Craig Topper36250ad2014-05-12 05:36:57 +00004169 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004170 TemplateSpecializationType *Spec
4171 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4172
4173 if (!Spec) {
4174 // Allocate a new canonical template specialization type.
4175 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4176 sizeof(TemplateArgument) * NumArgs),
4177 TypeAlignment);
4178 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004179 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004180 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004181 Types.push_back(Spec);
4182 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4183 }
4184
4185 assert(Spec->isDependentType() &&
4186 "Non-dependent template-id type must have a canonical type");
4187 return QualType(Spec, 0);
4188}
4189
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004190QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4191 NestedNameSpecifier *NNS,
4192 QualType NamedType,
4193 TagDecl *OwnedTagDecl) const {
Douglas Gregor52537682009-03-19 00:18:19 +00004194 llvm::FoldingSetNodeID ID;
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004195 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
Douglas Gregor52537682009-03-19 00:18:19 +00004196
Craig Topper36250ad2014-05-12 05:36:57 +00004197 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00004198 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004199 if (T)
4200 return QualType(T, 0);
4201
Douglas Gregorc42075a2010-02-04 18:10:26 +00004202 QualType Canon = NamedType;
4203 if (!Canon.isCanonical()) {
4204 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004205 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4206 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004207 (void)CheckT;
4208 }
4209
Bruno Riccid6bd5982018-08-16 10:48:16 +00004210 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4211 TypeAlignment);
4212 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4213
Douglas Gregor52537682009-03-19 00:18:19 +00004214 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004215 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004216 return QualType(T, 0);
4217}
4218
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004219QualType
Jay Foad39c79802011-01-12 09:06:06 +00004220ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004221 llvm::FoldingSetNodeID ID;
4222 ParenType::Profile(ID, InnerType);
4223
Craig Topper36250ad2014-05-12 05:36:57 +00004224 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004225 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4226 if (T)
4227 return QualType(T, 0);
4228
4229 QualType Canon = InnerType;
4230 if (!Canon.isCanonical()) {
4231 Canon = getCanonicalType(InnerType);
4232 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4233 assert(!CheckT && "Paren canonical type broken");
4234 (void)CheckT;
4235 }
4236
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004237 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004238 Types.push_back(T);
4239 ParenTypes.InsertNode(T, InsertPos);
4240 return QualType(T, 0);
4241}
4242
Leonard Chanc72aaf62019-05-07 03:20:17 +00004243QualType
4244ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
4245 const IdentifierInfo *MacroII) const {
4246 QualType Canon = UnderlyingTy;
4247 if (!Canon.isCanonical())
4248 Canon = getCanonicalType(UnderlyingTy);
4249
4250 auto *newType = new (*this, TypeAlignment)
4251 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4252 Types.push_back(newType);
4253 return QualType(newType, 0);
4254}
4255
Douglas Gregor02085352010-03-31 20:19:30 +00004256QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4257 NestedNameSpecifier *NNS,
4258 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004259 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004260 if (Canon.isNull()) {
4261 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004262 if (CanonNNS != NNS)
4263 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004264 }
4265
4266 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004267 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004268
Craig Topper36250ad2014-05-12 05:36:57 +00004269 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004270 DependentNameType *T
4271 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004272 if (T)
4273 return QualType(T, 0);
4274
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004275 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004276 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004277 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004278 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004279}
4280
Mike Stump11289f42009-09-09 15:08:12 +00004281QualType
John McCallc392f372010-06-11 00:33:02 +00004282ASTContext::getDependentTemplateSpecializationType(
4283 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004284 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004285 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004286 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004287 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004288 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004289 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4290 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004291 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004292}
4293
4294QualType
4295ASTContext::getDependentTemplateSpecializationType(
4296 ElaboratedTypeKeyword Keyword,
4297 NestedNameSpecifier *NNS,
4298 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004299 ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004300 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor6e068012011-02-28 00:04:36 +00004301 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004302
Douglas Gregorc42075a2010-02-04 18:10:26 +00004303 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004304 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004305 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004306
Craig Topper36250ad2014-05-12 05:36:57 +00004307 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004308 DependentTemplateSpecializationType *T
4309 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004310 if (T)
4311 return QualType(T, 0);
4312
John McCallc392f372010-06-11 00:33:02 +00004313 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004314
John McCallc392f372010-06-11 00:33:02 +00004315 ElaboratedTypeKeyword CanonKeyword = Keyword;
4316 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4317
4318 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004319 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004320 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004321 for (unsigned I = 0; I != NumArgs; ++I) {
4322 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4323 if (!CanonArgs[I].structurallyEquals(Args[I]))
4324 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004325 }
4326
John McCallc392f372010-06-11 00:33:02 +00004327 QualType Canon;
4328 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4329 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004330 Name,
4331 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004332
4333 // Find the insert position again.
4334 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4335 }
4336
4337 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4338 sizeof(TemplateArgument) * NumArgs),
4339 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004340 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004341 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004342 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004343 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004344 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004345}
4346
Richard Smith32918772017-02-14 00:25:28 +00004347TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4348 TemplateArgument Arg;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004349 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith32918772017-02-14 00:25:28 +00004350 QualType ArgType = getTypeDeclType(TTP);
4351 if (TTP->isParameterPack())
4352 ArgType = getPackExpansionType(ArgType, None);
4353
4354 Arg = TemplateArgument(ArgType);
4355 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4356 Expr *E = new (*this) DeclRefExpr(
Bruno Ricci5fc4db72018-12-21 14:10:18 +00004357 *this, NTTP, /*enclosing*/ false,
Richard Smith32918772017-02-14 00:25:28 +00004358 NTTP->getType().getNonLValueExprType(*this),
4359 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4360
4361 if (NTTP->isParameterPack())
4362 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4363 None);
4364 Arg = TemplateArgument(E);
4365 } else {
4366 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4367 if (TTP->isParameterPack())
4368 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4369 else
4370 Arg = TemplateArgument(TemplateName(TTP));
4371 }
4372
4373 if (Param->isTemplateParameterPack())
4374 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4375
4376 return Arg;
4377}
4378
Richard Smith43e14d22016-12-23 02:10:11 +00004379void
4380ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4381 SmallVectorImpl<TemplateArgument> &Args) {
4382 Args.reserve(Args.size() + Params->size());
4383
Richard Smith32918772017-02-14 00:25:28 +00004384 for (NamedDecl *Param : *Params)
4385 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004386}
4387
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004388QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004389 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004390 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004391 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004392
Richard Smithb2997f52019-05-21 20:10:50 +00004393 // A deduced type can deduce to a pack, eg
4394 // auto ...x = some_pack;
4395 // That declaration isn't (yet) valid, but is created as part of building an
4396 // init-capture pack:
4397 // [...x = some_pack] {}
4398 assert((Pattern->containsUnexpandedParameterPack() ||
4399 Pattern->getContainedDeducedType()) &&
Douglas Gregord2fa7662010-12-20 02:24:11 +00004400 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004401 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004402 PackExpansionType *T
4403 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4404 if (T)
4405 return QualType(T, 0);
4406
4407 QualType Canon;
4408 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004409 Canon = getCanonicalType(Pattern);
4410 // The canonical type might not contain an unexpanded parameter pack, if it
4411 // contains an alias template specialization which ignores one of its
4412 // parameters.
4413 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004414 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004415
Richard Smith68eea502012-07-16 00:20:35 +00004416 // Find the insert position again, in case we inserted an element into
4417 // PackExpansionTypes and invalidated our insert position.
4418 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4419 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004420 }
4421
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004422 T = new (*this, TypeAlignment)
4423 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004424 Types.push_back(T);
4425 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004426 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004427}
4428
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004429/// CmpProtocolNames - Comparison predicate for sorting protocols
4430/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004431static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4432 ObjCProtocolDecl *const *RHS) {
4433 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004434}
4435
Craig Topper1f26d5b2016-01-03 19:43:23 +00004436static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4437 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004438
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004439 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4440 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004441
Craig Topper1f26d5b2016-01-03 19:43:23 +00004442 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004443 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004444 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004445 return false;
4446 return true;
4447}
4448
Craig Topper6a8c1512015-10-22 01:56:18 +00004449static void
4450SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004451 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004452 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004453
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004454 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004455 for (ObjCProtocolDecl *&P : Protocols)
4456 P = P->getCanonicalDecl();
4457
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004458 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004459 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4460 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004461}
4462
John McCall8b07ec22010-05-15 11:32:37 +00004463QualType ASTContext::getObjCObjectType(QualType BaseType,
4464 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004465 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004466 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004467 llvm::makeArrayRef(Protocols, NumProtocols),
4468 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004469}
4470
4471QualType ASTContext::getObjCObjectType(
4472 QualType baseType,
4473 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004474 ArrayRef<ObjCProtocolDecl *> protocols,
4475 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004476 // If the base type is an interface and there aren't any protocols or
4477 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004478 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4479 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004480 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004481
4482 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004483 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004484 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004485 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004486 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4487 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004488
Douglas Gregore9d95f12015-07-07 03:57:35 +00004489 // Determine the type arguments to be used for canonicalization,
4490 // which may be explicitly specified here or written on the base
4491 // type.
4492 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4493 if (effectiveTypeArgs.empty()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004494 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
Douglas Gregore9d95f12015-07-07 03:57:35 +00004495 effectiveTypeArgs = baseObject->getTypeArgs();
4496 }
John McCallfc93cf92009-10-22 22:37:11 +00004497
Douglas Gregore9d95f12015-07-07 03:57:35 +00004498 // Build the canonical type, which has the canonical base type and a
4499 // sorted-and-uniqued list of protocols and the type arguments
4500 // canonicalized.
4501 QualType canonical;
4502 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4503 effectiveTypeArgs.end(),
4504 [&](QualType type) {
4505 return type.isCanonical();
4506 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004507 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004508 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4509 // Determine the canonical type arguments.
4510 ArrayRef<QualType> canonTypeArgs;
4511 SmallVector<QualType, 4> canonTypeArgsVec;
4512 if (!typeArgsAreCanonical) {
4513 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4514 for (auto typeArg : effectiveTypeArgs)
4515 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4516 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004517 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004518 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004519 }
4520
Douglas Gregore9d95f12015-07-07 03:57:35 +00004521 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4522 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4523 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004524 canonProtocolsVec.append(protocols.begin(), protocols.end());
4525 SortAndUniqueProtocols(canonProtocolsVec);
4526 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004527 } else {
4528 canonProtocols = protocols;
4529 }
4530
4531 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004532 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004533
John McCallfc93cf92009-10-22 22:37:11 +00004534 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004535 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4536 }
4537
Douglas Gregore9d95f12015-07-07 03:57:35 +00004538 unsigned size = sizeof(ObjCObjectTypeImpl);
4539 size += typeArgs.size() * sizeof(QualType);
4540 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4541 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004542 auto *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004543 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4544 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004545
4546 Types.push_back(T);
4547 ObjCObjectTypes.InsertNode(T, InsertPos);
4548 return QualType(T, 0);
4549}
4550
Manman Ren3569eb52016-09-13 17:03:12 +00004551/// Apply Objective-C protocol qualifiers to the given type.
4552/// If this is for the canonical type of a type parameter, we can apply
4553/// protocol qualifiers on the ObjCObjectPointerType.
4554QualType
4555ASTContext::applyObjCProtocolQualifiers(QualType type,
4556 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4557 bool allowOnPointerType) const {
4558 hasError = false;
4559
Eugene Zelenko7855e772018-04-03 00:11:50 +00004560 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
Manman Renc5705ba2016-09-13 17:41:05 +00004561 return getObjCTypeParamType(objT->getDecl(), protocols);
4562 }
4563
Manman Ren3569eb52016-09-13 17:03:12 +00004564 // Apply protocol qualifiers to ObjCObjectPointerType.
4565 if (allowOnPointerType) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004566 if (const auto *objPtr =
4567 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
Manman Ren3569eb52016-09-13 17:03:12 +00004568 const ObjCObjectType *objT = objPtr->getObjectType();
4569 // Merge protocol lists and construct ObjCObjectType.
4570 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4571 protocolsVec.append(objT->qual_begin(),
4572 objT->qual_end());
4573 protocolsVec.append(protocols.begin(), protocols.end());
4574 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4575 type = getObjCObjectType(
4576 objT->getBaseType(),
4577 objT->getTypeArgsAsWritten(),
4578 protocols,
4579 objT->isKindOfTypeAsWritten());
4580 return getObjCObjectPointerType(type);
4581 }
4582 }
4583
4584 // Apply protocol qualifiers to ObjCObjectType.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004585 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
Manman Ren3569eb52016-09-13 17:03:12 +00004586 // FIXME: Check for protocols to which the class type is already
4587 // known to conform.
4588
4589 return getObjCObjectType(objT->getBaseType(),
4590 objT->getTypeArgsAsWritten(),
4591 protocols,
4592 objT->isKindOfTypeAsWritten());
4593 }
4594
4595 // If the canonical type is ObjCObjectType, ...
4596 if (type->isObjCObjectType()) {
4597 // Silently overwrite any existing protocol qualifiers.
4598 // TODO: determine whether that's the right thing to do.
4599
4600 // FIXME: Check for protocols to which the class type is already
4601 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004602 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004603 }
4604
4605 // id<protocol-list>
4606 if (type->isObjCIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004607 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004608 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004609 objPtr->isKindOfType());
4610 return getObjCObjectPointerType(type);
4611 }
4612
4613 // Class<protocol-list>
4614 if (type->isObjCClassType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004615 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004616 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004617 objPtr->isKindOfType());
4618 return getObjCObjectPointerType(type);
4619 }
4620
4621 hasError = true;
4622 return type;
4623}
4624
Manman Rene6be26c2016-09-13 17:25:08 +00004625QualType
4626ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4627 ArrayRef<ObjCProtocolDecl *> protocols,
4628 QualType Canonical) const {
4629 // Look in the folding set for an existing type.
4630 llvm::FoldingSetNodeID ID;
4631 ObjCTypeParamType::Profile(ID, Decl, protocols);
4632 void *InsertPos = nullptr;
4633 if (ObjCTypeParamType *TypeParam =
4634 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4635 return QualType(TypeParam, 0);
4636
4637 if (Canonical.isNull()) {
4638 // We canonicalize to the underlying type.
4639 Canonical = getCanonicalType(Decl->getUnderlyingType());
4640 if (!protocols.empty()) {
4641 // Apply the protocol qualifers.
4642 bool hasError;
Richard Trieua986a312018-08-30 01:57:52 +00004643 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
4644 Canonical, protocols, hasError, true /*allowOnPointerType*/));
Manman Rene6be26c2016-09-13 17:25:08 +00004645 assert(!hasError && "Error when apply protocol qualifier to bound type");
4646 }
4647 }
4648
4649 unsigned size = sizeof(ObjCTypeParamType);
4650 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4651 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004652 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
Manman Rene6be26c2016-09-13 17:25:08 +00004653
4654 Types.push_back(newType);
4655 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4656 return QualType(newType, 0);
4657}
4658
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004659/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4660/// protocol list adopt all protocols in QT's qualified-id protocol
4661/// list.
4662bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4663 ObjCInterfaceDecl *IC) {
4664 if (!QT->isObjCQualifiedIdType())
4665 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004666
Eugene Zelenko7855e772018-04-03 00:11:50 +00004667 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004668 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004669 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004670 if (!IC->ClassImplementsProtocol(Proto, false))
4671 return false;
4672 }
4673 return true;
4674 }
4675 return false;
4676}
4677
4678/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4679/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4680/// of protocols.
4681bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4682 ObjCInterfaceDecl *IDecl) {
4683 if (!QT->isObjCQualifiedIdType())
4684 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004685 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004686 if (!OPT)
4687 return false;
4688 if (!IDecl->hasDefinition())
4689 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004690 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4691 CollectInheritedProtocols(IDecl, InheritedProtocols);
4692 if (InheritedProtocols.empty())
4693 return false;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004694 // Check that if every protocol in list of id<plist> conforms to a protocol
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004695 // of IDecl's, then bridge casting is ok.
4696 bool Conforms = false;
4697 for (auto *Proto : OPT->quals()) {
4698 Conforms = false;
4699 for (auto *PI : InheritedProtocols) {
4700 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4701 Conforms = true;
4702 break;
4703 }
4704 }
4705 if (!Conforms)
4706 break;
4707 }
4708 if (Conforms)
4709 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004710
Aaron Ballman83731462014-03-17 16:14:00 +00004711 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004712 // If both the right and left sides have qualifiers.
4713 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004714 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004715 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004716 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004717 break;
4718 }
4719 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004720 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004721 }
4722 return true;
4723}
4724
John McCall8b07ec22010-05-15 11:32:37 +00004725/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4726/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004727QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004728 llvm::FoldingSetNodeID ID;
4729 ObjCObjectPointerType::Profile(ID, ObjectT);
4730
Craig Topper36250ad2014-05-12 05:36:57 +00004731 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004732 if (ObjCObjectPointerType *QT =
4733 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4734 return QualType(QT, 0);
4735
4736 // Find the canonical object type.
4737 QualType Canonical;
4738 if (!ObjectT.isCanonical()) {
4739 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4740
4741 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004742 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4743 }
4744
Douglas Gregorf85bee62010-02-08 22:59:26 +00004745 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004746 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004747 auto *QType =
John McCall8b07ec22010-05-15 11:32:37 +00004748 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004749
Steve Narofffb4330f2009-06-17 22:40:22 +00004750 Types.push_back(QType);
4751 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004752 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004753}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004754
Douglas Gregor1c283312010-08-11 12:19:30 +00004755/// getObjCInterfaceType - Return the unique reference to the type for the
4756/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004757QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4758 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004759 if (Decl->TypeForDecl)
4760 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004761
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004762 if (PrevDecl) {
4763 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4764 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4765 return QualType(PrevDecl->TypeForDecl, 0);
4766 }
4767
Douglas Gregor7671e532011-12-16 16:34:57 +00004768 // Prefer the definition, if there is one.
4769 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4770 Decl = Def;
Fangrui Song6907ce22018-07-30 19:24:48 +00004771
Douglas Gregor1c283312010-08-11 12:19:30 +00004772 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004773 auto *T = new (Mem) ObjCInterfaceType(Decl);
Douglas Gregor1c283312010-08-11 12:19:30 +00004774 Decl->TypeForDecl = T;
4775 Types.push_back(T);
4776 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004777}
4778
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004779/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4780/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004781/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004782/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004783/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004784QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004785 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004786 if (tofExpr->isTypeDependent()) {
4787 llvm::FoldingSetNodeID ID;
4788 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004789
Craig Topper36250ad2014-05-12 05:36:57 +00004790 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004791 DependentTypeOfExprType *Canon
4792 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4793 if (Canon) {
4794 // We already have a "canonical" version of an identical, dependent
4795 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004796 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004797 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004798 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004799 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004800 Canon
4801 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004802 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4803 toe = Canon;
4804 }
4805 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004806 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004807 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004808 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004809 Types.push_back(toe);
4810 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004811}
4812
Steve Naroffa773cd52007-08-01 18:02:17 +00004813/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004814/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004815/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004816/// an issue. This doesn't affect the type checker, since it operates
4817/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004818QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004819 QualType Canonical = getCanonicalType(tofType);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004820 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004821 Types.push_back(tot);
4822 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004823}
4824
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004825/// Unlike many "get<Type>" functions, we don't unique DecltypeType
Richard Smith8eb1d322014-06-05 20:13:13 +00004826/// nodes. This would never be helpful, since each such type has its own
4827/// expression, and would not give a significant memory saving, since there
4828/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004829QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004830 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004831
4832 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004833 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004834 // unique dependent type. Two such decltype-specifiers refer to the same
4835 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004836 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004837 llvm::FoldingSetNodeID ID;
4838 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004839
Craig Topper36250ad2014-05-12 05:36:57 +00004840 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004841 DependentDecltypeType *Canon
4842 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004843 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004844 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004845 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004846 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004847 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004848 dt = new (*this, TypeAlignment)
4849 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004850 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004851 dt = new (*this, TypeAlignment)
4852 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004853 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004854 Types.push_back(dt);
4855 return QualType(dt, 0);
4856}
4857
Alexis Hunte852b102011-05-24 22:41:36 +00004858/// getUnaryTransformationType - We don't unique these, since the memory
4859/// savings are minimal and these are rare.
4860QualType ASTContext::getUnaryTransformType(QualType BaseType,
4861 QualType UnderlyingType,
4862 UnaryTransformType::UTTKind Kind)
4863 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004864 UnaryTransformType *ut = nullptr;
4865
4866 if (BaseType->isDependentType()) {
4867 // Look in the folding set for an existing type.
4868 llvm::FoldingSetNodeID ID;
4869 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4870
4871 void *InsertPos = nullptr;
4872 DependentUnaryTransformType *Canon
4873 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4874
4875 if (!Canon) {
4876 // Build a new, canonical __underlying_type(type) type.
4877 Canon = new (*this, TypeAlignment)
4878 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4879 Kind);
4880 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4881 }
4882 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4883 QualType(), Kind,
4884 QualType(Canon, 0));
4885 } else {
4886 QualType CanonType = getCanonicalType(UnderlyingType);
4887 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4888 UnderlyingType, Kind,
4889 CanonType);
4890 }
4891 Types.push_back(ut);
4892 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004893}
4894
Richard Smith2a7d4812013-05-04 07:00:32 +00004895/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4896/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4897/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004898QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Richard Smithb2997f52019-05-21 20:10:50 +00004899 bool IsDependent, bool IsPack) const {
4900 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
Richard Smithe301ba22015-11-11 02:02:15 +00004901 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004902 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004903
Richard Smith2a7d4812013-05-04 07:00:32 +00004904 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004905 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004906 llvm::FoldingSetNodeID ID;
Richard Smithb2997f52019-05-21 20:10:50 +00004907 AutoType::Profile(ID, DeducedType, Keyword, IsDependent, IsPack);
Richard Smith2a7d4812013-05-04 07:00:32 +00004908 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4909 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004910
Eugene Zelenko7855e772018-04-03 00:11:50 +00004911 auto *AT = new (*this, TypeAlignment)
Richard Smithb2997f52019-05-21 20:10:50 +00004912 AutoType(DeducedType, Keyword, IsDependent, IsPack);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004913 Types.push_back(AT);
4914 if (InsertPos)
4915 AutoTypes.InsertNode(AT, InsertPos);
4916 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004917}
4918
Richard Smith600b5262017-01-26 20:40:47 +00004919/// Return the uniqued reference to the deduced template specialization type
4920/// which has been deduced to the given type, or to the canonical undeduced
4921/// such type, or the canonical deduced-but-dependent such type.
4922QualType ASTContext::getDeducedTemplateSpecializationType(
4923 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4924 // Look in the folding set for an existing type.
4925 void *InsertPos = nullptr;
4926 llvm::FoldingSetNodeID ID;
4927 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4928 IsDependent);
4929 if (DeducedTemplateSpecializationType *DTST =
4930 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4931 return QualType(DTST, 0);
4932
Eugene Zelenko7855e772018-04-03 00:11:50 +00004933 auto *DTST = new (*this, TypeAlignment)
Richard Smith600b5262017-01-26 20:40:47 +00004934 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4935 Types.push_back(DTST);
4936 if (InsertPos)
4937 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4938 return QualType(DTST, 0);
4939}
4940
Eli Friedman0dfb8892011-10-06 23:00:33 +00004941/// getAtomicType - Return the uniqued reference to the atomic type for
4942/// the given value type.
4943QualType ASTContext::getAtomicType(QualType T) const {
4944 // Unique pointers, to guarantee there is only one pointer of a particular
4945 // structure.
4946 llvm::FoldingSetNodeID ID;
4947 AtomicType::Profile(ID, T);
4948
Craig Topper36250ad2014-05-12 05:36:57 +00004949 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004950 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4951 return QualType(AT, 0);
4952
4953 // If the atomic value type isn't canonical, this won't be a canonical type
4954 // either, so fill in the canonical type field.
4955 QualType Canonical;
4956 if (!T.isCanonical()) {
4957 Canonical = getAtomicType(getCanonicalType(T));
4958
4959 // Get the new insert position for the node we care about.
4960 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004961 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004962 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00004963 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
Eli Friedman0dfb8892011-10-06 23:00:33 +00004964 Types.push_back(New);
4965 AtomicTypes.InsertNode(New, InsertPos);
4966 return QualType(New, 0);
4967}
4968
Richard Smith02e85f32011-04-14 22:09:26 +00004969/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4970QualType ASTContext::getAutoDeductType() const {
4971 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004972 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004973 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Richard Smithb2997f52019-05-21 20:10:50 +00004974 /*dependent*/false, /*pack*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004975 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004976 return AutoDeductTy;
4977}
4978
4979/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4980QualType ASTContext::getAutoRRefDeductType() const {
4981 if (AutoRRefDeductTy.isNull())
4982 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4983 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4984 return AutoRRefDeductTy;
4985}
4986
Chris Lattnerfb072462007-01-23 05:45:31 +00004987/// getTagDeclType - Return the unique reference to the type for the
4988/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004989QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004990 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004991 // FIXME: What is the design on getTagDeclType when it requires casting
4992 // away const? mutable?
4993 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004994}
4995
Mike Stump11289f42009-09-09 15:08:12 +00004996/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4997/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4998/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004999CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00005000 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00005001}
Chris Lattnerfb072462007-01-23 05:45:31 +00005002
Fangrui Song6907ce22018-07-30 19:24:48 +00005003/// Return the unique signed counterpart of the integer type
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00005004/// corresponding to size_t.
5005CanQualType ASTContext::getSignedSizeType() const {
5006 return getFromTargetType(Target->getSignedSizeType());
5007}
5008
Hans Wennborg27541db2011-10-27 08:29:09 +00005009/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5010CanQualType ASTContext::getIntMaxType() const {
5011 return getFromTargetType(Target->getIntMaxType());
5012}
5013
5014/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5015CanQualType ASTContext::getUIntMaxType() const {
5016 return getFromTargetType(Target->getUIntMaxType());
5017}
5018
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00005019/// getSignedWCharType - Return the type of "signed wchar_t".
5020/// Used when in C++, as a GCC extension.
5021QualType ASTContext::getSignedWCharType() const {
5022 // FIXME: derive from "Target" ?
5023 return WCharTy;
5024}
5025
5026/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5027/// Used when in C++, as a GCC extension.
5028QualType ASTContext::getUnsignedWCharType() const {
5029 // FIXME: derive from "Target" ?
5030 return UnsignedIntTy;
5031}
5032
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00005033QualType ASTContext::getIntPtrType() const {
5034 return getFromTargetType(Target->getIntPtrType());
5035}
5036
5037QualType ASTContext::getUIntPtrType() const {
5038 return getCorrespondingUnsignedType(getIntPtrType());
5039}
5040
Hans Wennborg27541db2011-10-27 08:29:09 +00005041/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005042/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5043QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00005044 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005045}
5046
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005047/// Return the unique unsigned counterpart of "ptrdiff_t"
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00005048/// integer type. The standard (C11 7.21.6.1p7) refers to this type
5049/// in the definition of %tu format specifier.
5050QualType ASTContext::getUnsignedPointerDiffType() const {
5051 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5052}
5053
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005054/// Return the unique type for "pid_t" defined in
Eli Friedman4e91899e2012-11-27 02:58:24 +00005055/// <sys/types.h>. We need this to compute the correct type for vfork().
5056QualType ASTContext::getProcessIDType() const {
5057 return getFromTargetType(Target->getProcessIDType());
5058}
5059
Chris Lattnera21ad802008-04-02 05:18:44 +00005060//===----------------------------------------------------------------------===//
5061// Type Operators
5062//===----------------------------------------------------------------------===//
5063
Jay Foad39c79802011-01-12 09:06:06 +00005064CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00005065 // Push qualifiers into arrays, and then discard any remaining
5066 // qualifiers.
5067 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00005068 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00005069 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00005070 QualType Result;
5071 if (isa<ArrayType>(Ty)) {
5072 Result = getArrayDecayedType(QualType(Ty,0));
5073 } else if (isa<FunctionType>(Ty)) {
5074 Result = getPointerType(QualType(Ty, 0));
5075 } else {
5076 Result = QualType(Ty, 0);
5077 }
5078
5079 return CanQualType::CreateUnsafe(Result);
5080}
5081
John McCall6c9dd522011-01-18 07:41:22 +00005082QualType ASTContext::getUnqualifiedArrayType(QualType type,
5083 Qualifiers &quals) {
5084 SplitQualType splitType = type.getSplitUnqualifiedType();
5085
5086 // FIXME: getSplitUnqualifiedType() actually walks all the way to
5087 // the unqualified desugared type and then drops it on the floor.
5088 // We then have to strip that sugar back off with
5089 // getUnqualifiedDesugaredType(), which is silly.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005090 const auto *AT =
5091 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00005092
5093 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005094 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00005095 quals = splitType.Quals;
5096 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005097 }
5098
John McCall6c9dd522011-01-18 07:41:22 +00005099 // Otherwise, recurse on the array's element type.
5100 QualType elementType = AT->getElementType();
5101 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5102
5103 // If that didn't change the element type, AT has no qualifiers, so we
5104 // can just use the results in splitType.
5105 if (elementType == unqualElementType) {
5106 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00005107 quals = splitType.Quals;
5108 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00005109 }
5110
5111 // Otherwise, add in the qualifiers from the outermost type, then
5112 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00005113 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005114
Eugene Zelenko7855e772018-04-03 00:11:50 +00005115 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005116 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005117 CAT->getSizeModifier(), 0);
5118 }
5119
Eugene Zelenko7855e772018-04-03 00:11:50 +00005120 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005121 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005122 }
5123
Eugene Zelenko7855e772018-04-03 00:11:50 +00005124 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005125 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00005126 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005127 VAT->getSizeModifier(),
5128 VAT->getIndexTypeCVRQualifiers(),
5129 VAT->getBracketsRange());
5130 }
5131
Eugene Zelenko7855e772018-04-03 00:11:50 +00005132 const auto *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00005133 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005134 DSAT->getSizeModifier(), 0,
5135 SourceRange());
5136}
5137
Richard Smitha3405ff2018-07-11 00:19:19 +00005138/// Attempt to unwrap two types that may both be array types with the same bound
5139/// (or both be array types of unknown bound) for the purpose of comparing the
5140/// cv-decomposition of two types per C++ [conv.qual].
Richard Smith5407d4f2018-07-18 20:13:36 +00005141bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5142 bool UnwrappedAny = false;
Richard Smitha3405ff2018-07-11 00:19:19 +00005143 while (true) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005144 auto *AT1 = getAsArrayType(T1);
5145 if (!AT1) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005146
Richard Smith5407d4f2018-07-18 20:13:36 +00005147 auto *AT2 = getAsArrayType(T2);
5148 if (!AT2) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005149
5150 // If we don't have two array types with the same constant bound nor two
5151 // incomplete array types, we've unwrapped everything we can.
5152 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5153 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5154 if (!CAT2 || CAT1->getSize() != CAT2->getSize())
Richard Smith5407d4f2018-07-18 20:13:36 +00005155 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005156 } else if (!isa<IncompleteArrayType>(AT1) ||
5157 !isa<IncompleteArrayType>(AT2)) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005158 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005159 }
5160
5161 T1 = AT1->getElementType();
5162 T2 = AT2->getElementType();
Richard Smith5407d4f2018-07-18 20:13:36 +00005163 UnwrappedAny = true;
Richard Smitha3405ff2018-07-11 00:19:19 +00005164 }
5165}
5166
5167/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5168///
5169/// If T1 and T2 are both pointer types of the same kind, or both array types
5170/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5171/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5172///
5173/// This function will typically be called in a loop that successively
5174/// "unwraps" pointer and pointer-to-member types to compare them at each
5175/// level.
5176///
5177/// \return \c true if a pointer type was unwrapped, \c false if we reached a
5178/// pair of types that can't be unwrapped further.
5179bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005180 UnwrapSimilarArrayTypes(T1, T2);
Richard Smitha3405ff2018-07-11 00:19:19 +00005181
Eugene Zelenko7855e772018-04-03 00:11:50 +00005182 const auto *T1PtrType = T1->getAs<PointerType>();
5183 const auto *T2PtrType = T2->getAs<PointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005184 if (T1PtrType && T2PtrType) {
5185 T1 = T1PtrType->getPointeeType();
5186 T2 = T2PtrType->getPointeeType();
5187 return true;
5188 }
Richard Smith5407d4f2018-07-18 20:13:36 +00005189
Eugene Zelenko7855e772018-04-03 00:11:50 +00005190 const auto *T1MPType = T1->getAs<MemberPointerType>();
5191 const auto *T2MPType = T2->getAs<MemberPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00005192 if (T1MPType && T2MPType &&
5193 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005194 QualType(T2MPType->getClass(), 0))) {
5195 T1 = T1MPType->getPointeeType();
5196 T2 = T2MPType->getPointeeType();
5197 return true;
5198 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005199
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005200 if (getLangOpts().ObjC) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005201 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5202 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005203 if (T1OPType && T2OPType) {
5204 T1 = T1OPType->getPointeeType();
5205 T2 = T2OPType->getPointeeType();
5206 return true;
5207 }
5208 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005209
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005210 // FIXME: Block pointers, too?
Fangrui Song6907ce22018-07-30 19:24:48 +00005211
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005212 return false;
5213}
5214
Richard Smitha3405ff2018-07-11 00:19:19 +00005215bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5216 while (true) {
5217 Qualifiers Quals;
5218 T1 = getUnqualifiedArrayType(T1, Quals);
5219 T2 = getUnqualifiedArrayType(T2, Quals);
5220 if (hasSameType(T1, T2))
5221 return true;
5222 if (!UnwrapSimilarTypes(T1, T2))
5223 return false;
5224 }
5225}
5226
5227bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5228 while (true) {
5229 Qualifiers Quals1, Quals2;
5230 T1 = getUnqualifiedArrayType(T1, Quals1);
5231 T2 = getUnqualifiedArrayType(T2, Quals2);
5232
5233 Quals1.removeCVRQualifiers();
5234 Quals2.removeCVRQualifiers();
5235 if (Quals1 != Quals2)
5236 return false;
5237
5238 if (hasSameType(T1, T2))
5239 return true;
5240
5241 if (!UnwrapSimilarTypes(T1, T2))
5242 return false;
5243 }
5244}
5245
Jay Foad39c79802011-01-12 09:06:06 +00005246DeclarationNameInfo
5247ASTContext::getNameForTemplate(TemplateName Name,
5248 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005249 switch (Name.getKind()) {
5250 case TemplateName::QualifiedTemplate:
5251 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005252 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00005253 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5254 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005255
John McCalld9dfe3a2011-06-30 08:33:18 +00005256 case TemplateName::OverloadedTemplate: {
5257 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5258 // DNInfo work in progress: CHECKME: what about DNLoc?
5259 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5260 }
5261
Richard Smithb23c5e82019-05-09 03:31:27 +00005262 case TemplateName::AssumedTemplate: {
5263 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5264 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5265 }
5266
John McCalld9dfe3a2011-06-30 08:33:18 +00005267 case TemplateName::DependentTemplate: {
5268 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005269 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00005270 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005271 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5272 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00005273 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005274 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5275 // DNInfo work in progress: FIXME: source locations?
5276 DeclarationNameLoc DNLoc;
5277 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5278 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5279 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00005280 }
5281 }
5282
John McCalld9dfe3a2011-06-30 08:33:18 +00005283 case TemplateName::SubstTemplateTemplateParm: {
5284 SubstTemplateTemplateParmStorage *subst
5285 = Name.getAsSubstTemplateTemplateParm();
5286 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5287 NameLoc);
5288 }
5289
5290 case TemplateName::SubstTemplateTemplateParmPack: {
5291 SubstTemplateTemplateParmPackStorage *subst
5292 = Name.getAsSubstTemplateTemplateParmPack();
5293 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5294 NameLoc);
5295 }
5296 }
5297
5298 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005299}
5300
Jay Foad39c79802011-01-12 09:06:06 +00005301TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005302 switch (Name.getKind()) {
5303 case TemplateName::QualifiedTemplate:
5304 case TemplateName::Template: {
5305 TemplateDecl *Template = Name.getAsTemplateDecl();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005306 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005307 Template = getCanonicalTemplateTemplateParmDecl(TTP);
Fangrui Song6907ce22018-07-30 19:24:48 +00005308
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005309 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005310 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005311 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005312
John McCalld9dfe3a2011-06-30 08:33:18 +00005313 case TemplateName::OverloadedTemplate:
Richard Smithb23c5e82019-05-09 03:31:27 +00005314 case TemplateName::AssumedTemplate:
5315 llvm_unreachable("cannot canonicalize unresolved template");
Mike Stump11289f42009-09-09 15:08:12 +00005316
John McCalld9dfe3a2011-06-30 08:33:18 +00005317 case TemplateName::DependentTemplate: {
5318 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5319 assert(DTN && "Non-dependent template names must refer to template decls.");
5320 return DTN->CanonicalTemplateName;
5321 }
5322
5323 case TemplateName::SubstTemplateTemplateParm: {
5324 SubstTemplateTemplateParmStorage *subst
5325 = Name.getAsSubstTemplateTemplateParm();
5326 return getCanonicalTemplateName(subst->getReplacement());
5327 }
5328
5329 case TemplateName::SubstTemplateTemplateParmPack: {
5330 SubstTemplateTemplateParmPackStorage *subst
5331 = Name.getAsSubstTemplateTemplateParmPack();
5332 TemplateTemplateParmDecl *canonParameter
5333 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5334 TemplateArgument canonArgPack
5335 = getCanonicalTemplateArgument(subst->getArgumentPack());
5336 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5337 }
5338 }
5339
5340 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005341}
5342
Douglas Gregoradee3e32009-11-11 23:06:43 +00005343bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5344 X = getCanonicalTemplateName(X);
5345 Y = getCanonicalTemplateName(Y);
5346 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5347}
5348
Mike Stump11289f42009-09-09 15:08:12 +00005349TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005350ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005351 switch (Arg.getKind()) {
5352 case TemplateArgument::Null:
5353 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005354
Douglas Gregora8e02e72009-07-28 23:00:59 +00005355 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005356 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005357
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005358 case TemplateArgument::Declaration: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005359 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005360 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005361 }
Mike Stump11289f42009-09-09 15:08:12 +00005362
Eli Friedmanb826a002012-09-26 02:36:12 +00005363 case TemplateArgument::NullPtr:
5364 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5365 /*isNullPtr*/true);
5366
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005367 case TemplateArgument::Template:
5368 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005369
5370 case TemplateArgument::TemplateExpansion:
5371 return TemplateArgument(getCanonicalTemplateName(
5372 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005373 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005374
Douglas Gregora8e02e72009-07-28 23:00:59 +00005375 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005376 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005377
Douglas Gregora8e02e72009-07-28 23:00:59 +00005378 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005379 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005380
Douglas Gregora8e02e72009-07-28 23:00:59 +00005381 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005382 if (Arg.pack_size() == 0)
5383 return Arg;
Fangrui Song6907ce22018-07-30 19:24:48 +00005384
Eugene Zelenko7855e772018-04-03 00:11:50 +00005385 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005386 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005387 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005388 AEnd = Arg.pack_end();
5389 A != AEnd; (void)++A, ++Idx)
5390 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005391
Benjamin Kramercce63472015-08-05 09:40:22 +00005392 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005393 }
5394 }
5395
5396 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005397 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005398}
5399
Douglas Gregor333489b2009-03-27 23:10:48 +00005400NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005401ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005402 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005403 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005404
5405 switch (NNS->getKind()) {
5406 case NestedNameSpecifier::Identifier:
5407 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005408 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005409 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5410 NNS->getAsIdentifier());
5411
5412 case NestedNameSpecifier::Namespace:
5413 // A namespace is canonical; build a nested-name-specifier with
5414 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005415 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005416 NNS->getAsNamespace()->getOriginalNamespace());
5417
5418 case NestedNameSpecifier::NamespaceAlias:
5419 // A namespace is canonical; build a nested-name-specifier with
5420 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005421 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005422 NNS->getAsNamespaceAlias()->getNamespace()
5423 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005424
5425 case NestedNameSpecifier::TypeSpec:
5426 case NestedNameSpecifier::TypeSpecWithTemplate: {
5427 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Fangrui Song6907ce22018-07-30 19:24:48 +00005428
Douglas Gregor3ade5702010-11-04 00:09:33 +00005429 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5430 // break it apart into its prefix and identifier, then reconsititute those
5431 // as the canonical nested-name-specifier. This is required to canonicalize
5432 // a dependent nested-name-specifier involving typedefs of dependent-name
5433 // types, e.g.,
5434 // typedef typename T::type T1;
5435 // typedef typename T1::type T2;
Eugene Zelenko7855e772018-04-03 00:11:50 +00005436 if (const auto *DNT = T->getAs<DependentNameType>())
Fangrui Song6907ce22018-07-30 19:24:48 +00005437 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005438 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005439
Eli Friedman5358a0a2012-03-03 04:09:56 +00005440 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5441 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5442 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005443 return NestedNameSpecifier::Create(*this, nullptr, false,
5444 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005445 }
5446
5447 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005448 case NestedNameSpecifier::Super:
5449 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005450 return NNS;
5451 }
5452
David Blaikie8a40f702012-01-17 06:56:22 +00005453 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005454}
5455
Jay Foad39c79802011-01-12 09:06:06 +00005456const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005457 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005458 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005459 // Handle the common positive case fast.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005460 if (const auto *AT = dyn_cast<ArrayType>(T))
Chris Lattner7adf0762008-08-04 07:31:14 +00005461 return AT;
5462 }
Mike Stump11289f42009-09-09 15:08:12 +00005463
John McCall8ccfcb52009-09-24 19:53:00 +00005464 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005465 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005466 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005467
John McCall8ccfcb52009-09-24 19:53:00 +00005468 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005469 // implements C99 6.7.3p8: "If the specification of an array type includes
5470 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005471
Chris Lattner7adf0762008-08-04 07:31:14 +00005472 // If we get here, we either have type qualifiers on the type, or we have
5473 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005474 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005475
John McCall33ddac02011-01-19 10:06:00 +00005476 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005477 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005478
Chris Lattner7adf0762008-08-04 07:31:14 +00005479 // If we have a simple case, just return now.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005480 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005481 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005482 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005483
Chris Lattner7adf0762008-08-04 07:31:14 +00005484 // Otherwise, we have an array and we have qualifiers on it. Push the
5485 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005486 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005487
Eugene Zelenko7855e772018-04-03 00:11:50 +00005488 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005489 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5490 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005491 CAT->getIndexTypeCVRQualifiers()));
Eugene Zelenko7855e772018-04-03 00:11:50 +00005492 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005493 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5494 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005495 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005496
Eugene Zelenko7855e772018-04-03 00:11:50 +00005497 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
Douglas Gregor4619e432008-12-05 23:32:09 +00005498 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005499 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005500 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005501 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005502 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005503 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005504
Eugene Zelenko7855e772018-04-03 00:11:50 +00005505 const auto *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005506 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005507 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005508 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005509 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005510 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005511}
5512
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005513QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005514 if (T->isArrayType() || T->isFunctionType())
5515 return getDecayedType(T);
5516 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005517}
5518
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005519QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005520 T = getVariableArrayDecayedType(T);
5521 T = getAdjustedParameterType(T);
5522 return T.getUnqualifiedType();
5523}
5524
David Majnemerd09a51c2015-03-03 01:50:05 +00005525QualType ASTContext::getExceptionObjectType(QualType T) const {
5526 // C++ [except.throw]p3:
5527 // A throw-expression initializes a temporary object, called the exception
5528 // object, the type of which is determined by removing any top-level
5529 // cv-qualifiers from the static type of the operand of throw and adjusting
5530 // the type from "array of T" or "function returning T" to "pointer to T"
5531 // or "pointer to function returning T", [...]
5532 T = getVariableArrayDecayedType(T);
5533 if (T->isArrayType() || T->isFunctionType())
5534 T = getDecayedType(T);
5535 return T.getUnqualifiedType();
5536}
5537
Chris Lattnera21ad802008-04-02 05:18:44 +00005538/// getArrayDecayedType - Return the properly qualified result of decaying the
5539/// specified array type to a pointer. This operation is non-trivial when
5540/// handling typedefs etc. The canonical type of "T" must be an array type,
5541/// this returns a pointer to a properly qualified element of the array.
5542///
5543/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005544QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005545 // Get the element type with 'getAsArrayType' so that we don't lose any
5546 // typedefs in the element type of the array. This also handles propagation
5547 // of type qualifiers from the array type into the element type if present
5548 // (C99 6.7.3p8).
5549 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5550 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005551
Chris Lattner7adf0762008-08-04 07:31:14 +00005552 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005553
5554 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005555 QualType Result = getQualifiedType(PtrTy,
5556 PrettyArrayType->getIndexTypeQualifiers());
5557
5558 // int x[_Nullable] -> int * _Nullable
5559 if (auto Nullability = Ty->getNullability(*this)) {
5560 Result = const_cast<ASTContext *>(this)->getAttributedType(
5561 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5562 }
5563 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005564}
5565
John McCall33ddac02011-01-19 10:06:00 +00005566QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5567 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005568}
5569
John McCall33ddac02011-01-19 10:06:00 +00005570QualType ASTContext::getBaseElementType(QualType type) const {
5571 Qualifiers qs;
5572 while (true) {
5573 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005574 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005575 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005576
John McCall33ddac02011-01-19 10:06:00 +00005577 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005578 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005579 }
Mike Stump11289f42009-09-09 15:08:12 +00005580
John McCall33ddac02011-01-19 10:06:00 +00005581 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005582}
5583
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005584/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005585uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005586ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5587 uint64_t ElementCount = 1;
5588 do {
5589 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005590 CA = dyn_cast_or_null<ConstantArrayType>(
5591 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005592 } while (CA);
5593 return ElementCount;
5594}
5595
Steve Naroff0af91202007-04-27 21:51:21 +00005596/// getFloatingRank - Return a relative rank for floating point types.
5597/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005598static FloatingRank getFloatingRank(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005599 if (const auto *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005600 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005601
John McCall9dd450b2009-09-21 23:43:11 +00005602 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5603 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005604 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005605 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005606 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005607 case BuiltinType::Float: return FloatRank;
5608 case BuiltinType::Double: return DoubleRank;
5609 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005610 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005611 }
5612}
5613
Mike Stump11289f42009-09-09 15:08:12 +00005614/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5615/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005616/// 'typeDomain' is a real floating point or complex type.
5617/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005618QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5619 QualType Domain) const {
5620 FloatingRank EltRank = getFloatingRank(Size);
5621 if (Domain->isComplexType()) {
5622 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005623 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005624 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005625 case FloatRank: return FloatComplexTy;
5626 case DoubleRank: return DoubleComplexTy;
5627 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005628 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005629 }
Steve Naroff0af91202007-04-27 21:51:21 +00005630 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005631
5632 assert(Domain->isRealFloatingType() && "Unknown domain!");
5633 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005634 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005635 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005636 case FloatRank: return FloatTy;
5637 case DoubleRank: return DoubleTy;
5638 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005639 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005640 }
David Blaikief47fa302012-01-17 02:30:50 +00005641 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005642}
5643
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005644/// getFloatingTypeOrder - Compare the rank of the two specified floating
5645/// point types, ignoring the domain of the type (i.e. 'double' ==
5646/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005647/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005648int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005649 FloatingRank LHSR = getFloatingRank(LHS);
5650 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005651
Chris Lattnerb90739d2008-04-06 23:38:49 +00005652 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005653 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005654 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005655 return 1;
5656 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005657}
5658
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +00005659int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
5660 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
5661 return 0;
5662 return getFloatingTypeOrder(LHS, RHS);
5663}
5664
Chris Lattner76a00cf2008-04-06 22:59:24 +00005665/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5666/// routine will assert if passed a built-in type that isn't an integer or enum,
5667/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005668unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005669 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005670
Chris Lattner76a00cf2008-04-06 22:59:24 +00005671 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005672 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005673 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005674 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005675 case BuiltinType::Char_S:
5676 case BuiltinType::Char_U:
5677 case BuiltinType::SChar:
5678 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005679 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005680 case BuiltinType::Short:
5681 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005682 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005683 case BuiltinType::Int:
5684 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005685 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005686 case BuiltinType::Long:
5687 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005688 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005689 case BuiltinType::LongLong:
5690 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005691 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005692 case BuiltinType::Int128:
5693 case BuiltinType::UInt128:
5694 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005695 }
5696}
5697
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005698/// Whether this is a promotable bitfield reference according
Eli Friedman629ffb92009-08-20 04:21:42 +00005699/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5700///
5701/// \returns the type this bit-field will promote to, or NULL if no
5702/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005703QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005704 if (E->isTypeDependent() || E->isValueDependent())
Eugene Zelenko7855e772018-04-03 00:11:50 +00005705 return {};
Richard Smith5b571672014-09-24 23:55:00 +00005706
Richard Smithaadb2542018-06-28 21:17:55 +00005707 // C++ [conv.prom]p5:
5708 // If the bit-field has an enumerated type, it is treated as any other
5709 // value of that type for promotion purposes.
5710 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5711 return {};
5712
Richard Smith5b571672014-09-24 23:55:00 +00005713 // FIXME: We should not do this unless E->refersToBitField() is true. This
5714 // matters in C where getSourceBitField() will find bit-fields for various
5715 // cases where the source expression is not a bit-field designator.
5716
John McCalld25db7e2013-05-06 21:39:12 +00005717 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005718 if (!Field)
Eugene Zelenko7855e772018-04-03 00:11:50 +00005719 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005720
5721 QualType FT = Field->getType();
5722
Richard Smithcaf33902011-10-10 18:28:20 +00005723 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005724 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005725 // C++ [conv.prom]p5:
5726 // A prvalue for an integral bit-field can be converted to a prvalue of type
5727 // int if int can represent all the values of the bit-field; otherwise, it
5728 // can be converted to unsigned int if unsigned int can represent all the
5729 // values of the bit-field. If the bit-field is larger yet, no integral
5730 // promotion applies to it.
5731 // C11 6.3.1.1/2:
5732 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5733 // If an int can represent all values of the original type (as restricted by
5734 // the width, for a bit-field), the value is converted to an int; otherwise,
5735 // it is converted to an unsigned int.
5736 //
5737 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5738 // We perform that promotion here to match GCC and C++.
Richard Smithaadb2542018-06-28 21:17:55 +00005739 // FIXME: C does not permit promotion of an enum bit-field whose rank is
5740 // greater than that of 'int'. We perform that promotion to match GCC.
Eli Friedman629ffb92009-08-20 04:21:42 +00005741 if (BitWidth < IntSize)
5742 return IntTy;
5743
5744 if (BitWidth == IntSize)
5745 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5746
Richard Smithaadb2542018-06-28 21:17:55 +00005747 // Bit-fields wider than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005748 // like the base type. GCC has some weird bugs in this area that we
5749 // deliberately do not follow (GCC follows a pre-standard resolution to
5750 // C's DR315 which treats bit-width as being part of the type, and this leaks
5751 // into their semantics in some cases).
Eugene Zelenko7855e772018-04-03 00:11:50 +00005752 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005753}
5754
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005755/// getPromotedIntegerType - Returns the type that Promotable will
5756/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5757/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005758QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005759 assert(!Promotable.isNull());
5760 assert(Promotable->isPromotableIntegerType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005761 if (const auto *ET = Promotable->getAs<EnumType>())
John McCall56774992009-12-09 09:09:27 +00005762 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005763
Eugene Zelenko7855e772018-04-03 00:11:50 +00005764 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005765 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5766 // (3.9.1) can be converted to a prvalue of the first of the following
5767 // types that can represent all the values of its underlying type:
5768 // int, unsigned int, long int, unsigned long int, long long int, or
5769 // unsigned long long int [...]
5770 // FIXME: Is there some better way to compute this?
5771 if (BT->getKind() == BuiltinType::WChar_S ||
5772 BT->getKind() == BuiltinType::WChar_U ||
Richard Smith3a8244d2018-05-01 05:02:45 +00005773 BT->getKind() == BuiltinType::Char8 ||
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005774 BT->getKind() == BuiltinType::Char16 ||
5775 BT->getKind() == BuiltinType::Char32) {
5776 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5777 uint64_t FromSize = getTypeSize(BT);
5778 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5779 LongLongTy, UnsignedLongLongTy };
5780 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5781 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5782 if (FromSize < ToSize ||
5783 (FromSize == ToSize &&
5784 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5785 return PromoteTypes[Idx];
5786 }
5787 llvm_unreachable("char type should fit into long long");
5788 }
5789 }
5790
5791 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005792 if (Promotable->isSignedIntegerType())
5793 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005794 uint64_t PromotableSize = getIntWidth(Promotable);
5795 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005796 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5797 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5798}
5799
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005800/// Recurses in pointer/array types until it finds an objc retainable
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005801/// type and returns its ownership.
5802Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5803 while (!T.isNull()) {
5804 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5805 return T.getObjCLifetime();
5806 if (T->isArrayType())
5807 T = getBaseElementType(T);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005808 else if (const auto *PT = T->getAs<PointerType>())
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005809 T = PT->getPointeeType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005810 else if (const auto *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005811 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005812 else
5813 break;
5814 }
5815
5816 return Qualifiers::OCL_None;
5817}
5818
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005819static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5820 // Incomplete enum types are not treated as integer types.
5821 // FIXME: In C++, enum types are never integer types.
5822 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5823 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005824 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005825}
5826
Mike Stump11289f42009-09-09 15:08:12 +00005827/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005828/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005829/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005830int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005831 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5832 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005833
5834 // Unwrap enums to their underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005835 if (const auto *ET = dyn_cast<EnumType>(LHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005836 LHSC = getIntegerTypeForEnum(ET);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005837 if (const auto *ET = dyn_cast<EnumType>(RHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005838 RHSC = getIntegerTypeForEnum(ET);
5839
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005840 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005841
Chris Lattner76a00cf2008-04-06 22:59:24 +00005842 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5843 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005844
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005845 unsigned LHSRank = getIntegerRank(LHSC);
5846 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005847
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005848 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5849 if (LHSRank == RHSRank) return 0;
5850 return LHSRank > RHSRank ? 1 : -1;
5851 }
Mike Stump11289f42009-09-09 15:08:12 +00005852
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005853 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5854 if (LHSUnsigned) {
5855 // If the unsigned [LHS] type is larger, return it.
5856 if (LHSRank >= RHSRank)
5857 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005858
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005859 // If the signed type can represent all values of the unsigned type, it
5860 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005861 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005862 return -1;
5863 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005864
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005865 // If the unsigned [RHS] type is larger, return it.
5866 if (RHSRank >= LHSRank)
5867 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005868
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005869 // If the signed type can represent all values of the unsigned type, it
5870 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005871 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005872 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005873}
Anders Carlsson98f07902007-08-17 05:31:46 +00005874
Ben Langmuirf5416742016-02-04 00:55:24 +00005875TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005876 if (CFConstantStringTypeDecl)
5877 return CFConstantStringTypeDecl;
Anders Carlsson6d417272009-11-14 21:45:58 +00005878
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005879 assert(!CFConstantStringTagDecl &&
5880 "tag and typedef should be initialized together");
5881 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5882 CFConstantStringTagDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00005883
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005884 struct {
5885 QualType Type;
5886 const char *Name;
5887 } Fields[5];
5888 unsigned Count = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005889
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005890 /// Objective-C ABI
5891 ///
5892 /// typedef struct __NSConstantString_tag {
Saleem Abdulrasool1f6c41f2018-10-27 06:12:52 +00005893 /// const int *isa;
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005894 /// int flags;
5895 /// const char *str;
5896 /// long length;
5897 /// } __NSConstantString;
5898 ///
5899 /// Swift ABI (4.1, 4.2)
5900 ///
5901 /// typedef struct __NSConstantString_tag {
5902 /// uintptr_t _cfisa;
5903 /// uintptr_t _swift_rc;
5904 /// _Atomic(uint64_t) _cfinfoa;
5905 /// const char *_ptr;
5906 /// uint32_t _length;
5907 /// } __NSConstantString;
5908 ///
5909 /// Swift ABI (5.0)
5910 ///
5911 /// typedef struct __NSConstantString_tag {
5912 /// uintptr_t _cfisa;
5913 /// uintptr_t _swift_rc;
5914 /// _Atomic(uint64_t) _cfinfoa;
5915 /// const char *_ptr;
5916 /// uintptr_t _length;
5917 /// } __NSConstantString;
5918
5919 const auto CFRuntime = getLangOpts().CFRuntime;
5920 if (static_cast<unsigned>(CFRuntime) <
5921 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
5922 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
5923 Fields[Count++] = { IntTy, "flags" };
5924 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
5925 Fields[Count++] = { LongTy, "length" };
5926 } else {
5927 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
5928 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
5929 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
5930 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
5931 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
5932 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
5933 Fields[Count++] = { IntTy, "_ptr" };
5934 else
5935 Fields[Count++] = { getUIntPtrType(), "_ptr" };
5936 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005937
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005938 // Create fields
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005939 for (unsigned i = 0; i < Count; ++i) {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005940 FieldDecl *Field =
5941 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005942 SourceLocation(), &Idents.get(Fields[i].Name),
5943 Fields[i].Type, /*TInfo=*/nullptr,
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005944 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
5945 Field->setAccess(AS_public);
5946 CFConstantStringTagDecl->addDecl(Field);
Anders Carlsson98f07902007-08-17 05:31:46 +00005947 }
Mike Stump11289f42009-09-09 15:08:12 +00005948
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005949 CFConstantStringTagDecl->completeDefinition();
5950 // This type is designed to be compatible with NSConstantString, but cannot
5951 // use the same name, since NSConstantString is an interface.
5952 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5953 CFConstantStringTypeDecl =
5954 buildImplicitTypedef(tagType, "__NSConstantString");
5955
Quentin Colombet043406b2016-02-03 22:41:00 +00005956 return CFConstantStringTypeDecl;
5957}
5958
Ben Langmuirf5416742016-02-04 00:55:24 +00005959RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5960 if (!CFConstantStringTagDecl)
5961 getCFConstantStringDecl(); // Build the tag and the typedef.
5962 return CFConstantStringTagDecl;
5963}
5964
Quentin Colombet043406b2016-02-03 22:41:00 +00005965// getCFConstantStringType - Return the type used for constant CFStrings.
5966QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005967 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005968}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005969
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005970QualType ASTContext::getObjCSuperType() const {
5971 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005972 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005973 TUDecl->addDecl(ObjCSuperTypeDecl);
5974 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5975 }
5976 return ObjCSuperType;
5977}
5978
Douglas Gregor512b0772009-04-23 22:29:11 +00005979void ASTContext::setCFConstantStringType(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005980 const auto *TD = T->getAs<TypedefType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00005981 assert(TD && "Invalid CFConstantStringType");
5982 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005983 const auto *TagType =
Ben Langmuirf5416742016-02-04 00:55:24 +00005984 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5985 assert(TagType && "Invalid CFConstantStringType");
5986 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005987}
5988
Jay Foad39c79802011-01-12 09:06:06 +00005989QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005990 if (BlockDescriptorType)
5991 return getTagDeclType(BlockDescriptorType);
5992
Alp Toker2dea15b2013-12-17 01:22:38 +00005993 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005994 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005995 RD = buildImplicitRecord("__block_descriptor");
5996 RD->startDefinition();
5997
Mike Stumpd0153282009-10-20 02:12:22 +00005998 QualType FieldTypes[] = {
5999 UnsignedLongTy,
6000 UnsignedLongTy,
6001 };
6002
Craig Topperd6d31ac2013-07-15 08:24:27 +00006003 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00006004 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006005 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00006006 };
6007
6008 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006009 FieldDecl *Field = FieldDecl::Create(
6010 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00006011 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6012 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00006013 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006014 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00006015 }
6016
Alp Toker2dea15b2013-12-17 01:22:38 +00006017 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00006018
Alp Toker2dea15b2013-12-17 01:22:38 +00006019 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00006020
6021 return getTagDeclType(BlockDescriptorType);
6022}
6023
Jay Foad39c79802011-01-12 09:06:06 +00006024QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006025 if (BlockDescriptorExtendedType)
6026 return getTagDeclType(BlockDescriptorExtendedType);
6027
Alp Toker2dea15b2013-12-17 01:22:38 +00006028 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006029 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00006030 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6031 RD->startDefinition();
6032
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006033 QualType FieldTypes[] = {
6034 UnsignedLongTy,
6035 UnsignedLongTy,
6036 getPointerType(VoidPtrTy),
6037 getPointerType(VoidPtrTy)
6038 };
6039
Craig Topperd6d31ac2013-07-15 08:24:27 +00006040 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006041 "reserved",
6042 "Size",
6043 "CopyFuncPtr",
6044 "DestroyFuncPtr"
6045 };
6046
6047 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006048 FieldDecl *Field = FieldDecl::Create(
6049 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00006050 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6051 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00006052 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00006053 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006054 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006055 }
6056
Alp Toker2dea15b2013-12-17 01:22:38 +00006057 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006058
Alp Toker2dea15b2013-12-17 01:22:38 +00006059 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006060 return getTagDeclType(BlockDescriptorExtendedType);
6061}
6062
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006063TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006064 const auto *BT = dyn_cast<BuiltinType>(T);
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006065
6066 if (!BT) {
6067 if (isa<PipeType>(T))
6068 return TargetInfo::OCLTK_Pipe;
6069
6070 return TargetInfo::OCLTK_Default;
6071 }
6072
6073 switch (BT->getKind()) {
6074#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6075 case BuiltinType::Id: \
6076 return TargetInfo::OCLTK_Image;
6077#include "clang/Basic/OpenCLImageTypes.def"
6078
6079 case BuiltinType::OCLClkEvent:
6080 return TargetInfo::OCLTK_ClkEvent;
6081
6082 case BuiltinType::OCLEvent:
6083 return TargetInfo::OCLTK_Event;
6084
6085 case BuiltinType::OCLQueue:
6086 return TargetInfo::OCLTK_Queue;
6087
6088 case BuiltinType::OCLReserveID:
6089 return TargetInfo::OCLTK_ReserveID;
6090
6091 case BuiltinType::OCLSampler:
6092 return TargetInfo::OCLTK_Sampler;
6093
6094 default:
6095 return TargetInfo::OCLTK_Default;
6096 }
6097}
6098
6099LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6100 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6101}
6102
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006103/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6104/// requires copy/dispose. Note that this must match the logic
6105/// in buildByrefHelpers.
6106bool ASTContext::BlockRequiresCopying(QualType Ty,
6107 const VarDecl *D) {
6108 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00006109 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006110 if (!copyExpr && record->hasTrivialDestructor()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006111
Mike Stump94967902009-10-21 18:16:27 +00006112 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00006113 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006114
Akira Hatanaka7275da02018-02-28 07:15:55 +00006115 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6116 // move or destroy.
6117 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6118 return true;
6119
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006120 if (!Ty->isObjCRetainableType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006121
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006122 Qualifiers qs = Ty.getQualifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00006123
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006124 // If we have lifetime, that dominates.
6125 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006126 switch (lifetime) {
6127 case Qualifiers::OCL_None: llvm_unreachable("impossible");
Fangrui Song6907ce22018-07-30 19:24:48 +00006128
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006129 // These are just bits as far as the runtime is concerned.
6130 case Qualifiers::OCL_ExplicitNone:
6131 case Qualifiers::OCL_Autoreleasing:
6132 return false;
Akira Hatanaka7275da02018-02-28 07:15:55 +00006133
6134 // These cases should have been taken care of when checking the type's
6135 // non-triviality.
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006136 case Qualifiers::OCL_Weak:
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006137 case Qualifiers::OCL_Strong:
Akira Hatanaka7275da02018-02-28 07:15:55 +00006138 llvm_unreachable("impossible");
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006139 }
6140 llvm_unreachable("fell out of lifetime switch!");
6141 }
6142 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6143 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00006144}
6145
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006146bool ASTContext::getByrefLifetime(QualType Ty,
6147 Qualifiers::ObjCLifetime &LifeTime,
6148 bool &HasByrefExtendedLayout) const {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00006149 if (!getLangOpts().ObjC ||
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006150 getLangOpts().getGC() != LangOptions::NonGC)
6151 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006152
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006153 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00006154 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006155 HasByrefExtendedLayout = true;
6156 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006157 } else if ((LifeTime = Ty.getObjCLifetime())) {
6158 // Honor the ARC qualifiers.
6159 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6160 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006161 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00006162 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006163 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006164 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006165 return true;
6166}
6167
Douglas Gregorbab8a962011-09-08 01:46:34 +00006168TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6169 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00006170 ObjCInstanceTypeDecl =
6171 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00006172 return ObjCInstanceTypeDecl;
6173}
6174
Anders Carlsson18acd442007-10-29 06:33:42 +00006175// This returns true if a type has been typedefed to BOOL:
6176// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00006177static bool isTypeTypedefedAsBOOL(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006178 if (const auto *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00006179 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6180 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00006181
Anders Carlssond8499822007-10-29 05:01:08 +00006182 return false;
6183}
6184
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006185/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006186/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00006187CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00006188 if (!type->isIncompleteArrayType() && type->isIncompleteType())
6189 return CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +00006190
Ken Dyck40775002010-01-11 17:06:35 +00006191 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00006192
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006193 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00006194 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00006195 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006196 // Treat arrays as pointers, since that's how they're passed in.
6197 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00006198 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00006199 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00006200}
6201
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006202bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00006203 return getTargetInfo().getCXXABI().isMicrosoft() &&
6204 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00006205 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00006206 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006207}
6208
Richard Smithd9b90092016-07-02 01:32:16 +00006209ASTContext::InlineVariableDefinitionKind
6210ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6211 if (!VD->isInline())
6212 return InlineVariableDefinitionKind::None;
6213
6214 // In almost all cases, it's a weak definition.
6215 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00006216 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00006217 return InlineVariableDefinitionKind::Weak;
6218
6219 // If there's a file-context declaration in this translation unit, it's a
6220 // non-discardable definition.
6221 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00006222 if (D->getLexicalDeclContext()->isFileContext() &&
6223 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00006224 return InlineVariableDefinitionKind::Strong;
6225
6226 // If we've not seen one yet, we don't know.
6227 return InlineVariableDefinitionKind::WeakUnknown;
6228}
6229
Eugene Zelenko7855e772018-04-03 00:11:50 +00006230static std::string charUnitsToString(const CharUnits &CU) {
Ken Dyck40775002010-01-11 17:06:35 +00006231 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006232}
6233
John McCall351762c2011-02-07 10:33:21 +00006234/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00006235/// declaration.
John McCall351762c2011-02-07 10:33:21 +00006236std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6237 std::string S;
6238
David Chisnall950a9512009-11-17 19:33:30 +00006239 const BlockDecl *Decl = Expr->getBlockDecl();
6240 QualType BlockTy =
6241 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
6242 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006243 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00006244 getObjCEncodingForMethodParameter(
6245 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
6246 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006247 else
Alp Toker314cc812014-01-25 16:55:45 +00006248 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00006249 // Compute size of all parameters.
6250 // Start with computing size of a pointer in number of bytes.
6251 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006252 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6253 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006254 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00006255 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006256 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00006257 if (sz.isZero())
6258 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006259 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00006260 ParmOffset += sz;
6261 }
6262 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00006263 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00006264 // Block pointer and offset.
6265 S += "@?0";
Fangrui Song6907ce22018-07-30 19:24:48 +00006266
David Chisnall950a9512009-11-17 19:33:30 +00006267 // Argument types.
6268 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006269 for (auto PVDecl : Decl->parameters()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006270 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006271 if (const auto *AT =
6272 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall950a9512009-11-17 19:33:30 +00006273 // Use array's original type only if it has known number of
6274 // elements.
6275 if (!isa<ConstantArrayType>(AT))
6276 PType = PVDecl->getType();
6277 } else if (PType->isFunctionType())
6278 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006279 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006280 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6281 S, true /*Extended*/);
6282 else
6283 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00006284 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006285 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00006286 }
John McCall351762c2011-02-07 10:33:21 +00006287
6288 return S;
David Chisnall950a9512009-11-17 19:33:30 +00006289}
6290
John McCall843dfcc2016-11-29 21:57:00 +00006291std::string
6292ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6293 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006294 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00006295 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00006296 CharUnits ParmOffset;
6297 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00006298 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00006299 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00006300 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006301 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006302 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006303
6304 assert(sz.isPositive() &&
John McCall843dfcc2016-11-29 21:57:00 +00006305 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00006306 ParmOffset += sz;
6307 }
6308 S += charUnitsToString(ParmOffset);
6309 ParmOffset = CharUnits::Zero();
6310
6311 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00006312 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006313 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006314 if (const auto *AT =
6315 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006316 // Use array's original type only if it has known number of
6317 // elements.
6318 if (!isa<ConstantArrayType>(AT))
6319 PType = PVDecl->getType();
6320 } else if (PType->isFunctionType())
6321 PType = PVDecl->getType();
6322 getObjCEncodingForType(PType, S);
6323 S += charUnitsToString(ParmOffset);
6324 ParmOffset += getObjCEncodingTypeSize(PType);
6325 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006326
John McCall843dfcc2016-11-29 21:57:00 +00006327 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006328}
6329
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006330/// getObjCEncodingForMethodParameter - Return the encoded type for a single
Fangrui Song6907ce22018-07-30 19:24:48 +00006331/// method parameter or return type. If Extended, include class names and
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006332/// block object types.
6333void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6334 QualType T, std::string& S,
6335 bool Extended) const {
6336 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6337 getObjCEncodingForTypeQualifier(QT, S);
6338 // Encode parameter type.
Nico Weber2e9591c2019-05-14 12:32:37 +00006339 ObjCEncOptions Options = ObjCEncOptions()
6340 .setExpandPointedToStructures()
6341 .setExpandStructures()
6342 .setIsOutermostType();
6343 if (Extended)
6344 Options.setEncodeBlockParameters().setEncodeClassNames();
6345 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006346}
6347
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006348/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006349/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00006350std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6351 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006352 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006353 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006354 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006355 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6356 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006357 // Compute size of all parameters.
6358 // Start with computing size of a pointer in number of bytes.
6359 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006360 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006361 // The first two arguments (self and _cmd) are pointers; account for
6362 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006363 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006364 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006365 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006366 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006367 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006368 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006369 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006370
6371 assert(sz.isPositive() &&
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006372 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006373 ParmOffset += sz;
6374 }
Ken Dyck40775002010-01-11 17:06:35 +00006375 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006376 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006377 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006378
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006379 // Argument types.
6380 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006381 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006382 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006383 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006384 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006385 if (const auto *AT =
6386 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
Steve Naroffe4e55d22009-04-14 00:03:58 +00006387 // Use array's original type only if it has known number of
6388 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006389 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006390 PType = PVDecl->getType();
6391 } else if (PType->isFunctionType())
6392 PType = PVDecl->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00006393 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006394 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006395 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006396 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006397 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006398
John McCall843dfcc2016-11-29 21:57:00 +00006399 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006400}
6401
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006402ObjCPropertyImplDecl *
6403ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6404 const ObjCPropertyDecl *PD,
6405 const Decl *Container) const {
6406 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006407 return nullptr;
Eugene Zelenko7855e772018-04-03 00:11:50 +00006408 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006409 for (auto *PID : CID->property_impls())
6410 if (PID->getPropertyDecl() == PD)
6411 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006412 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006413 const auto *OID = cast<ObjCImplementationDecl>(Container);
Craig Topper36250ad2014-05-12 05:36:57 +00006414 for (auto *PID : OID->property_impls())
6415 if (PID->getPropertyDecl() == PD)
6416 return PID;
6417 }
6418 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006419}
6420
Daniel Dunbar4932b362008-08-28 04:38:10 +00006421/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006422/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006423/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6424/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006425/// Property attributes are stored as a comma-delimited C string. The simple
6426/// attributes readonly and bycopy are encoded as single characters. The
6427/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6428/// encoded as single characters, followed by an identifier. Property types
6429/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006430/// these attributes are defined by the following enumeration:
6431/// @code
6432/// enum PropertyAttributes {
6433/// kPropertyReadOnly = 'R', // property is read-only.
6434/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6435/// kPropertyByref = '&', // property is a reference to the value last assigned
6436/// kPropertyDynamic = 'D', // property is dynamic
6437/// kPropertyGetter = 'G', // followed by getter selector name
6438/// kPropertySetter = 'S', // followed by setter selector name
6439/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006440/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006441/// kPropertyWeak = 'W' // 'weak' property
6442/// kPropertyStrong = 'P' // property GC'able
6443/// kPropertyNonAtomic = 'N' // property non-atomic
6444/// };
6445/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006446std::string
6447ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6448 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006449 // Collect information from the property implementation decl(s).
6450 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006451 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006452
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006453 if (ObjCPropertyImplDecl *PropertyImpDecl =
6454 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6455 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6456 Dynamic = true;
6457 else
6458 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006459 }
6460
6461 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006462 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006463
6464 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006465 // GCC has some special rules regarding encoding of properties which
6466 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006467 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006468
6469 if (PD->isReadOnly()) {
6470 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006471 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6472 S += ",C";
6473 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6474 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006475 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6476 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006477 } else {
6478 switch (PD->getSetterKind()) {
6479 case ObjCPropertyDecl::Assign: break;
6480 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006481 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006482 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006483 }
6484 }
6485
6486 // It really isn't clear at all what this means, since properties
6487 // are "dynamic by default".
6488 if (Dynamic)
6489 S += ",D";
6490
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006491 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6492 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006493
Daniel Dunbar4932b362008-08-28 04:38:10 +00006494 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6495 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006496 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006497 }
6498
6499 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6500 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006501 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006502 }
6503
6504 if (SynthesizePID) {
6505 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6506 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006507 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006508 }
6509
6510 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006511 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006512}
6513
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006514/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006515/// Another legacy compatibility encoding: 32-bit longs are encoded as
6516/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006517/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006518void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006519 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006520 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006521 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006522 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006523 else
Jay Foad39c79802011-01-12 09:06:06 +00006524 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006525 PointeeTy = IntTy;
6526 }
6527 }
6528}
6529
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006530void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006531 const FieldDecl *Field,
6532 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006533 // We follow the behavior of gcc, expanding structures which are
6534 // directly pointed to, and expanding embedded structures. Note that
6535 // these rules are sufficient to prevent recursive encoding of the
6536 // same type.
Nico Weber2e9591c2019-05-14 12:32:37 +00006537 getObjCEncodingForTypeImpl(T, S,
6538 ObjCEncOptions()
6539 .setExpandPointedToStructures()
6540 .setExpandStructures()
6541 .setIsOutermostType(),
6542 Field, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006543}
6544
Joe Groff98ac7d22014-07-07 22:25:15 +00006545void ASTContext::getObjCEncodingForPropertyType(QualType T,
6546 std::string& S) const {
6547 // Encode result type.
6548 // GCC has some special rules regarding encoding of properties which
6549 // closely resembles encoding of ivars.
Nico Weber2e9591c2019-05-14 12:32:37 +00006550 getObjCEncodingForTypeImpl(T, S,
6551 ObjCEncOptions()
6552 .setExpandPointedToStructures()
6553 .setExpandStructures()
6554 .setIsOutermostType()
6555 .setEncodingProperty(),
6556 /*Field=*/nullptr);
Joe Groff98ac7d22014-07-07 22:25:15 +00006557}
6558
John McCall393a78d2012-12-20 02:45:14 +00006559static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
6560 BuiltinType::Kind kind) {
6561 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006562 case BuiltinType::Void: return 'v';
6563 case BuiltinType::Bool: return 'B';
Richard Smith3a8244d2018-05-01 05:02:45 +00006564 case BuiltinType::Char8:
David Chisnallb190a2c2010-06-04 01:10:52 +00006565 case BuiltinType::Char_U:
6566 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006567 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006568 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006569 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006570 case BuiltinType::UInt: return 'I';
6571 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006572 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006573 case BuiltinType::UInt128: return 'T';
6574 case BuiltinType::ULongLong: return 'Q';
6575 case BuiltinType::Char_S:
6576 case BuiltinType::SChar: return 'c';
6577 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006578 case BuiltinType::WChar_S:
6579 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006580 case BuiltinType::Int: return 'i';
6581 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006582 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006583 case BuiltinType::LongLong: return 'q';
6584 case BuiltinType::Int128: return 't';
6585 case BuiltinType::Float: return 'f';
6586 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006587 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006588 case BuiltinType::NullPtr: return '*'; // like char*
6589
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006590 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006591 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006592 case BuiltinType::Half:
Leonard Chanf921d852018-06-04 16:07:52 +00006593 case BuiltinType::ShortAccum:
6594 case BuiltinType::Accum:
6595 case BuiltinType::LongAccum:
6596 case BuiltinType::UShortAccum:
6597 case BuiltinType::UAccum:
6598 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00006599 case BuiltinType::ShortFract:
6600 case BuiltinType::Fract:
6601 case BuiltinType::LongFract:
6602 case BuiltinType::UShortFract:
6603 case BuiltinType::UFract:
6604 case BuiltinType::ULongFract:
6605 case BuiltinType::SatShortAccum:
6606 case BuiltinType::SatAccum:
6607 case BuiltinType::SatLongAccum:
6608 case BuiltinType::SatUShortAccum:
6609 case BuiltinType::SatUAccum:
6610 case BuiltinType::SatULongAccum:
6611 case BuiltinType::SatShortFract:
6612 case BuiltinType::SatFract:
6613 case BuiltinType::SatLongFract:
6614 case BuiltinType::SatUShortFract:
6615 case BuiltinType::SatUFract:
6616 case BuiltinType::SatULongFract:
John McCall393a78d2012-12-20 02:45:14 +00006617 // FIXME: potentially need @encodes for these!
6618 return ' ';
6619
6620 case BuiltinType::ObjCId:
6621 case BuiltinType::ObjCClass:
6622 case BuiltinType::ObjCSel:
6623 llvm_unreachable("@encoding ObjC primitive type");
6624
6625 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006626#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6627 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006628#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00006629#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6630 case BuiltinType::Id:
6631#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006632 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006633 case BuiltinType::OCLClkEvent:
6634 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006635 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006636 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006637 case BuiltinType::Dependent:
6638#define BUILTIN_TYPE(KIND, ID)
6639#define PLACEHOLDER_TYPE(KIND, ID) \
6640 case BuiltinType::KIND:
6641#include "clang/AST/BuiltinTypes.def"
6642 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006643 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006644 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006645}
6646
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006647static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6648 EnumDecl *Enum = ET->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00006649
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006650 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6651 if (!Enum->isFixed())
6652 return 'i';
Fangrui Song6907ce22018-07-30 19:24:48 +00006653
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006654 // The encoding of a fixed enum type matches its fixed underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00006655 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006656 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006657}
6658
Jay Foad39c79802011-01-12 09:06:06 +00006659static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006660 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006661 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006662 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006663 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6664 // The GNU runtime requires more information; bitfields are encoded as b,
6665 // then the offset (in bits) of the first element, then the type of the
6666 // bitfield, then the size in bits. For example, in this structure:
6667 //
6668 // struct
6669 // {
6670 // int integer;
6671 // int flags:2;
6672 // };
6673 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6674 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6675 // information is not especially sensible, but we're stuck with it for
6676 // compatibility with GCC, although providing it breaks anything that
6677 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006678 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006679 uint64_t Offset;
6680
6681 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6682 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6683 IVD);
6684 } else {
6685 const RecordDecl *RD = FD->getParent();
6686 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6687 Offset = RL.getFieldOffset(FD->getFieldIndex());
6688 }
6689
6690 S += llvm::utostr(Offset);
6691
Eugene Zelenko7855e772018-04-03 00:11:50 +00006692 if (const auto *ET = T->getAs<EnumType>())
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006693 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006694 else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006695 const auto *BT = T->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006696 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6697 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006698 }
Richard Smithcaf33902011-10-10 18:28:20 +00006699 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006700}
6701
Daniel Dunbar07d07852009-10-18 21:17:35 +00006702// FIXME: Use SmallString for accumulating string.
Nico Weber2e9591c2019-05-14 12:32:37 +00006703void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
6704 const ObjCEncOptions Options,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006705 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006706 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006707 CanQualType CT = getCanonicalType(T);
6708 switch (CT->getTypeClass()) {
6709 case Type::Builtin:
6710 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006711 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006712 return EncodeBitField(this, S, T, FD);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006713 if (const auto *BT = dyn_cast<BuiltinType>(CT))
John McCall393a78d2012-12-20 02:45:14 +00006714 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6715 else
6716 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006717 return;
Mike Stump11289f42009-09-09 15:08:12 +00006718
John McCall393a78d2012-12-20 02:45:14 +00006719 case Type::Complex: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006720 const auto *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006721 S += 'j';
Nico Weber2e9591c2019-05-14 12:32:37 +00006722 getObjCEncodingForTypeImpl(CT->getElementType(), S, ObjCEncOptions(),
6723 /*Field=*/nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006724 return;
6725 }
John McCall393a78d2012-12-20 02:45:14 +00006726
6727 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006728 const auto *AT = T->castAs<AtomicType>();
John McCall393a78d2012-12-20 02:45:14 +00006729 S += 'A';
Nico Weber2e9591c2019-05-14 12:32:37 +00006730 getObjCEncodingForTypeImpl(AT->getValueType(), S, ObjCEncOptions(),
6731 /*Field=*/nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006732 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006733 }
John McCall393a78d2012-12-20 02:45:14 +00006734
6735 // encoding for pointer or reference types.
6736 case Type::Pointer:
6737 case Type::LValueReference:
6738 case Type::RValueReference: {
6739 QualType PointeeTy;
6740 if (isa<PointerType>(CT)) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006741 const auto *PT = T->castAs<PointerType>();
John McCall393a78d2012-12-20 02:45:14 +00006742 if (PT->isObjCSelType()) {
6743 S += ':';
6744 return;
6745 }
6746 PointeeTy = PT->getPointeeType();
6747 } else {
6748 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6749 }
6750
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006751 bool isReadOnly = false;
6752 // For historical/compatibility reasons, the read-only qualifier of the
6753 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6754 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006755 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006756 if (isa<TypedefType>(T.getTypePtr())) {
Nico Weber2e9591c2019-05-14 12:32:37 +00006757 if (Options.IsOutermostType() && T.isConstQualified()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006758 isReadOnly = true;
6759 S += 'r';
6760 }
Nico Weber2e9591c2019-05-14 12:32:37 +00006761 } else if (Options.IsOutermostType()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006762 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006763 while (P->getAs<PointerType>())
6764 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006765 if (P.isConstQualified()) {
6766 isReadOnly = true;
6767 S += 'r';
6768 }
6769 }
6770 if (isReadOnly) {
6771 // Another legacy compatibility encoding. Some ObjC qualifier and type
6772 // combinations need to be rearranged.
6773 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006774 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006775 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006776 }
Mike Stump11289f42009-09-09 15:08:12 +00006777
Anders Carlssond8499822007-10-29 05:01:08 +00006778 if (PointeeTy->isCharType()) {
6779 // char pointer types should be encoded as '*' unless it is a
6780 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006781 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006782 S += '*';
6783 return;
6784 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00006785 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006786 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6787 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6788 S += '#';
6789 return;
6790 }
6791 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6792 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6793 S += '@';
6794 return;
6795 }
6796 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006797 }
Anders Carlssond8499822007-10-29 05:01:08 +00006798 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006799 getLegacyIntegralTypeEncoding(PointeeTy);
6800
Nico Weber2e9591c2019-05-14 12:32:37 +00006801 ObjCEncOptions NewOptions;
6802 if (Options.ExpandPointedToStructures())
6803 NewOptions.setExpandStructures();
6804 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
6805 /*Field=*/nullptr, NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006806 return;
6807 }
John McCall393a78d2012-12-20 02:45:14 +00006808
6809 case Type::ConstantArray:
6810 case Type::IncompleteArray:
6811 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006812 const auto *AT = cast<ArrayType>(CT);
John McCall393a78d2012-12-20 02:45:14 +00006813
Nico Weber2e9591c2019-05-14 12:32:37 +00006814 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006815 // Incomplete arrays are encoded as a pointer to the array element.
6816 S += '^';
6817
Nico Weber2e9591c2019-05-14 12:32:37 +00006818 getObjCEncodingForTypeImpl(
6819 AT->getElementType(), S,
6820 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006821 } else {
6822 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006823
Eugene Zelenko7855e772018-04-03 00:11:50 +00006824 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006825 S += llvm::utostr(CAT->getSize().getZExtValue());
6826 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006827 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006828 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6829 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006830 S += '0';
6831 }
Mike Stump11289f42009-09-09 15:08:12 +00006832
Nico Weberdf129332019-05-10 13:56:56 +00006833 getObjCEncodingForTypeImpl(
6834 AT->getElementType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00006835 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
6836 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006837 S += ']';
6838 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006839 return;
6840 }
Mike Stump11289f42009-09-09 15:08:12 +00006841
John McCall393a78d2012-12-20 02:45:14 +00006842 case Type::FunctionNoProto:
6843 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006844 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006845 return;
Mike Stump11289f42009-09-09 15:08:12 +00006846
John McCall393a78d2012-12-20 02:45:14 +00006847 case Type::Record: {
6848 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006849 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006850 // Anonymous structures print as '?'
6851 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6852 S += II->getName();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006853 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006854 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006855 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00006856 printTemplateArgumentList(OS, TemplateArgs.asArray(),
6857 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006858 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006859 } else {
6860 S += '?';
6861 }
Nico Weber2e9591c2019-05-14 12:32:37 +00006862 if (Options.ExpandStructures()) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006863 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006864 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006865 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006866 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006867 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006868 if (FD) {
6869 S += '"';
6870 S += Field->getNameAsString();
6871 S += '"';
6872 }
Mike Stump11289f42009-09-09 15:08:12 +00006873
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006874 // Special case bit-fields.
6875 if (Field->isBitField()) {
Nico Weberdf129332019-05-10 13:56:56 +00006876 getObjCEncodingForTypeImpl(Field->getType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00006877 ObjCEncOptions().setExpandStructures(),
6878 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006879 } else {
6880 QualType qt = Field->getType();
6881 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00006882 getObjCEncodingForTypeImpl(
Nico Weber2e9591c2019-05-14 12:32:37 +00006883 qt, S,
6884 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
6885 NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006886 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006887 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006888 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006889 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006890 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006891 return;
6892 }
Mike Stump11289f42009-09-09 15:08:12 +00006893
John McCall393a78d2012-12-20 02:45:14 +00006894 case Type::BlockPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006895 const auto *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006896 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Nico Weber2e9591c2019-05-14 12:32:37 +00006897 if (Options.EncodeBlockParameters()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006898 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00006899
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006900 S += '<';
6901 // Block return type
Nico Weber2e9591c2019-05-14 12:32:37 +00006902 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
6903 Options.forComponentType(), FD, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006904 // Block self
6905 S += "@?";
6906 // Block parameters
Eugene Zelenko7855e772018-04-03 00:11:50 +00006907 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006908 for (const auto &I : FPT->param_types())
Nico Weber2e9591c2019-05-14 12:32:37 +00006909 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
6910 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006911 }
6912 S += '>';
6913 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006914 return;
6915 }
Mike Stump11289f42009-09-09 15:08:12 +00006916
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006917 case Type::ObjCObject: {
6918 // hack to match legacy encoding of *id and *Class
6919 QualType Ty = getObjCObjectPointerType(CT);
6920 if (Ty->isObjCIdType()) {
6921 S += "{objc_object=}";
6922 return;
6923 }
6924 else if (Ty->isObjCClassType()) {
6925 S += "{objc_class=}";
6926 return;
6927 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006928 // TODO: Double check to make sure this intentionally falls through.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006929 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006930 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006931
John McCall393a78d2012-12-20 02:45:14 +00006932 case Type::ObjCInterface: {
6933 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006934 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006935 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006936 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006937 S += OI->getObjCRuntimeNameAsString();
Nico Weber2e9591c2019-05-14 12:32:37 +00006938 if (Options.ExpandStructures()) {
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006939 S += '=';
6940 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6941 DeepCollectObjCIvars(OI, true, Ivars);
6942 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006943 const FieldDecl *Field = Ivars[i];
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006944 if (Field->isBitField())
Nico Weberdf129332019-05-10 13:56:56 +00006945 getObjCEncodingForTypeImpl(Field->getType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00006946 ObjCEncOptions().setExpandStructures(),
6947 Field);
Akira Hatanakaf3c89b12019-05-29 21:23:30 +00006948 else
6949 getObjCEncodingForTypeImpl(Field->getType(), S,
6950 ObjCEncOptions().setExpandStructures(), FD,
Nico Weber2e9591c2019-05-14 12:32:37 +00006951 NotEncodedT);
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006952 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006953 }
6954 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006955 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006956 }
Mike Stump11289f42009-09-09 15:08:12 +00006957
John McCall393a78d2012-12-20 02:45:14 +00006958 case Type::ObjCObjectPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006959 const auto *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006960 if (OPT->isObjCIdType()) {
6961 S += '@';
6962 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006963 }
Mike Stump11289f42009-09-09 15:08:12 +00006964
Steve Narofff0c86112009-10-28 22:03:49 +00006965 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6966 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
Nico Weberdf129332019-05-10 13:56:56 +00006967 // Since this is a binary compatibility issue, need to consult with
6968 // runtime folks. Fortunately, this is a *very* obscure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006969 S += '#';
6970 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006971 }
Mike Stump11289f42009-09-09 15:08:12 +00006972
Chris Lattnere7cabb92009-07-13 00:10:46 +00006973 if (OPT->isObjCQualifiedIdType()) {
Nico Weber2e9591c2019-05-14 12:32:37 +00006974 getObjCEncodingForTypeImpl(
6975 getObjCIdType(), S,
6976 Options.keepingOnly(ObjCEncOptions()
6977 .setExpandPointedToStructures()
6978 .setExpandStructures()),
6979 FD);
6980 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006981 // Note that we do extended encoding of protocol qualifer list
6982 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006983 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006984 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006985 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006986 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006987 S += '>';
6988 }
6989 S += '"';
6990 }
6991 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006992 }
Mike Stump11289f42009-09-09 15:08:12 +00006993
Chris Lattnere7cabb92009-07-13 00:10:46 +00006994 S += '@';
Fangrui Song6907ce22018-07-30 19:24:48 +00006995 if (OPT->getInterfaceDecl() &&
Nico Weber2e9591c2019-05-14 12:32:37 +00006996 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006997 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006998 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006999 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00007000 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007001 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00007002 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00007003 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00007004 S += '"';
7005 }
7006 return;
7007 }
Mike Stump11289f42009-09-09 15:08:12 +00007008
John McCalla9e6e8d2010-05-17 23:56:34 +00007009 // gcc just blithely ignores member pointers.
Nico Weber2e9591c2019-05-14 12:32:37 +00007010 // FIXME: we should do better than that. 'M' is available.
John McCall393a78d2012-12-20 02:45:14 +00007011 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007012 // This matches gcc's encoding, even though technically it is insufficient.
7013 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00007014 case Type::Vector:
7015 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007016 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007017 if (NotEncodedT)
7018 *NotEncodedT = T;
7019 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00007020
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007021 // We could see an undeduced auto type here during error recovery.
7022 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00007023 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007024 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00007025 return;
7026
Xiuli Pan9c14e282016-01-09 12:53:17 +00007027 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00007028#define ABSTRACT_TYPE(KIND, BASE)
7029#define TYPE(KIND, BASE)
7030#define DEPENDENT_TYPE(KIND, BASE) \
7031 case Type::KIND:
7032#define NON_CANONICAL_TYPE(KIND, BASE) \
7033 case Type::KIND:
7034#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7035 case Type::KIND:
7036#include "clang/AST/TypeNodes.def"
7037 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00007038 }
John McCall393a78d2012-12-20 02:45:14 +00007039 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00007040}
7041
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007042void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7043 std::string &S,
7044 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007045 bool includeVBases,
7046 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007047 assert(RDecl && "Expected non-null RecordDecl");
7048 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00007049 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007050 return;
7051
Eugene Zelenko7855e772018-04-03 00:11:50 +00007052 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007053 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7054 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7055
7056 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00007057 for (const auto &BI : CXXRec->bases()) {
7058 if (!BI.isVirtual()) {
7059 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007060 if (base->isEmpty())
7061 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007062 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007063 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7064 std::make_pair(offs, base));
7065 }
7066 }
7067 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007068
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007069 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00007070 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007071 uint64_t offs = layout.getFieldOffset(i);
7072 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00007073 std::make_pair(offs, Field));
7074 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007075 }
7076
7077 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00007078 for (const auto &BI : CXXRec->vbases()) {
7079 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007080 if (base->isEmpty())
7081 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007082 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00007083 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7084 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00007085 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7086 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007087 }
7088 }
7089
7090 CharUnits size;
7091 if (CXXRec) {
7092 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7093 } else {
7094 size = layout.getSize();
7095 }
7096
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007097#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007098 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007099#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007100 std::multimap<uint64_t, NamedDecl *>::iterator
7101 CurLayObj = FieldOrBaseOffsets.begin();
7102
Douglas Gregorf5d6c742012-04-27 22:30:01 +00007103 if (CXXRec && CXXRec->isDynamicClass() &&
7104 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007105 if (FD) {
7106 S += "\"_vptr$";
7107 std::string recname = CXXRec->getNameAsString();
7108 if (recname.empty()) recname = "?";
7109 S += recname;
7110 S += '"';
7111 }
7112 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007113#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007114 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007115#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007116 }
7117
7118 if (!RDecl->hasFlexibleArrayMember()) {
7119 // Mark the end of the structure.
7120 uint64_t offs = toBits(size);
7121 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00007122 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007123 }
7124
7125 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007126#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007127 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007128 if (CurOffs < CurLayObj->first) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007129 uint64_t padding = CurLayObj->first - CurOffs;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007130 // FIXME: There doesn't seem to be a way to indicate in the encoding that
7131 // packing/alignment of members is different that normal, in which case
7132 // the encoding will be out-of-sync with the real layout.
7133 // If the runtime switches to just consider the size of types without
7134 // taking into account alignment, we could make padding explicit in the
7135 // encoding (e.g. using arrays of chars). The encoding strings would be
7136 // longer then though.
7137 CurOffs += padding;
7138 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007139#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007140
7141 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00007142 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007143 break; // reached end of structure.
7144
Eugene Zelenko7855e772018-04-03 00:11:50 +00007145 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007146 // We expand the bases without their virtual bases since those are going
7147 // in the initial structure. Note that this differs from gcc which
7148 // expands virtual bases each time one is encountered in the hierarchy,
7149 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007150 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7151 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007152 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007153#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007154 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007155#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007156 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007157 const auto *field = cast<FieldDecl>(dcl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007158 if (FD) {
7159 S += '"';
7160 S += field->getNameAsString();
7161 S += '"';
7162 }
7163
7164 if (field->isBitField()) {
7165 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007166#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00007167 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007168#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007169 } else {
7170 QualType qt = field->getType();
7171 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00007172 getObjCEncodingForTypeImpl(
Nico Weber2e9591c2019-05-14 12:32:37 +00007173 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7174 FD, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007175#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007176 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007177#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007178 }
7179 }
7180 }
7181}
7182
Mike Stump11289f42009-09-09 15:08:12 +00007183void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00007184 std::string& S) const {
7185 if (QT & Decl::OBJC_TQ_In)
7186 S += 'n';
7187 if (QT & Decl::OBJC_TQ_Inout)
7188 S += 'N';
7189 if (QT & Decl::OBJC_TQ_Out)
7190 S += 'o';
7191 if (QT & Decl::OBJC_TQ_Bycopy)
7192 S += 'O';
7193 if (QT & Decl::OBJC_TQ_Byref)
7194 S += 'R';
7195 if (QT & Decl::OBJC_TQ_Oneway)
7196 S += 'V';
7197}
7198
Douglas Gregor3ea72692011-08-12 05:46:01 +00007199TypedefDecl *ASTContext::getObjCIdDecl() const {
7200 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007201 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00007202 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007203 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00007204 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00007205 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00007206}
7207
Douglas Gregor52e02802011-08-12 06:17:30 +00007208TypedefDecl *ASTContext::getObjCSelDecl() const {
7209 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007210 QualType T = getPointerType(ObjCBuiltinSelTy);
7211 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00007212 }
7213 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00007214}
7215
Douglas Gregor0a586182011-08-12 05:59:41 +00007216TypedefDecl *ASTContext::getObjCClassDecl() const {
7217 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007218 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00007219 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007220 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00007221 }
Douglas Gregor0a586182011-08-12 05:59:41 +00007222 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00007223}
7224
Douglas Gregord53ae832012-01-17 18:09:05 +00007225ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7226 if (!ObjCProtocolClassDecl) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007227 ObjCProtocolClassDecl
7228 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregord53ae832012-01-17 18:09:05 +00007229 SourceLocation(),
7230 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00007231 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00007232 /*PrevDecl=*/nullptr,
Fangrui Song6907ce22018-07-30 19:24:48 +00007233 SourceLocation(), true);
Douglas Gregord53ae832012-01-17 18:09:05 +00007234 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007235
Douglas Gregord53ae832012-01-17 18:09:05 +00007236 return ObjCProtocolClassDecl;
7237}
7238
Meador Inge5d3fb222012-06-16 03:34:49 +00007239//===----------------------------------------------------------------------===//
7240// __builtin_va_list Construction Functions
7241//===----------------------------------------------------------------------===//
7242
Charles Davisc7d5c942015-09-17 20:55:33 +00007243static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7244 StringRef Name) {
7245 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007246 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00007247 return Context->buildImplicitTypedef(T, Name);
7248}
7249
7250static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7251 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7252}
7253
7254static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7255 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007256}
7257
7258static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7259 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007260 QualType T = Context->getPointerType(Context->VoidTy);
7261 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007262}
7263
Tim Northover9bb857a2013-01-31 12:13:10 +00007264static TypedefDecl *
7265CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007266 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007267 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007268 if (Context->getLangOpts().CPlusPlus) {
7269 // namespace std { struct __va_list {
7270 NamespaceDecl *NS;
7271 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7272 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00007273 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00007274 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007275 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007276 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00007277 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00007278 }
7279
7280 VaListTagDecl->startDefinition();
7281
7282 const size_t NumFields = 5;
7283 QualType FieldTypes[NumFields];
7284 const char *FieldNames[NumFields];
7285
7286 // void *__stack;
7287 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7288 FieldNames[0] = "__stack";
7289
7290 // void *__gr_top;
7291 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7292 FieldNames[1] = "__gr_top";
7293
7294 // void *__vr_top;
7295 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7296 FieldNames[2] = "__vr_top";
7297
7298 // int __gr_offs;
7299 FieldTypes[3] = Context->IntTy;
7300 FieldNames[3] = "__gr_offs";
7301
7302 // int __vr_offs;
7303 FieldTypes[4] = Context->IntTy;
7304 FieldNames[4] = "__vr_offs";
7305
7306 // Create fields
7307 for (unsigned i = 0; i < NumFields; ++i) {
7308 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7309 VaListTagDecl,
7310 SourceLocation(),
7311 SourceLocation(),
7312 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007313 FieldTypes[i], /*TInfo=*/nullptr,
7314 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00007315 /*Mutable=*/false,
7316 ICIS_NoInit);
7317 Field->setAccess(AS_public);
7318 VaListTagDecl->addDecl(Field);
7319 }
7320 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007321 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00007322 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00007323
7324 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007325 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007326}
7327
Meador Inge5d3fb222012-06-16 03:34:49 +00007328static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7329 // typedef struct __va_list_tag {
7330 RecordDecl *VaListTagDecl;
7331
Alp Toker2dea15b2013-12-17 01:22:38 +00007332 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007333 VaListTagDecl->startDefinition();
7334
7335 const size_t NumFields = 5;
7336 QualType FieldTypes[NumFields];
7337 const char *FieldNames[NumFields];
7338
7339 // unsigned char gpr;
7340 FieldTypes[0] = Context->UnsignedCharTy;
7341 FieldNames[0] = "gpr";
7342
7343 // unsigned char fpr;
7344 FieldTypes[1] = Context->UnsignedCharTy;
7345 FieldNames[1] = "fpr";
7346
7347 // unsigned short reserved;
7348 FieldTypes[2] = Context->UnsignedShortTy;
7349 FieldNames[2] = "reserved";
7350
7351 // void* overflow_arg_area;
7352 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7353 FieldNames[3] = "overflow_arg_area";
7354
7355 // void* reg_save_area;
7356 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7357 FieldNames[4] = "reg_save_area";
7358
7359 // Create fields
7360 for (unsigned i = 0; i < NumFields; ++i) {
7361 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7362 SourceLocation(),
7363 SourceLocation(),
7364 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007365 FieldTypes[i], /*TInfo=*/nullptr,
7366 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007367 /*Mutable=*/false,
7368 ICIS_NoInit);
7369 Field->setAccess(AS_public);
7370 VaListTagDecl->addDecl(Field);
7371 }
7372 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007373 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007374 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7375
7376 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007377 TypedefDecl *VaListTagTypedefDecl =
7378 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7379
Meador Inge5d3fb222012-06-16 03:34:49 +00007380 QualType VaListTagTypedefType =
7381 Context->getTypedefType(VaListTagTypedefDecl);
7382
7383 // typedef __va_list_tag __builtin_va_list[1];
7384 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7385 QualType VaListTagArrayType
7386 = Context->getConstantArrayType(VaListTagTypedefType,
7387 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007388 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007389}
7390
7391static TypedefDecl *
7392CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007393 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007394 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007395 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007396 VaListTagDecl->startDefinition();
7397
7398 const size_t NumFields = 4;
7399 QualType FieldTypes[NumFields];
7400 const char *FieldNames[NumFields];
7401
7402 // unsigned gp_offset;
7403 FieldTypes[0] = Context->UnsignedIntTy;
7404 FieldNames[0] = "gp_offset";
7405
7406 // unsigned fp_offset;
7407 FieldTypes[1] = Context->UnsignedIntTy;
7408 FieldNames[1] = "fp_offset";
7409
7410 // void* overflow_arg_area;
7411 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7412 FieldNames[2] = "overflow_arg_area";
7413
7414 // void* reg_save_area;
7415 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7416 FieldNames[3] = "reg_save_area";
7417
7418 // Create fields
7419 for (unsigned i = 0; i < NumFields; ++i) {
7420 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7421 VaListTagDecl,
7422 SourceLocation(),
7423 SourceLocation(),
7424 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007425 FieldTypes[i], /*TInfo=*/nullptr,
7426 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007427 /*Mutable=*/false,
7428 ICIS_NoInit);
7429 Field->setAccess(AS_public);
7430 VaListTagDecl->addDecl(Field);
7431 }
7432 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007433 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007434 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7435
Richard Smith9b88a4c2015-07-27 05:40:23 +00007436 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007437
Richard Smith9b88a4c2015-07-27 05:40:23 +00007438 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007439 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007440 QualType VaListTagArrayType =
7441 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007442 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007443}
7444
7445static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7446 // typedef int __builtin_va_list[4];
7447 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00007448 QualType IntArrayType =
7449 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007450 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007451}
7452
Logan Chien57086ce2012-10-10 06:56:20 +00007453static TypedefDecl *
7454CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007455 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007456 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007457 if (Context->getLangOpts().CPlusPlus) {
7458 // namespace std { struct __va_list {
7459 NamespaceDecl *NS;
7460 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7461 Context->getTranslationUnitDecl(),
7462 /*Inline*/false, SourceLocation(),
7463 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007464 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007465 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007466 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007467 }
7468
7469 VaListDecl->startDefinition();
7470
7471 // void * __ap;
7472 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7473 VaListDecl,
7474 SourceLocation(),
7475 SourceLocation(),
7476 &Context->Idents.get("__ap"),
7477 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007478 /*TInfo=*/nullptr,
7479 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007480 /*Mutable=*/false,
7481 ICIS_NoInit);
7482 Field->setAccess(AS_public);
7483 VaListDecl->addDecl(Field);
7484
7485 // };
7486 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007487 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007488
7489 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007490 QualType T = Context->getRecordType(VaListDecl);
7491 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007492}
7493
Ulrich Weigand47445072013-05-06 16:26:41 +00007494static TypedefDecl *
7495CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007496 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007497 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007498 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007499 VaListTagDecl->startDefinition();
7500
7501 const size_t NumFields = 4;
7502 QualType FieldTypes[NumFields];
7503 const char *FieldNames[NumFields];
7504
7505 // long __gpr;
7506 FieldTypes[0] = Context->LongTy;
7507 FieldNames[0] = "__gpr";
7508
7509 // long __fpr;
7510 FieldTypes[1] = Context->LongTy;
7511 FieldNames[1] = "__fpr";
7512
7513 // void *__overflow_arg_area;
7514 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7515 FieldNames[2] = "__overflow_arg_area";
7516
7517 // void *__reg_save_area;
7518 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7519 FieldNames[3] = "__reg_save_area";
7520
7521 // Create fields
7522 for (unsigned i = 0; i < NumFields; ++i) {
7523 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7524 VaListTagDecl,
7525 SourceLocation(),
7526 SourceLocation(),
7527 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007528 FieldTypes[i], /*TInfo=*/nullptr,
7529 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007530 /*Mutable=*/false,
7531 ICIS_NoInit);
7532 Field->setAccess(AS_public);
7533 VaListTagDecl->addDecl(Field);
7534 }
7535 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007536 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007537 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007538
Richard Smith9b88a4c2015-07-27 05:40:23 +00007539 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007540
7541 // typedef __va_list_tag __builtin_va_list[1];
7542 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007543 QualType VaListTagArrayType =
7544 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007545
Alp Toker56b5cc92013-12-15 10:36:26 +00007546 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007547}
7548
Meador Inge5d3fb222012-06-16 03:34:49 +00007549static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7550 TargetInfo::BuiltinVaListKind Kind) {
7551 switch (Kind) {
7552 case TargetInfo::CharPtrBuiltinVaList:
7553 return CreateCharPtrBuiltinVaListDecl(Context);
7554 case TargetInfo::VoidPtrBuiltinVaList:
7555 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007556 case TargetInfo::AArch64ABIBuiltinVaList:
7557 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007558 case TargetInfo::PowerABIBuiltinVaList:
7559 return CreatePowerABIBuiltinVaListDecl(Context);
7560 case TargetInfo::X86_64ABIBuiltinVaList:
7561 return CreateX86_64ABIBuiltinVaListDecl(Context);
7562 case TargetInfo::PNaClABIBuiltinVaList:
7563 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007564 case TargetInfo::AAPCSABIBuiltinVaList:
7565 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007566 case TargetInfo::SystemZBuiltinVaList:
7567 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007568 }
7569
7570 llvm_unreachable("Unhandled __builtin_va_list type kind");
7571}
7572
7573TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007574 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007575 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007576 assert(BuiltinVaListDecl->isImplicit());
7577 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007578
7579 return BuiltinVaListDecl;
7580}
7581
Richard Smith9b88a4c2015-07-27 05:40:23 +00007582Decl *ASTContext::getVaListTagDecl() const {
7583 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007584 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007585 if (!VaListTagDecl)
7586 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007587
Richard Smith9b88a4c2015-07-27 05:40:23 +00007588 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007589}
7590
Charles Davisc7d5c942015-09-17 20:55:33 +00007591TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7592 if (!BuiltinMSVaListDecl)
7593 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7594
7595 return BuiltinMSVaListDecl;
7596}
7597
Erich Keane41af9712018-04-16 21:30:08 +00007598bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
7599 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
7600}
7601
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007602void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007603 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007604 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007605
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007606 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007607}
7608
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007609/// Retrieve the template name that corresponds to a non-empty
John McCalld28ae272009-12-02 08:04:21 +00007610/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007611TemplateName
7612ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7613 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007614 unsigned size = End - Begin;
7615 assert(size > 1 && "set is not overloaded!");
7616
7617 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7618 size * sizeof(FunctionTemplateDecl*));
Eugene Zelenko7855e772018-04-03 00:11:50 +00007619 auto *OT = new (memory) OverloadedTemplateStorage(size);
John McCalld28ae272009-12-02 08:04:21 +00007620
7621 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007622 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007623 NamedDecl *D = *I;
7624 assert(isa<FunctionTemplateDecl>(D) ||
Richard Smithef53a3e2018-06-06 16:36:56 +00007625 isa<UnresolvedUsingValueDecl>(D) ||
John McCalld28ae272009-12-02 08:04:21 +00007626 (isa<UsingShadowDecl>(D) &&
7627 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7628 *Storage++ = D;
7629 }
7630
7631 return TemplateName(OT);
7632}
7633
Richard Smithb23c5e82019-05-09 03:31:27 +00007634/// Retrieve a template name representing an unqualified-id that has been
7635/// assumed to name a template for ADL purposes.
7636TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
7637 auto *OT = new (*this) AssumedTemplateStorage(Name);
7638 return TemplateName(OT);
7639}
7640
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007641/// Retrieve the template name that represents a qualified
Douglas Gregordc572a32009-03-30 22:58:21 +00007642/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007643TemplateName
7644ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7645 bool TemplateKeyword,
7646 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007647 assert(NNS && "Missing nested-name-specifier in qualified template name");
Fangrui Song6907ce22018-07-30 19:24:48 +00007648
Douglas Gregorc42075a2010-02-04 18:10:26 +00007649 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007650 llvm::FoldingSetNodeID ID;
7651 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7652
Craig Topper36250ad2014-05-12 05:36:57 +00007653 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007654 QualifiedTemplateName *QTN =
7655 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7656 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007657 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007658 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007659 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7660 }
7661
7662 return TemplateName(QTN);
7663}
7664
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007665/// Retrieve the template name that represents a dependent
Douglas Gregordc572a32009-03-30 22:58:21 +00007666/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007667TemplateName
7668ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7669 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007670 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007671 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007672
7673 llvm::FoldingSetNodeID ID;
7674 DependentTemplateName::Profile(ID, NNS, Name);
7675
Craig Topper36250ad2014-05-12 05:36:57 +00007676 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007677 DependentTemplateName *QTN =
7678 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7679
7680 if (QTN)
7681 return TemplateName(QTN);
7682
7683 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7684 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007685 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007686 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007687 } else {
7688 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007689 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007690 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007691 DependentTemplateName *CheckQTN =
7692 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7693 assert(!CheckQTN && "Dependent type name canonicalization broken");
7694 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007695 }
7696
7697 DependentTemplateNames.InsertNode(QTN, InsertPos);
7698 return TemplateName(QTN);
7699}
7700
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007701/// Retrieve the template name that represents a dependent
Douglas Gregor71395fa2009-11-04 00:56:37 +00007702/// template name such as \c MetaFun::template operator+.
Fangrui Song6907ce22018-07-30 19:24:48 +00007703TemplateName
Douglas Gregor71395fa2009-11-04 00:56:37 +00007704ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007705 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007706 assert((!NNS || NNS->isDependent()) &&
7707 "Nested name specifier must be dependent");
Fangrui Song6907ce22018-07-30 19:24:48 +00007708
Douglas Gregor71395fa2009-11-04 00:56:37 +00007709 llvm::FoldingSetNodeID ID;
7710 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007711
7712 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007713 DependentTemplateName *QTN
7714 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007715
Douglas Gregor71395fa2009-11-04 00:56:37 +00007716 if (QTN)
7717 return TemplateName(QTN);
Fangrui Song6907ce22018-07-30 19:24:48 +00007718
Douglas Gregor71395fa2009-11-04 00:56:37 +00007719 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7720 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007721 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007722 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007723 } else {
7724 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007725 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007726 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007727
Douglas Gregorc42075a2010-02-04 18:10:26 +00007728 DependentTemplateName *CheckQTN
7729 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7730 assert(!CheckQTN && "Dependent template name canonicalization broken");
7731 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007732 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007733
Douglas Gregor71395fa2009-11-04 00:56:37 +00007734 DependentTemplateNames.InsertNode(QTN, InsertPos);
7735 return TemplateName(QTN);
7736}
7737
Fangrui Song6907ce22018-07-30 19:24:48 +00007738TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007739ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7740 TemplateName replacement) const {
7741 llvm::FoldingSetNodeID ID;
7742 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007743
7744 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007745 SubstTemplateTemplateParmStorage *subst
7746 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007747
John McCalld9dfe3a2011-06-30 08:33:18 +00007748 if (!subst) {
7749 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7750 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7751 }
7752
7753 return TemplateName(subst);
7754}
7755
Fangrui Song6907ce22018-07-30 19:24:48 +00007756TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007757ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7758 const TemplateArgument &ArgPack) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007759 auto &Self = const_cast<ASTContext &>(*this);
Douglas Gregor5590be02011-01-15 06:45:20 +00007760 llvm::FoldingSetNodeID ID;
7761 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007762
7763 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007764 SubstTemplateTemplateParmPackStorage *Subst
7765 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007766
Douglas Gregor5590be02011-01-15 06:45:20 +00007767 if (!Subst) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007768 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007769 ArgPack.pack_size(),
7770 ArgPack.pack_begin());
7771 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7772 }
7773
7774 return TemplateName(Subst);
7775}
7776
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007777/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007778/// TargetInfo, produce the corresponding type. The unsigned @p Type
7779/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007780CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007781 switch (Type) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007782 case TargetInfo::NoInt: return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007783 case TargetInfo::SignedChar: return SignedCharTy;
7784 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007785 case TargetInfo::SignedShort: return ShortTy;
7786 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7787 case TargetInfo::SignedInt: return IntTy;
7788 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7789 case TargetInfo::SignedLong: return LongTy;
7790 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7791 case TargetInfo::SignedLongLong: return LongLongTy;
7792 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7793 }
7794
David Blaikie83d382b2011-09-23 05:06:16 +00007795 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007796}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007797
7798//===----------------------------------------------------------------------===//
7799// Type Predicates.
7800//===----------------------------------------------------------------------===//
7801
Fariborz Jahanian96207692009-02-18 21:49:28 +00007802/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7803/// garbage collection attribute.
7804///
John McCall553d45a2011-01-12 00:34:59 +00007805Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007806 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007807 return Qualifiers::GCNone;
7808
Erik Pilkingtonfa983902018-10-30 20:31:30 +00007809 assert(getLangOpts().ObjC);
John McCall553d45a2011-01-12 00:34:59 +00007810 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7811
7812 // Default behaviour under objective-C's gc is for ObjC pointers
7813 // (or pointers to them) be treated as though they were declared
7814 // as __strong.
7815 if (GCAttrs == Qualifiers::GCNone) {
7816 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7817 return Qualifiers::Strong;
7818 else if (Ty->isPointerType())
7819 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7820 } else {
7821 // It's not valid to set GC attributes on anything that isn't a
7822 // pointer.
7823#ifndef NDEBUG
7824 QualType CT = Ty->getCanonicalTypeInternal();
Eugene Zelenko7855e772018-04-03 00:11:50 +00007825 while (const auto *AT = dyn_cast<ArrayType>(CT))
John McCall553d45a2011-01-12 00:34:59 +00007826 CT = AT->getElementType();
7827 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7828#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007829 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007830 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007831}
7832
Chris Lattner49af6a42008-04-07 06:51:04 +00007833//===----------------------------------------------------------------------===//
7834// Type Compatibility Testing
7835//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007836
Mike Stump11289f42009-09-09 15:08:12 +00007837/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007838/// compatible.
7839static bool areCompatVectorTypes(const VectorType *LHS,
7840 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007841 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007842 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007843 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007844}
7845
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007846bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7847 QualType SecondVec) {
7848 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7849 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7850
7851 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7852 return true;
7853
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007854 // Treat Neon vector types and most AltiVec vector types as if they are the
7855 // equivalent GCC vector types.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007856 const auto *First = FirstVec->getAs<VectorType>();
7857 const auto *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007858 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007859 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007860 First->getVectorKind() != VectorType::AltiVecPixel &&
7861 First->getVectorKind() != VectorType::AltiVecBool &&
7862 Second->getVectorKind() != VectorType::AltiVecPixel &&
7863 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007864 return true;
7865
7866 return false;
7867}
7868
Steve Naroff8e6aee52009-07-23 01:01:38 +00007869//===----------------------------------------------------------------------===//
7870// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7871//===----------------------------------------------------------------------===//
7872
7873/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7874/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007875bool
7876ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7877 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007878 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007879 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007880 for (auto *PI : rProto->protocols())
7881 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007882 return true;
7883 return false;
7884}
7885
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007886/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7887/// Class<pr1, ...>.
Fangrui Song6907ce22018-07-30 19:24:48 +00007888bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007889 QualType rhs) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007890 const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7891 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007892 assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
Fangrui Song6907ce22018-07-30 19:24:48 +00007893
Aaron Ballman83731462014-03-17 16:14:00 +00007894 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007895 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007896 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007897 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7898 match = true;
7899 break;
7900 }
7901 }
7902 if (!match)
7903 return false;
7904 }
7905 return true;
7906}
7907
Steve Naroff8e6aee52009-07-23 01:01:38 +00007908/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7909/// ObjCQualifiedIDType.
7910bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7911 bool compare) {
7912 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007913 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007914 lhs->isObjCIdType() || lhs->isObjCClassType())
7915 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007916 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007917 rhs->isObjCIdType() || rhs->isObjCClassType())
7918 return true;
7919
7920 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007921 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007922
Steve Naroff8e6aee52009-07-23 01:01:38 +00007923 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007924
Steve Naroff8e6aee52009-07-23 01:01:38 +00007925 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007926 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007927 // make sure we check the class hierarchy.
7928 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007929 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007930 // when comparing an id<P> on lhs with a static type on rhs,
7931 // see if static class implements all of id's protocols, directly or
7932 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007933 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007934 return false;
7935 }
7936 }
7937 // If there are no qualifiers and no interface, we have an 'id'.
7938 return true;
7939 }
Mike Stump11289f42009-09-09 15:08:12 +00007940 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007941 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007942 bool match = false;
7943
7944 // when comparing an id<P> on lhs with a static type on rhs,
7945 // see if static class implements all of id's protocols, directly or
7946 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007947 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007948 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7949 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7950 match = true;
7951 break;
7952 }
7953 }
Mike Stump11289f42009-09-09 15:08:12 +00007954 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007955 // make sure we check the class hierarchy.
7956 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007957 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007958 // when comparing an id<P> on lhs with a static type on rhs,
7959 // see if static class implements all of id's protocols, directly or
7960 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007961 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007962 match = true;
7963 break;
7964 }
7965 }
7966 }
7967 if (!match)
7968 return false;
7969 }
Mike Stump11289f42009-09-09 15:08:12 +00007970
Steve Naroff8e6aee52009-07-23 01:01:38 +00007971 return true;
7972 }
Mike Stump11289f42009-09-09 15:08:12 +00007973
Steve Naroff8e6aee52009-07-23 01:01:38 +00007974 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7975 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7976
Mike Stump11289f42009-09-09 15:08:12 +00007977 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007978 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007979 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007980 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007981 bool match = false;
7982
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007983 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007984 // see if static class implements all of id's protocols, directly or
7985 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007986 // First, lhs protocols in the qualifier list must be found, direct
7987 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007988 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007989 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7990 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7991 match = true;
7992 break;
7993 }
7994 }
7995 if (!match)
7996 return false;
7997 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007998
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007999 // Static class's protocols, or its super class or category protocols
8000 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
8001 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
8002 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8003 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8004 // This is rather dubious but matches gcc's behavior. If lhs has
8005 // no type qualifier and its class has no static protocol(s)
8006 // assume that it is mismatch.
8007 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
8008 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00008009 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008010 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00008011 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008012 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8013 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8014 match = true;
8015 break;
8016 }
8017 }
8018 if (!match)
8019 return false;
8020 }
8021 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00008022 return true;
8023 }
8024 return false;
8025}
8026
Eli Friedman47f77112008-08-22 00:56:42 +00008027/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00008028/// compatible for assignment from RHS to LHS. This handles validation of any
8029/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00008030bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
8031 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00008032 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8033 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8034
Steve Naroff1329fa02009-07-15 18:40:39 +00008035 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00008036 if (LHS->isObjCUnqualifiedIdOrClass() ||
8037 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00008038 return true;
8039
Douglas Gregorab209d82015-07-07 03:58:42 +00008040 // Function object that propagates a successful result or handles
8041 // __kindof types.
8042 auto finish = [&](bool succeeded) -> bool {
8043 if (succeeded)
8044 return true;
8045
8046 if (!RHS->isKindOfType())
8047 return false;
8048
8049 // Strip off __kindof and protocol qualifiers, then check whether
8050 // we can assign the other way.
8051 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8052 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8053 };
8054
8055 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8056 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8057 QualType(RHSOPT,0),
8058 false));
8059 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008060
Douglas Gregorab209d82015-07-07 03:58:42 +00008061 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8062 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
8063 QualType(RHSOPT,0)));
8064 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008065
John McCall8b07ec22010-05-15 11:32:37 +00008066 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00008067 if (LHS->getInterface() && RHS->getInterface()) {
8068 return finish(canAssignObjCInterfaces(LHS, RHS));
8069 }
Mike Stump11289f42009-09-09 15:08:12 +00008070
Steve Naroff8e6aee52009-07-23 01:01:38 +00008071 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008072}
8073
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008074/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Fangrui Song6907ce22018-07-30 19:24:48 +00008075/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008076/// arguments in block literals. When passed as arguments, passing 'A*' where
8077/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8078/// not OK. For the return type, the opposite is not OK.
8079bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8080 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008081 const ObjCObjectPointerType *RHSOPT,
8082 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008083
8084 // Function object that propagates a successful result or handles
8085 // __kindof types.
8086 auto finish = [&](bool succeeded) -> bool {
8087 if (succeeded)
8088 return true;
8089
8090 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8091 if (!Expected->isKindOfType())
8092 return false;
8093
8094 // Strip off __kindof and protocol qualifiers, then check whether
8095 // we can assign the other way.
8096 return canAssignObjCInterfacesInBlockPointer(
8097 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8098 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8099 BlockReturnType);
8100 };
8101
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008102 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008103 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00008104
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008105 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008106 return finish(RHSOPT->isObjCBuiltinType() ||
8107 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008108 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008109
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008110 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00008111 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8112 QualType(RHSOPT,0),
8113 false));
Fangrui Song6907ce22018-07-30 19:24:48 +00008114
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008115 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8116 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8117 if (LHS && RHS) { // We have 2 user-defined types.
8118 if (LHS != RHS) {
8119 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008120 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008121 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008122 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008123 }
8124 else
8125 return true;
8126 }
8127 return false;
8128}
8129
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008130/// Comparison routine for Objective-C protocols to be used with
8131/// llvm::array_pod_sort.
8132static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8133 ObjCProtocolDecl * const *rhs) {
8134 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008135}
8136
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008137/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008138/// of protocols inherited from two distinct objective-c pointer objects with
8139/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008140/// It is used to build composite qualifier list of the composite type of
8141/// the conditional expression involving two objective-c pointer objects.
Fangrui Song6907ce22018-07-30 19:24:48 +00008142static
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008143void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008144 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008145 const ObjCObjectPointerType *LHSOPT,
8146 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008147 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008148
John McCall8b07ec22010-05-15 11:32:37 +00008149 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8150 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8151 assert(LHS->getInterface() && "LHS must have an interface base");
8152 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008153
8154 // Add all of the protocols for the LHS.
8155 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8156
8157 // Start with the protocol qualifiers.
8158 for (auto proto : LHS->quals()) {
8159 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008160 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008161
8162 // Also add the protocols associated with the LHS interface.
8163 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8164
Raphael Isemannb23ccec2018-12-10 12:37:46 +00008165 // Add all of the protocols for the RHS.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008166 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8167
8168 // Start with the protocol qualifiers.
8169 for (auto proto : RHS->quals()) {
8170 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008171 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008172
8173 // Also add the protocols associated with the RHS interface.
8174 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8175
8176 // Compute the intersection of the collected protocol sets.
8177 for (auto proto : LHSProtocolSet) {
8178 if (RHSProtocolSet.count(proto))
8179 IntersectionSet.push_back(proto);
8180 }
8181
8182 // Compute the set of protocols that is implied by either the common type or
8183 // the protocols within the intersection.
8184 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8185 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8186
8187 // Remove any implied protocols from the list of inherited protocols.
8188 if (!ImpliedProtocols.empty()) {
8189 IntersectionSet.erase(
8190 std::remove_if(IntersectionSet.begin(),
8191 IntersectionSet.end(),
8192 [&](ObjCProtocolDecl *proto) -> bool {
8193 return ImpliedProtocols.count(proto) > 0;
8194 }),
8195 IntersectionSet.end());
8196 }
8197
8198 // Sort the remaining protocols by name.
8199 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8200 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008201}
8202
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008203/// Determine whether the first type is a subtype of the second.
8204static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8205 QualType rhs) {
8206 // Common case: two object pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008207 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8208 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008209 if (lhsOPT && rhsOPT)
8210 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8211
8212 // Two block pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008213 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8214 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008215 if (lhsBlock && rhsBlock)
8216 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8217
8218 // If either is an unqualified 'id' and the other is a block, it's
8219 // acceptable.
8220 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8221 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8222 return true;
8223
8224 return false;
8225}
8226
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008227// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008228static bool sameObjCTypeArgs(ASTContext &ctx,
8229 const ObjCInterfaceDecl *iface,
8230 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00008231 ArrayRef<QualType> rhsArgs,
8232 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008233 if (lhsArgs.size() != rhsArgs.size())
8234 return false;
8235
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008236 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008237 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008238 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8239 continue;
8240
8241 switch (typeParams->begin()[i]->getVariance()) {
8242 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00008243 if (!stripKindOf ||
8244 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8245 rhsArgs[i].stripObjCKindOfType(ctx))) {
8246 return false;
8247 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008248 break;
8249
8250 case ObjCTypeParamVariance::Covariant:
8251 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8252 return false;
8253 break;
8254
8255 case ObjCTypeParamVariance::Contravariant:
8256 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8257 return false;
8258 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00008259 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008260 }
8261
8262 return true;
8263}
8264
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008265QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008266 const ObjCObjectPointerType *Lptr,
8267 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00008268 const ObjCObjectType *LHS = Lptr->getObjectType();
8269 const ObjCObjectType *RHS = Rptr->getObjectType();
8270 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8271 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008272
8273 if (!LDecl || !RDecl)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008274 return {};
Douglas Gregore83b9562015-07-07 03:57:53 +00008275
Manman Renc46f7d12016-05-06 19:35:02 +00008276 // When either LHS or RHS is a kindof type, we should return a kindof type.
8277 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8278 // kindof(A).
8279 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8280
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008281 // Follow the left-hand side up the class hierarchy until we either hit a
8282 // root or find the RHS. Record the ancestors in case we don't find it.
8283 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8284 LHSAncestors;
8285 while (true) {
8286 // Record this ancestor. We'll need this if the common type isn't in the
8287 // path from the LHS to the root.
8288 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00008289
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008290 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8291 // Get the type arguments.
8292 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8293 bool anyChanges = false;
8294 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8295 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008296 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8297 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008298 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008299 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008300 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8301 // If only one has type arguments, the result will not have type
8302 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008303 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008304 anyChanges = true;
8305 }
8306
8307 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008308 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008309 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8310 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00008311 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008312 anyChanges = true;
8313
8314 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00008315 // If we need to return a kindof type but LHS is not a kindof type, we
8316 // build a new result type.
8317 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008318 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008319 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008320 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008321 return getObjCObjectPointerType(Result);
8322 }
8323
8324 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008325 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008326
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008327 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00008328 QualType LHSSuperType = LHS->getSuperClassType();
8329 if (LHSSuperType.isNull())
8330 break;
8331
8332 LHS = LHSSuperType->castAs<ObjCObjectType>();
8333 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008334
8335 // We didn't find anything by following the LHS to its root; now check
8336 // the RHS against the cached set of ancestors.
8337 while (true) {
8338 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8339 if (KnownLHS != LHSAncestors.end()) {
8340 LHS = KnownLHS->second;
8341
8342 // Get the type arguments.
8343 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8344 bool anyChanges = false;
8345 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8346 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008347 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8348 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008349 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008350 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008351 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8352 // If only one has type arguments, the result will not have type
8353 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008354 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008355 anyChanges = true;
8356 }
8357
8358 // Compute the intersection of protocols.
8359 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8360 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8361 Protocols);
8362 if (!Protocols.empty())
8363 anyChanges = true;
8364
Manman Renc46f7d12016-05-06 19:35:02 +00008365 // If we need to return a kindof type but RHS is not a kindof type, we
8366 // build a new result type.
8367 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008368 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008369 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008370 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008371 return getObjCObjectPointerType(Result);
8372 }
8373
8374 return getObjCObjectPointerType(QualType(RHS, 0));
8375 }
8376
8377 // Find the superclass of the RHS.
8378 QualType RHSSuperType = RHS->getSuperClassType();
8379 if (RHSSuperType.isNull())
8380 break;
8381
8382 RHS = RHSSuperType->castAs<ObjCObjectType>();
8383 }
8384
Eugene Zelenko7855e772018-04-03 00:11:50 +00008385 return {};
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008386}
8387
John McCall8b07ec22010-05-15 11:32:37 +00008388bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8389 const ObjCObjectType *RHS) {
8390 assert(LHS->getInterface() && "LHS is not an interface type");
8391 assert(RHS->getInterface() && "RHS is not an interface type");
8392
Chris Lattner49af6a42008-04-07 06:51:04 +00008393 // Verify that the base decls are compatible: the RHS must be a subclass of
8394 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008395 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8396 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8397 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008398 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008399
Douglas Gregore83b9562015-07-07 03:57:53 +00008400 // If the LHS has protocol qualifiers, determine whether all of them are
8401 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8402 // LHS).
8403 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008404 // OK if conversion of LHS to SuperClass results in narrowing of types
8405 // ; i.e., SuperClass may implement at least one of the protocols
8406 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8407 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8408 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8409 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8410 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8411 // qualifiers.
8412 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008413 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008414 // If there is no protocols associated with RHS, it is not a match.
8415 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008416 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008417
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008418 for (const auto *LHSProto : LHS->quals()) {
8419 bool SuperImplementsProtocol = false;
8420 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8421 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8422 SuperImplementsProtocol = true;
8423 break;
8424 }
8425 if (!SuperImplementsProtocol)
8426 return false;
8427 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008428 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008429
8430 // If the LHS is specialized, we may need to check type arguments.
8431 if (LHS->isSpecialized()) {
8432 // Follow the superclass chain until we've matched the LHS class in the
8433 // hierarchy. This substitutes type arguments through.
8434 const ObjCObjectType *RHSSuper = RHS;
8435 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8436 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8437
8438 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008439 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008440 !sameObjCTypeArgs(*this, LHS->getInterface(),
8441 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008442 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008443 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008444 }
8445 }
8446
8447 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008448}
8449
Steve Naroffb7605152009-02-12 17:52:19 +00008450bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8451 // get the "pointed to" types
Eugene Zelenko7855e772018-04-03 00:11:50 +00008452 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8453 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008454
Steve Naroff7cae42b2009-07-10 23:34:53 +00008455 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008456 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008457
8458 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8459 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008460}
8461
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008462bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8463 return canAssignObjCInterfaces(
8464 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8465 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8466}
8467
Mike Stump11289f42009-09-09 15:08:12 +00008468/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008469/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008470/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008471/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008472bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8473 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008474 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008475 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008476
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008477 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008478}
8479
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008480bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008481 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008482}
8483
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008484bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8485 return !mergeTypes(LHS, RHS, true).isNull();
8486}
8487
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008488/// mergeTransparentUnionType - if T is a transparent union type and a member
8489/// of T is compatible with SubType, return the merged type, else return
8490/// QualType()
8491QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8492 bool OfBlockPointer,
8493 bool Unqualified) {
8494 if (const RecordType *UT = T->getAsUnionType()) {
8495 RecordDecl *UD = UT->getDecl();
8496 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008497 for (const auto *I : UD->fields()) {
8498 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008499 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8500 if (!MT.isNull())
8501 return MT;
8502 }
8503 }
8504 }
8505
Eugene Zelenko7855e772018-04-03 00:11:50 +00008506 return {};
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008507}
8508
Alp Toker9cacbab2014-01-20 20:26:09 +00008509/// mergeFunctionParameterTypes - merge two types which appear as function
8510/// parameter types
8511QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8512 bool OfBlockPointer,
8513 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008514 // GNU extension: two types are compatible if they appear as a function
8515 // argument, one of the types is a transparent union type and the other
8516 // type is compatible with a union member
8517 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8518 Unqualified);
8519 if (!lmerge.isNull())
8520 return lmerge;
8521
8522 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8523 Unqualified);
8524 if (!rmerge.isNull())
8525 return rmerge;
8526
8527 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8528}
8529
Fangrui Song6907ce22018-07-30 19:24:48 +00008530QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008531 bool OfBlockPointer,
8532 bool Unqualified) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008533 const auto *lbase = lhs->getAs<FunctionType>();
8534 const auto *rbase = rhs->getAs<FunctionType>();
8535 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8536 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008537 bool allLTypes = true;
8538 bool allRTypes = true;
8539
8540 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008541 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008542 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008543 QualType RHS = rbase->getReturnType();
8544 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008545 bool UnqualifiedResult = Unqualified;
8546 if (!UnqualifiedResult)
8547 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008548 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008549 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008550 else
Alp Toker314cc812014-01-25 16:55:45 +00008551 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008552 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008553 if (retType.isNull())
8554 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00008555
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008556 if (Unqualified)
8557 retType = retType.getUnqualifiedType();
8558
Alp Toker314cc812014-01-25 16:55:45 +00008559 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8560 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008561 if (Unqualified) {
8562 LRetType = LRetType.getUnqualifiedType();
8563 RRetType = RRetType.getUnqualifiedType();
8564 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008565
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008566 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008567 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008568 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008569 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008570
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008571 // FIXME: double check this
8572 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8573 // rbase->getRegParmAttr() != 0 &&
8574 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008575 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8576 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008577
Douglas Gregor8c940862010-01-18 17:14:39 +00008578 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008579 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008580 return {};
Mike Stump11289f42009-09-09 15:08:12 +00008581
John McCall8c6b56f2010-12-15 01:06:38 +00008582 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008583 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008584 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008585 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008586 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008587
John McCall31168b02011-06-15 23:02:42 +00008588 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008589 return {};
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008590 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008591 return {};
Oren Ben Simhon220671a2018-03-17 13:31:35 +00008592 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008593 return {};
John McCall31168b02011-06-15 23:02:42 +00008594
John McCall8c6b56f2010-12-15 01:06:38 +00008595 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8596 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008597
Rafael Espindola8778c282012-11-29 16:09:03 +00008598 if (lbaseInfo.getNoReturn() != NoReturn)
8599 allLTypes = false;
8600 if (rbaseInfo.getNoReturn() != NoReturn)
8601 allRTypes = false;
8602
John McCall31168b02011-06-15 23:02:42 +00008603 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008604
Eli Friedman47f77112008-08-22 00:56:42 +00008605 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008606 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8607 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008608 // Compatible functions must have the same number of parameters
8609 if (lproto->getNumParams() != rproto->getNumParams())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008610 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008611
8612 // Variadic and non-variadic functions aren't compatible
8613 if (lproto->isVariadic() != rproto->isVariadic())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008614 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008615
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008616 if (lproto->getMethodQuals() != rproto->getMethodQuals())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008617 return {};
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008618
Akira Hatanaka98a49332017-09-22 00:41:05 +00008619 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8620 bool canUseLeft, canUseRight;
8621 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8622 newParamInfos))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008623 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008624
Akira Hatanaka98a49332017-09-22 00:41:05 +00008625 if (!canUseLeft)
8626 allLTypes = false;
8627 if (!canUseRight)
8628 allRTypes = false;
8629
Alp Toker601b22c2014-01-21 23:35:24 +00008630 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008631 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008632 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8633 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8634 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8635 QualType paramType = mergeFunctionParameterTypes(
8636 lParamType, rParamType, OfBlockPointer, Unqualified);
8637 if (paramType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008638 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008639
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008640 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008641 paramType = paramType.getUnqualifiedType();
8642
8643 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008644 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008645 lParamType = lParamType.getUnqualifiedType();
8646 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008647 }
Alp Toker601b22c2014-01-21 23:35:24 +00008648
8649 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008650 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008651 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008652 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008653 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008654
Eli Friedman47f77112008-08-22 00:56:42 +00008655 if (allLTypes) return lhs;
8656 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008657
8658 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8659 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008660 EPI.ExtParameterInfos =
8661 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008662 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008663 }
8664
8665 if (lproto) allRTypes = false;
8666 if (rproto) allLTypes = false;
8667
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008668 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008669 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008670 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008671 if (proto->isVariadic())
8672 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008673 // Check that the types are compatible with the types that
8674 // would result from default argument promotions (C99 6.7.5.3p15).
8675 // The only types actually affected are promotable integer
8676 // types and floats, which would be passed as a different
8677 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008678 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8679 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008680
Eli Friedman448ce402012-08-30 00:44:15 +00008681 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008682 // to pass enum values.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008683 if (const auto *Enum = paramTy->getAs<EnumType>()) {
Alp Toker601b22c2014-01-21 23:35:24 +00008684 paramTy = Enum->getDecl()->getIntegerType();
8685 if (paramTy.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008686 return {};
Eli Friedman448ce402012-08-30 00:44:15 +00008687 }
Alp Toker601b22c2014-01-21 23:35:24 +00008688
8689 if (paramTy->isPromotableIntegerType() ||
8690 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008691 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008692 }
8693
8694 if (allLTypes) return lhs;
8695 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008696
8697 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8698 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008699 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008700 }
8701
8702 if (allLTypes) return lhs;
8703 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008704 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008705}
8706
John McCall433c2e62013-03-21 00:10:07 +00008707/// Given that we have an enum type and a non-enum type, try to merge them.
8708static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8709 QualType other, bool isBlockReturnType) {
8710 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8711 // a signed integer type, or an unsigned integer type.
8712 // Compatibility is based on the underlying type, not the promotion
8713 // type.
8714 QualType underlyingType = ET->getDecl()->getIntegerType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00008715 if (underlyingType.isNull())
8716 return {};
John McCall433c2e62013-03-21 00:10:07 +00008717 if (Context.hasSameType(underlyingType, other))
8718 return other;
8719
8720 // In block return types, we're more permissive and accept any
8721 // integral type of the same size.
8722 if (isBlockReturnType && other->isIntegerType() &&
8723 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8724 return other;
8725
Eugene Zelenko7855e772018-04-03 00:11:50 +00008726 return {};
John McCall433c2e62013-03-21 00:10:07 +00008727}
8728
Fangrui Song6907ce22018-07-30 19:24:48 +00008729QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008730 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008731 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008732 // C++ [expr]: If an expression initially has the type "reference to T", the
8733 // type is adjusted to "T" prior to any further analysis, the expression
8734 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008735 // expression is an lvalue unless the reference is an rvalue reference and
8736 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008737 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8738 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008739
8740 if (Unqualified) {
8741 LHS = LHS.getUnqualifiedType();
8742 RHS = RHS.getUnqualifiedType();
8743 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008744
Eli Friedman47f77112008-08-22 00:56:42 +00008745 QualType LHSCan = getCanonicalType(LHS),
8746 RHSCan = getCanonicalType(RHS);
8747
8748 // If two types are identical, they are compatible.
8749 if (LHSCan == RHSCan)
8750 return LHS;
8751
John McCall8ccfcb52009-09-24 19:53:00 +00008752 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008753 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8754 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008755 if (LQuals != RQuals) {
8756 // If any of these qualifiers are different, we have a type
8757 // mismatch.
8758 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008759 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008760 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8761 LQuals.hasUnaligned() != RQuals.hasUnaligned())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008762 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008763
8764 // Exactly one GC qualifier difference is allowed: __strong is
8765 // okay if the other type has no GC qualifier but is an Objective
8766 // C object pointer (i.e. implicitly strong by default). We fix
8767 // this by pretending that the unqualified type was actually
8768 // qualified __strong.
8769 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8770 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8771 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8772
8773 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008774 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008775
8776 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8777 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8778 }
8779 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8780 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8781 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008782 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008783 }
8784
8785 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008786
Eli Friedmandcca6332009-06-01 01:22:52 +00008787 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8788 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008789
Chris Lattnerfd652912008-01-14 05:45:46 +00008790 // We want to consider the two function types to be the same for these
8791 // comparisons, just force one to the other.
8792 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8793 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008794
8795 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008796 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8797 LHSClass = Type::ConstantArray;
8798 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8799 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008800
John McCall8b07ec22010-05-15 11:32:37 +00008801 // ObjCInterfaces are just specialized ObjCObjects.
8802 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8803 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8804
Nate Begemance4d7fc2008-04-18 23:10:10 +00008805 // Canonicalize ExtVector -> Vector.
8806 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8807 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008808
Chris Lattner95554662008-04-07 05:43:21 +00008809 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008810 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008811 // Note that we only have special rules for turning block enum
8812 // returns into block int returns, not vice-versa.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008813 if (const auto *ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008814 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008815 }
John McCall9dd450b2009-09-21 23:43:11 +00008816 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008817 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008818 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008819 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008820 if (OfBlockPointer && !BlockReturnType) {
8821 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8822 return LHS;
8823 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8824 return RHS;
8825 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008826
Eugene Zelenko7855e772018-04-03 00:11:50 +00008827 return {};
Steve Naroff32e44c02007-10-15 20:41:53 +00008828 }
Eli Friedman47f77112008-08-22 00:56:42 +00008829
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008830 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008831 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008832#define TYPE(Class, Base)
8833#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008834#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008835#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8836#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8837#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008838 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008839
Richard Smith27d807c2013-04-30 13:56:41 +00008840 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008841 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008842 case Type::LValueReference:
8843 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008844 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008845 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008846
John McCall8b07ec22010-05-15 11:32:37 +00008847 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008848 case Type::IncompleteArray:
8849 case Type::VariableArray:
8850 case Type::FunctionProto:
8851 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008852 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008853
Chris Lattnerfd652912008-01-14 05:45:46 +00008854 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008855 {
8856 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008857 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8858 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008859 if (Unqualified) {
8860 LHSPointee = LHSPointee.getUnqualifiedType();
8861 RHSPointee = RHSPointee.getUnqualifiedType();
8862 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008863 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008864 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008865 if (ResultType.isNull())
8866 return {};
Eli Friedman091a9ac2009-06-02 05:28:56 +00008867 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008868 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008869 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008870 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008871 return getPointerType(ResultType);
8872 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008873 case Type::BlockPointer:
8874 {
8875 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008876 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8877 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008878 if (Unqualified) {
8879 LHSPointee = LHSPointee.getUnqualifiedType();
8880 RHSPointee = RHSPointee.getUnqualifiedType();
8881 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008882 if (getLangOpts().OpenCL) {
8883 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8884 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8885 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8886 // 6.12.5) thus the following check is asymmetric.
8887 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008888 return {};
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008889 LHSPteeQual.removeAddressSpace();
8890 RHSPteeQual.removeAddressSpace();
8891 LHSPointee =
8892 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8893 RHSPointee =
8894 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8895 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008896 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8897 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008898 if (ResultType.isNull())
8899 return {};
Steve Naroff68e167d2008-12-10 17:49:55 +00008900 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8901 return LHS;
8902 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8903 return RHS;
8904 return getBlockPointerType(ResultType);
8905 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008906 case Type::Atomic:
8907 {
8908 // Merge two pointer types, while trying to preserve typedef info
8909 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8910 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8911 if (Unqualified) {
8912 LHSValue = LHSValue.getUnqualifiedType();
8913 RHSValue = RHSValue.getUnqualifiedType();
8914 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008915 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
Eli Friedman0dfb8892011-10-06 23:00:33 +00008916 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008917 if (ResultType.isNull())
8918 return {};
Eli Friedman0dfb8892011-10-06 23:00:33 +00008919 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8920 return LHS;
8921 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8922 return RHS;
8923 return getAtomicType(ResultType);
8924 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008925 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008926 {
8927 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8928 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8929 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008930 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008931
8932 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8933 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008934 if (Unqualified) {
8935 LHSElem = LHSElem.getUnqualifiedType();
8936 RHSElem = RHSElem.getUnqualifiedType();
8937 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008938
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008939 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008940 if (ResultType.isNull())
8941 return {};
Jeremy Morse8129c5c2018-06-05 09:18:26 +00008942
8943 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8944 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
8945
8946 // If either side is a variable array, and both are complete, check whether
8947 // the current dimension is definite.
8948 if (LVAT || RVAT) {
8949 auto SizeFetch = [this](const VariableArrayType* VAT,
8950 const ConstantArrayType* CAT)
8951 -> std::pair<bool,llvm::APInt> {
8952 if (VAT) {
8953 llvm::APSInt TheInt;
8954 Expr *E = VAT->getSizeExpr();
8955 if (E && E->isIntegerConstantExpr(TheInt, *this))
8956 return std::make_pair(true, TheInt);
8957 else
8958 return std::make_pair(false, TheInt);
8959 } else if (CAT) {
8960 return std::make_pair(true, CAT->getSize());
8961 } else {
8962 return std::make_pair(false, llvm::APInt());
8963 }
8964 };
8965
8966 bool HaveLSize, HaveRSize;
8967 llvm::APInt LSize, RSize;
8968 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
8969 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
8970 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
8971 return {}; // Definite, but unequal, array dimension
8972 }
8973
Chris Lattner465fa322008-10-05 17:34:18 +00008974 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8975 return LHS;
8976 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8977 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008978 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8979 ArrayType::ArraySizeModifier(), 0);
8980 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8981 ArrayType::ArraySizeModifier(), 0);
Chris Lattner465fa322008-10-05 17:34:18 +00008982 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8983 return LHS;
8984 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8985 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008986 if (LVAT) {
8987 // FIXME: This isn't correct! But tricky to implement because
8988 // the array's size has to be the size of LHS, but the type
8989 // has to be different.
8990 return LHS;
8991 }
8992 if (RVAT) {
8993 // FIXME: This isn't correct! But tricky to implement because
8994 // the array's size has to be the size of RHS, but the type
8995 // has to be different.
8996 return RHS;
8997 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008998 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8999 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00009000 return getIncompleteArrayType(ResultType,
9001 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00009002 }
Chris Lattnerfd652912008-01-14 05:45:46 +00009003 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009004 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009005 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009006 case Type::Enum:
Eugene Zelenko7855e772018-04-03 00:11:50 +00009007 return {};
Chris Lattnerfd652912008-01-14 05:45:46 +00009008 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009009 // Only exactly equal builtin types are compatible, which is tested above.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009010 return {};
Daniel Dunbar804c0442009-01-28 21:22:12 +00009011 case Type::Complex:
9012 // Distinct complex types are incompatible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009013 return {};
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009014 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00009015 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00009016 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
9017 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00009018 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009019 return {};
John McCall8b07ec22010-05-15 11:32:37 +00009020 case Type::ObjCObject: {
9021 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00009022 // FIXME: This should be type compatibility, e.g. whether
9023 // "LHS x; RHS x;" at global scope is legal.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009024 const auto *LHSIface = LHS->getAs<ObjCObjectType>();
9025 const auto *RHSIface = RHS->getAs<ObjCObjectType>();
John McCall8b07ec22010-05-15 11:32:37 +00009026 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00009027 return LHS;
9028
Eugene Zelenko7855e772018-04-03 00:11:50 +00009029 return {};
Cedric Venet4fc88b72009-02-21 17:14:49 +00009030 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009031 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009032 if (OfBlockPointer) {
9033 if (canAssignObjCInterfacesInBlockPointer(
9034 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00009035 RHS->getAs<ObjCObjectPointerType>(),
9036 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00009037 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009038 return {};
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009039 }
John McCall9dd450b2009-09-21 23:43:11 +00009040 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
9041 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00009042 return LHS;
9043
Eugene Zelenko7855e772018-04-03 00:11:50 +00009044 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009045 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00009046 assert(LHS != RHS &&
9047 "Equivalent pipe types should have already been handled!");
Eugene Zelenko7855e772018-04-03 00:11:50 +00009048 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009049 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009050
David Blaikie8a40f702012-01-17 06:56:22 +00009051 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00009052}
Ted Kremenekfc581a92007-10-31 17:10:13 +00009053
Akira Hatanaka98a49332017-09-22 00:41:05 +00009054bool ASTContext::mergeExtParameterInfo(
9055 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9056 bool &CanUseFirst, bool &CanUseSecond,
9057 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9058 assert(NewParamInfos.empty() && "param info list not empty");
9059 CanUseFirst = CanUseSecond = true;
9060 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9061 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9062
John McCall18afab72016-03-01 00:49:02 +00009063 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00009064 // we match if and only if the second type also doesn't have them.
9065 if (!FirstHasInfo && !SecondHasInfo)
9066 return true;
John McCall18afab72016-03-01 00:49:02 +00009067
Akira Hatanaka98a49332017-09-22 00:41:05 +00009068 bool NeedParamInfo = false;
9069 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9070 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00009071
Akira Hatanaka98a49332017-09-22 00:41:05 +00009072 for (size_t I = 0; I < E; ++I) {
9073 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9074 if (FirstHasInfo)
9075 FirstParam = FirstFnType->getExtParameterInfo(I);
9076 if (SecondHasInfo)
9077 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00009078
Akira Hatanaka98a49332017-09-22 00:41:05 +00009079 // Cannot merge unless everything except the noescape flag matches.
9080 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00009081 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00009082
9083 bool FirstNoEscape = FirstParam.isNoEscape();
9084 bool SecondNoEscape = SecondParam.isNoEscape();
9085 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9086 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9087 if (NewParamInfos.back().getOpaqueValue())
9088 NeedParamInfo = true;
9089 if (FirstNoEscape != IsNoEscape)
9090 CanUseFirst = false;
9091 if (SecondNoEscape != IsNoEscape)
9092 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00009093 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00009094
9095 if (!NeedParamInfo)
9096 NewParamInfos.clear();
9097
Fariborz Jahanian97676972011-09-28 21:52:05 +00009098 return true;
9099}
9100
Chandler Carruth21c90602015-12-30 03:24:14 +00009101void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9102 ObjCLayouts[CD] = nullptr;
9103}
9104
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009105/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9106/// 'RHS' attributes and returns the merged version; including for function
9107/// return types.
9108QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9109 QualType LHSCan = getCanonicalType(LHS),
9110 RHSCan = getCanonicalType(RHS);
9111 // If two types are identical, they are compatible.
9112 if (LHSCan == RHSCan)
9113 return LHS;
9114 if (RHSCan->isFunctionType()) {
9115 if (!LHSCan->isFunctionType())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009116 return {};
Alp Toker314cc812014-01-25 16:55:45 +00009117 QualType OldReturnType =
9118 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009119 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00009120 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009121 QualType ResReturnType =
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009122 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9123 if (ResReturnType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009124 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009125 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9126 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9127 // In either case, use OldReturnType to build the new function type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009128 const auto *F = LHS->getAs<FunctionType>();
9129 if (const auto *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009130 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9131 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00009132 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00009133 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009134 return ResultType;
9135 }
9136 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009137 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009138 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009139
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009140 // If the qualifiers are different, the types can still be merged.
9141 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9142 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9143 if (LQuals != RQuals) {
9144 // If any of these qualifiers are different, we have a type mismatch.
9145 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9146 LQuals.getAddressSpace() != RQuals.getAddressSpace())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009147 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009148
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009149 // Exactly one GC qualifier difference is allowed: __strong is
9150 // okay if the other type has no GC qualifier but is an Objective
9151 // C object pointer (i.e. implicitly strong by default). We fix
9152 // this by pretending that the unqualified type was actually
9153 // qualified __strong.
9154 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9155 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9156 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
Fangrui Song6907ce22018-07-30 19:24:48 +00009157
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009158 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009159 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009160
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009161 if (GC_L == Qualifiers::Strong)
9162 return LHS;
9163 if (GC_R == Qualifiers::Strong)
9164 return RHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009165 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009166 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009167
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009168 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
9169 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9170 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9171 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9172 if (ResQT == LHSBaseQT)
9173 return LHS;
9174 if (ResQT == RHSBaseQT)
9175 return RHS;
9176 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009177 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009178}
9179
Chris Lattner4ba0cef2008-04-07 07:01:58 +00009180//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009181// Integer Predicates
9182//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00009183
Jay Foad39c79802011-01-12 09:06:06 +00009184unsigned ASTContext::getIntWidth(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009185 if (const auto *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00009186 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00009187 if (T->isBooleanType())
9188 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00009189 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009190 return (unsigned)getTypeSize(T);
9191}
9192
Abramo Bagnara13640492012-09-09 10:21:24 +00009193QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Leonard Chanab80f3c2018-06-14 14:53:51 +00009194 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9195 "Unexpected type");
Fangrui Song6907ce22018-07-30 19:24:48 +00009196
Chris Lattnerec3a1562009-10-17 20:33:28 +00009197 // Turn <4 x signed int> -> <4 x unsigned int>
Eugene Zelenko7855e772018-04-03 00:11:50 +00009198 if (const auto *VTy = T->getAs<VectorType>())
Chris Lattnerec3a1562009-10-17 20:33:28 +00009199 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00009200 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00009201
9202 // For enums, we return the unsigned version of the base type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009203 if (const auto *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009204 T = ETy->getDecl()->getIntegerType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009205
Eugene Zelenko7855e772018-04-03 00:11:50 +00009206 const auto *BTy = T->getAs<BuiltinType>();
Leonard Chanab80f3c2018-06-14 14:53:51 +00009207 assert(BTy && "Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009208 switch (BTy->getKind()) {
9209 case BuiltinType::Char_S:
9210 case BuiltinType::SChar:
9211 return UnsignedCharTy;
9212 case BuiltinType::Short:
9213 return UnsignedShortTy;
9214 case BuiltinType::Int:
9215 return UnsignedIntTy;
9216 case BuiltinType::Long:
9217 return UnsignedLongTy;
9218 case BuiltinType::LongLong:
9219 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00009220 case BuiltinType::Int128:
9221 return UnsignedInt128Ty;
Leonard Chanab80f3c2018-06-14 14:53:51 +00009222
9223 case BuiltinType::ShortAccum:
9224 return UnsignedShortAccumTy;
9225 case BuiltinType::Accum:
9226 return UnsignedAccumTy;
9227 case BuiltinType::LongAccum:
9228 return UnsignedLongAccumTy;
9229 case BuiltinType::SatShortAccum:
9230 return SatUnsignedShortAccumTy;
9231 case BuiltinType::SatAccum:
9232 return SatUnsignedAccumTy;
9233 case BuiltinType::SatLongAccum:
9234 return SatUnsignedLongAccumTy;
9235 case BuiltinType::ShortFract:
9236 return UnsignedShortFractTy;
9237 case BuiltinType::Fract:
9238 return UnsignedFractTy;
9239 case BuiltinType::LongFract:
9240 return UnsignedLongFractTy;
9241 case BuiltinType::SatShortFract:
9242 return SatUnsignedShortFractTy;
9243 case BuiltinType::SatFract:
9244 return SatUnsignedFractTy;
9245 case BuiltinType::SatLongFract:
9246 return SatUnsignedLongFractTy;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009247 default:
Leonard Chanab80f3c2018-06-14 14:53:51 +00009248 llvm_unreachable("Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009249 }
9250}
9251
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009252ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00009253
Richard Smith1fa5d642013-05-11 05:45:24 +00009254void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9255 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00009256
9257//===----------------------------------------------------------------------===//
9258// Builtin Type Computation
9259//===----------------------------------------------------------------------===//
9260
9261/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00009262/// pointer over the consumed characters. This returns the resultant type. If
9263/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9264/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9265/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009266///
9267/// RequiresICE is filled in on return to indicate whether the value is required
9268/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00009269static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00009270 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009271 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00009272 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00009273 // Modifiers.
9274 int HowLong = 0;
9275 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009276 RequiresICE = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009277
Chris Lattnerdc226c22010-10-01 22:42:38 +00009278 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00009279 bool Done = false;
9280 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009281 bool IsSpecial = false;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009282 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00009283 while (!Done) {
9284 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00009285 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00009286 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009287 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00009288 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009289 case 'S':
9290 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9291 assert(!Signed && "Can't use 'S' modifier multiple times!");
9292 Signed = true;
9293 break;
9294 case 'U':
9295 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00009296 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009297 Unsigned = true;
9298 break;
9299 case 'L':
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009300 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009301 assert(HowLong <= 2 && "Can't have LLLL modifier");
9302 ++HowLong;
9303 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009304 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009305 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009306 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009307 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009308 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009309 IsSpecial = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009310 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009311 if (Context.getTargetInfo().getLongWidth() == 32)
9312 ++HowLong;
9313 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00009314 case 'W':
9315 // This modifier represents int64 type.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009316 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00009317 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009318 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009319 IsSpecial = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009320 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00009321 switch (Context.getTargetInfo().getInt64Type()) {
9322 default:
9323 llvm_unreachable("Unexpected integer type");
9324 case TargetInfo::SignedLong:
9325 HowLong = 1;
9326 break;
9327 case TargetInfo::SignedLongLong:
9328 HowLong = 2;
9329 break;
9330 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00009331 break;
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009332 case 'Z':
9333 // This modifier represents int32 type.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009334 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009335 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
9336 #ifndef NDEBUG
9337 IsSpecial = true;
9338 #endif
9339 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
9340 default:
9341 llvm_unreachable("Unexpected integer type");
9342 case TargetInfo::SignedInt:
9343 HowLong = 0;
9344 break;
9345 case TargetInfo::SignedLong:
9346 HowLong = 1;
9347 break;
9348 case TargetInfo::SignedLongLong:
9349 HowLong = 2;
9350 break;
9351 }
9352 break;
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009353 case 'O':
9354 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9355 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
9356 #ifndef NDEBUG
9357 IsSpecial = true;
9358 #endif
9359 if (Context.getLangOpts().OpenCL)
9360 HowLong = 1;
9361 else
9362 HowLong = 2;
9363 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009364 }
9365 }
9366
9367 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00009368
Chris Lattnerecd79c62009-06-14 00:45:47 +00009369 // Read the base type.
9370 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00009371 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009372 case 'v':
9373 assert(HowLong == 0 && !Signed && !Unsigned &&
9374 "Bad modifiers used with 'v'!");
9375 Type = Context.VoidTy;
9376 break;
Jack Carter24bef982013-08-15 15:16:57 +00009377 case 'h':
9378 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00009379 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00009380 Type = Context.HalfTy;
9381 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009382 case 'f':
9383 assert(HowLong == 0 && !Signed && !Unsigned &&
9384 "Bad modifiers used with 'f'!");
9385 Type = Context.FloatTy;
9386 break;
9387 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009388 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00009389 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009390 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00009391 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009392 else if (HowLong == 2)
9393 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009394 else
9395 Type = Context.DoubleTy;
9396 break;
9397 case 's':
9398 assert(HowLong == 0 && "Bad modifiers used with 's'!");
9399 if (Unsigned)
9400 Type = Context.UnsignedShortTy;
9401 else
9402 Type = Context.ShortTy;
9403 break;
9404 case 'i':
9405 if (HowLong == 3)
9406 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9407 else if (HowLong == 2)
9408 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9409 else if (HowLong == 1)
9410 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9411 else
9412 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9413 break;
9414 case 'c':
9415 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9416 if (Signed)
9417 Type = Context.SignedCharTy;
9418 else if (Unsigned)
9419 Type = Context.UnsignedCharTy;
9420 else
9421 Type = Context.CharTy;
9422 break;
9423 case 'b': // boolean
9424 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9425 Type = Context.BoolTy;
9426 break;
9427 case 'z': // size_t.
9428 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9429 Type = Context.getSizeType();
9430 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00009431 case 'w': // wchar_t.
9432 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9433 Type = Context.getWideCharType();
9434 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009435 case 'F':
9436 Type = Context.getCFConstantStringType();
9437 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00009438 case 'G':
9439 Type = Context.getObjCIdType();
9440 break;
9441 case 'H':
9442 Type = Context.getObjCSelType();
9443 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00009444 case 'M':
9445 Type = Context.getObjCSuperType();
9446 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009447 case 'a':
9448 Type = Context.getBuiltinVaListType();
9449 assert(!Type.isNull() && "builtin va list type not initialized!");
9450 break;
9451 case 'A':
9452 // This is a "reference" to a va_list; however, what exactly
9453 // this means depends on how va_list is defined. There are two
9454 // different kinds of va_list: ones passed by value, and ones
9455 // passed by reference. An example of a by-value va_list is
9456 // x86, where va_list is a char*. An example of by-ref va_list
9457 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9458 // we want this argument to be a char*&; for x86-64, we want
9459 // it to be a __va_list_tag*.
9460 Type = Context.getBuiltinVaListType();
9461 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009462 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009463 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009464 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009465 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009466 break;
9467 case 'V': {
9468 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009469 unsigned NumElements = strtoul(Str, &End, 10);
9470 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009471 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009472
Fangrui Song6907ce22018-07-30 19:24:48 +00009473 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009474 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009475 assert(!RequiresICE && "Can't require vector ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009476
Chris Lattnerdc226c22010-10-01 22:42:38 +00009477 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009478 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009479 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009480 break;
9481 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009482 case 'E': {
9483 char *End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009484
Douglas Gregorfed66992012-06-07 18:08:25 +00009485 unsigned NumElements = strtoul(Str, &End, 10);
9486 assert(End != Str && "Missing vector size");
Fangrui Song6907ce22018-07-30 19:24:48 +00009487
Douglas Gregorfed66992012-06-07 18:08:25 +00009488 Str = End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009489
Douglas Gregorfed66992012-06-07 18:08:25 +00009490 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009491 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009492 Type = Context.getExtVectorType(ElementType, NumElements);
Fangrui Song6907ce22018-07-30 19:24:48 +00009493 break;
Douglas Gregorfed66992012-06-07 18:08:25 +00009494 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009495 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009496 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009497 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009498 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009499 Type = Context.getComplexType(ElementType);
9500 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00009501 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009502 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009503 Type = Context.getPointerDiffType();
9504 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009505 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009506 Type = Context.getFILEType();
9507 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009508 Error = ASTContext::GE_Missing_stdio;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009509 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009510 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009511 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009512 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009513 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009514 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009515 else
9516 Type = Context.getjmp_bufType();
9517
Mike Stump2adb4da2009-07-28 23:47:15 +00009518 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009519 Error = ASTContext::GE_Missing_setjmp;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009520 return {};
Mike Stump2adb4da2009-07-28 23:47:15 +00009521 }
9522 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009523 case 'K':
9524 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9525 Type = Context.getucontext_tType();
9526
9527 if (Type.isNull()) {
9528 Error = ASTContext::GE_Missing_ucontext;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009529 return {};
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009530 }
9531 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009532 case 'p':
9533 Type = Context.getProcessIDType();
9534 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009535 }
Mike Stump11289f42009-09-09 15:08:12 +00009536
Chris Lattnerdc226c22010-10-01 22:42:38 +00009537 // If there are modifiers and if we're allowed to parse them, go for it.
9538 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009539 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009540 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009541 default: Done = true; --Str; break;
9542 case '*':
9543 case '&': {
9544 // Both pointers and references can have their pointee types
9545 // qualified with an address space.
9546 char *End;
9547 unsigned AddrSpace = strtoul(Str, &End, 10);
Matt Arsenaultc65f9662018-08-02 12:14:28 +00009548 if (End != Str) {
9549 // Note AddrSpace == 0 is not the same as an unspecified address space.
9550 Type = Context.getAddrSpaceQualType(
9551 Type,
9552 Context.getLangASForBuiltinAddressSpace(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009553 Str = End;
9554 }
9555 if (c == '*')
9556 Type = Context.getPointerType(Type);
9557 else
9558 Type = Context.getLValueReferenceType(Type);
9559 break;
9560 }
9561 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9562 case 'C':
9563 Type = Type.withConst();
9564 break;
9565 case 'D':
9566 Type = Context.getVolatileType(Type);
9567 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009568 case 'R':
9569 Type = Type.withRestrict();
9570 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009571 }
9572 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009573
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009574 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Fangrui Song6907ce22018-07-30 19:24:48 +00009575 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009576
Chris Lattnerecd79c62009-06-14 00:45:47 +00009577 return Type;
9578}
9579
9580/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009581QualType ASTContext::GetBuiltinType(unsigned Id,
9582 GetBuiltinTypeError &Error,
9583 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009584 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00009585 if (TypeStr[0] == '\0') {
9586 Error = GE_Missing_type;
9587 return {};
9588 }
Mike Stump11289f42009-09-09 15:08:12 +00009589
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009590 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009591
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009592 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009593 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009594 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9595 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009596 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009597 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009598
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009599 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009600
Chris Lattnerecd79c62009-06-14 00:45:47 +00009601 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009602 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009603 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009604 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009605
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009606 // If this argument is required to be an IntegerConstantExpression and the
9607 // caller cares, fill in the bitmask we return.
9608 if (RequiresICE && IntegerConstantArgs)
9609 *IntegerConstantArgs |= 1 << ArgTypes.size();
Fangrui Song6907ce22018-07-30 19:24:48 +00009610
Chris Lattnerecd79c62009-06-14 00:45:47 +00009611 // Do array -> pointer decay. The builtin should use the decayed type.
9612 if (Ty->isArrayType())
9613 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009614
Chris Lattnerecd79c62009-06-14 00:45:47 +00009615 ArgTypes.push_back(Ty);
9616 }
9617
David Majnemerba3e5ec2015-03-13 18:26:17 +00009618 if (Id == Builtin::BI__GetExceptionInfo)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009619 return {};
David Majnemerba3e5ec2015-03-13 18:26:17 +00009620
Chris Lattnerecd79c62009-06-14 00:45:47 +00009621 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9622 "'.' should only occur at end of builtin type list!");
9623
Erich Keane881e83d2019-03-04 14:54:52 +00009624 bool Variadic = (TypeStr[0] == '.');
9625
Erich Keane00022812019-05-23 16:05:21 +00009626 FunctionType::ExtInfo EI(getDefaultCallingConvention(
9627 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
John McCall991eb4b2010-12-21 00:44:39 +00009628 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9629
John McCall991eb4b2010-12-21 00:44:39 +00009630
Richard Smith836de6b2016-12-19 23:59:34 +00009631 // We really shouldn't be making a no-proto type here.
9632 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00009633 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00009634
John McCalldb40c7f2010-12-14 08:05:40 +00009635 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00009636 EPI.ExtInfo = EI;
9637 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00009638 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9639 EPI.ExceptionSpec.Type =
9640 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00009641
Jordan Rose5c382722013-03-08 21:51:21 +00009642 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009643}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00009644
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009645static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9646 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009647 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009648 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009649
Richard Smithe2467b72017-11-16 23:54:56 +00009650 // Non-user-provided functions get emitted as weak definitions with every
9651 // use, no matter whether they've been explicitly instantiated etc.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009652 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
Richard Smithe2467b72017-11-16 23:54:56 +00009653 if (!MD->isUserProvided())
9654 return GVA_DiscardableODR;
9655
Yaron Keren4cd211b2017-02-22 14:32:39 +00009656 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009657 switch (FD->getTemplateSpecializationKind()) {
9658 case TSK_Undeclared:
9659 case TSK_ExplicitSpecialization:
9660 External = GVA_StrongExternal;
9661 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009662
Rafael Espindola3ae00052013-05-13 00:12:11 +00009663 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009664 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009665
David Majnemerc3d07332014-05-15 06:25:57 +00009666 // C++11 [temp.explicit]p10:
9667 // [ Note: The intent is that an inline function that is the subject of
9668 // an explicit instantiation declaration will still be implicitly
9669 // instantiated when used so that the body can be considered for
9670 // inlining, but that no out-of-line copy of the inline function would be
9671 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00009672 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00009673 return GVA_AvailableExternally;
9674
Rafael Espindola3ae00052013-05-13 00:12:11 +00009675 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009676 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009677 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009678 }
9679
9680 if (!FD->isInlined())
9681 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00009682
David Majnemer3f021502015-10-08 04:53:31 +00009683 if ((!Context.getLangOpts().CPlusPlus &&
9684 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009685 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00009686 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009687 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9688
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009689 // GNU or C99 inline semantics. Determine whether this symbol should be
9690 // externally visible.
9691 if (FD->isInlineDefinitionExternallyVisible())
9692 return External;
9693
9694 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00009695 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009696 }
9697
David Majnemer54e3ba52014-04-02 23:17:29 +00009698 // Functions specified with extern and inline in -fms-compatibility mode
9699 // forcibly get emitted. While the body of the function cannot be later
9700 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00009701 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00009702 return GVA_StrongODR;
9703
David Majnemer27d69db2014-04-28 22:17:59 +00009704 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009705}
9706
Artem Belevichca2b9512016-05-02 20:30:03 +00009707static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00009708 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009709 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9710 // dllexport/dllimport on inline functions.
9711 if (D->hasAttr<DLLImportAttr>()) {
9712 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9713 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00009714 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009715 if (L == GVA_DiscardableODR)
9716 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00009717 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9718 D->hasAttr<CUDAGlobalAttr>()) {
9719 // Device-side functions with __global__ attribute must always be
9720 // visible externally so they can be launched from host.
9721 if (L == GVA_DiscardableODR || L == GVA_Internal)
9722 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009723 }
9724 return L;
9725}
9726
Richard Smitha4653622017-09-06 20:01:14 +00009727/// Adjust the GVALinkage for a declaration based on what an external AST source
9728/// knows about whether there can be other definitions of this declaration.
9729static GVALinkage
9730adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9731 GVALinkage L) {
9732 ExternalASTSource *Source = Ctx.getExternalSource();
9733 if (!Source)
9734 return L;
9735
9736 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00009737 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00009738 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009739 if (L == GVA_DiscardableODR)
9740 return GVA_StrongODR;
9741 break;
Richard Smitha4653622017-09-06 20:01:14 +00009742
David Blaikie9ffe5a32017-01-30 05:00:26 +00009743 case ExternalASTSource::EK_Always:
9744 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00009745
David Blaikie9ffe5a32017-01-30 05:00:26 +00009746 case ExternalASTSource::EK_ReplyHazy:
9747 break;
9748 }
9749 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009750}
9751
Richard Smitha4653622017-09-06 20:01:14 +00009752GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9753 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9754 adjustGVALinkageForAttributes(*this, FD,
9755 basicGVALinkageForFunction(*this, FD)));
9756}
9757
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009758static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9759 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009760 if (!VD->isExternallyVisible())
9761 return GVA_Internal;
9762
David Majnemer27d69db2014-04-28 22:17:59 +00009763 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00009764 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9765 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9766 LexicalContext = LexicalContext->getLexicalParent();
9767
David Blaikieeb210012017-01-27 23:11:10 +00009768 // ObjC Blocks can create local variables that don't have a FunctionDecl
9769 // LexicalContext.
9770 if (!LexicalContext)
9771 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00009772
David Blaikieeb210012017-01-27 23:11:10 +00009773 // Otherwise, let the static local variable inherit its linkage from the
9774 // nearest enclosing function.
9775 auto StaticLocalLinkage =
9776 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9777
9778 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9779 // be emitted in any object with references to the symbol for the object it
9780 // contains, whether inline or out-of-line."
9781 // Similar behavior is observed with MSVC. An alternative ABI could use
9782 // StrongODR/AvailableExternally to match the function, but none are
9783 // known/supported currently.
9784 if (StaticLocalLinkage == GVA_StrongODR ||
9785 StaticLocalLinkage == GVA_AvailableExternally)
9786 return GVA_DiscardableODR;
9787 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009788 }
9789
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009790 // MSVC treats in-class initialized static data members as definitions.
9791 // By giving them non-strong linkage, out-of-line definitions won't
9792 // cause link errors.
9793 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9794 return GVA_DiscardableODR;
9795
Richard Smithd9b90092016-07-02 01:32:16 +00009796 // Most non-template variables have strong linkage; inline variables are
9797 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9798 GVALinkage StrongLinkage;
9799 switch (Context.getInlineVariableDefinitionKind(VD)) {
9800 case ASTContext::InlineVariableDefinitionKind::None:
9801 StrongLinkage = GVA_StrongExternal;
9802 break;
9803 case ASTContext::InlineVariableDefinitionKind::Weak:
9804 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009805 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009806 break;
9807 case ASTContext::InlineVariableDefinitionKind::Strong:
9808 StrongLinkage = GVA_StrongODR;
9809 break;
9810 }
Richard Smith62f19e72016-06-25 00:15:56 +00009811
Richard Smith8809a0c2013-09-27 20:14:12 +00009812 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009813 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009814 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009815
David Majnemer6d1780c2015-07-17 23:36:49 +00009816 case TSK_ExplicitSpecialization:
Reid Klecknere6f2ff22019-06-26 21:16:51 +00009817 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9818 VD->isStaticDataMember()
9819 ? GVA_StrongODR
9820 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009821
Rafael Espindola3ae00052013-05-13 00:12:11 +00009822 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009823 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009824
David Majnemer27d69db2014-04-28 22:17:59 +00009825 case TSK_ExplicitInstantiationDeclaration:
9826 return GVA_AvailableExternally;
9827
Rafael Espindola3ae00052013-05-13 00:12:11 +00009828 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009829 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009830 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009831
9832 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009833}
9834
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009835GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009836 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9837 adjustGVALinkageForAttributes(*this, VD,
9838 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009839}
9840
David Blaikiee6b7c282017-04-11 20:46:34 +00009841bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009842 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009843 if (!VD->isFileVarDecl())
9844 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009845 // Global named register variables (GNU extension) are never emitted.
9846 if (VD->getStorageClass() == SC_Register)
9847 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009848 if (VD->getDescribedVarTemplate() ||
9849 isa<VarTemplatePartialSpecializationDecl>(VD))
9850 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009851 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Smith5205a8c2013-04-01 20:22:16 +00009852 // We never need to emit an uninstantiated function template.
9853 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9854 return false;
Nico Weber66220292016-03-02 17:28:48 +00009855 } else if (isa<PragmaCommentDecl>(D))
9856 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009857 else if (isa<PragmaDetectMismatchDecl>(D))
9858 return true;
Nico Weber66220292016-03-02 17:28:48 +00009859 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009860 return !D->getDeclContext()->isDependentContext();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009861 else if (isa<OMPAllocateDecl>(D))
9862 return !D->getDeclContext()->isDependentContext();
Michael Krused47b9432019-08-05 18:43:21 +00009863 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009864 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009865 else if (isa<ImportDecl>(D))
9866 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009867 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009868 return false;
9869
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009870 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
9871 assert(getExternalSource() && "It's from an AST file; must have a source.");
9872 // On Windows, PCH files are built together with an object file. If this
9873 // declaration comes from such a PCH and DeclMustBeEmitted would return
9874 // true, it would have returned true and the decl would have been emitted
9875 // into that object file, so it doesn't need to be emitted here.
9876 // Note that decls are still emitted if they're referenced, as usual;
9877 // DeclMustBeEmitted is used to decide whether a decl must be emitted even
9878 // if it's not referenced.
9879 //
9880 // Explicit template instantiation definitions are tricky. If there was an
9881 // explicit template instantiation decl in the PCH before, it will look like
9882 // the definition comes from there, even if that was just the declaration.
9883 // (Explicit instantiation defs of variable templates always get emitted.)
9884 bool IsExpInstDef =
9885 isa<FunctionDecl>(D) &&
9886 cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
9887 TSK_ExplicitInstantiationDefinition;
9888
Hans Wennborgb51a7032018-09-14 15:18:30 +00009889 // Implicit member function definitions, such as operator= might not be
9890 // marked as template specializations, since they're not coming from a
9891 // template but synthesized directly on the class.
9892 IsExpInstDef |=
9893 isa<CXXMethodDecl>(D) &&
9894 cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
9895 TSK_ExplicitInstantiationDefinition;
9896
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009897 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
9898 return false;
9899 }
9900
Richard Smith5205a8c2013-04-01 20:22:16 +00009901 // If this is a member of a class template, we do not need to emit it.
9902 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009903 return false;
9904
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009905 // Weak references don't produce any output by themselves.
9906 if (D->hasAttr<WeakRefAttr>())
9907 return false;
9908
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009909 // Aliases and used decls are required.
9910 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9911 return true;
9912
Eugene Zelenko7855e772018-04-03 00:11:50 +00009913 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009914 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009915 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009916 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009917
9918 // Constructors and destructors are required.
9919 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9920 return true;
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009921
John McCall6bd2a892013-01-25 22:31:03 +00009922 // The key function for a class is required. This rule only comes
9923 // into play when inline functions can be key functions, though.
9924 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009925 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
John McCall6bd2a892013-01-25 22:31:03 +00009926 const CXXRecordDecl *RD = MD->getParent();
9927 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9928 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9929 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9930 return true;
9931 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009932 }
9933 }
9934
David Blaikie9ffe5a32017-01-30 05:00:26 +00009935 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9936
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009937 // static, static inline, always_inline, and extern inline functions can
9938 // always be deferred. Normal inline functions can be deferred in C99/C++.
9939 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009940 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009941 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009942
Eugene Zelenko7855e772018-04-03 00:11:50 +00009943 const auto *VD = cast<VarDecl>(D);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009944 assert(VD->isFileVarDecl() && "Expected file scoped var");
9945
Alexey Bataevd01b7492018-08-15 19:45:12 +00009946 // If the decl is marked as `declare target to`, it should be emitted for the
9947 // host and for the device.
9948 if (LangOpts.OpenMP &&
9949 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
9950 return true;
9951
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009952 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9953 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009954 return false;
9955
Richard Smitha0e5e542012-11-12 21:38:00 +00009956 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +00009957 auto Linkage = GetGVALinkageForVariable(VD);
9958 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +00009959 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009960
Richard Smitha4653622017-09-06 20:01:14 +00009961 // We never need to emit a variable that is available in another TU.
9962 if (Linkage == GVA_AvailableExternally)
9963 return false;
9964
Richard Smitha0e5e542012-11-12 21:38:00 +00009965 // Variables that have destruction with side-effects are required.
9966 if (VD->getType().isDestructedType())
9967 return true;
9968
9969 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009970 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009971 // We can get a value-dependent initializer during error recovery.
9972 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009973 return true;
9974
Richard Smithda383632016-08-15 01:33:41 +00009975 // Likewise, variables with tuple-like bindings are required if their
9976 // bindings have side-effects.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009977 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
9978 for (const auto *BD : DD->bindings())
9979 if (const auto *BindingVD = BD->getHoldingVar())
Richard Smithda383632016-08-15 01:33:41 +00009980 if (DeclMustBeEmitted(BindingVD))
9981 return true;
9982
Richard Smitha0e5e542012-11-12 21:38:00 +00009983 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009984}
Charles Davis53c59df2010-08-16 03:33:14 +00009985
Erich Keane281d20b2018-01-08 21:34:17 +00009986void ASTContext::forEachMultiversionedFunctionVersion(
9987 const FunctionDecl *FD,
Erich Keane0fb16482018-08-13 18:33:20 +00009988 llvm::function_ref<void(FunctionDecl *)> Pred) const {
Erich Keane281d20b2018-01-08 21:34:17 +00009989 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
9990 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
Erich Keane7304f0a2018-11-28 20:58:43 +00009991 FD = FD->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +00009992 for (auto *CurDecl :
9993 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
Erich Keane7304f0a2018-11-28 20:58:43 +00009994 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +00009995 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
9996 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
9997 SeenDecls.insert(CurFD);
9998 Pred(CurFD);
9999 }
10000 }
10001}
10002
Reid Kleckner78af0702013-08-27 23:08:25 +000010003CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
Erich Keane00022812019-05-23 16:05:21 +000010004 bool IsCXXMethod,
10005 bool IsBuiltin) const {
Charles Davis99202b32010-11-09 18:04:24 +000010006 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +000010007 if (IsCXXMethod)
10008 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +000010009
Erich Keane00022812019-05-23 16:05:21 +000010010 // Builtins ignore user-specified default calling convention and remain the
10011 // Target's default calling convention.
10012 if (!IsBuiltin) {
10013 switch (LangOpts.getDefaultCallingConv()) {
10014 case LangOptions::DCC_None:
10015 break;
10016 case LangOptions::DCC_CDecl:
10017 return CC_C;
10018 case LangOptions::DCC_FastCall:
10019 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
10020 return CC_X86FastCall;
10021 break;
10022 case LangOptions::DCC_StdCall:
10023 if (!IsVariadic)
10024 return CC_X86StdCall;
10025 break;
10026 case LangOptions::DCC_VectorCall:
10027 // __vectorcall cannot be applied to variadic functions.
10028 if (!IsVariadic)
10029 return CC_X86VectorCall;
10030 break;
10031 case LangOptions::DCC_RegCall:
10032 // __regcall cannot be applied to variadic functions.
10033 if (!IsVariadic)
10034 return CC_X86RegCall;
10035 break;
10036 }
Alexey Bataeva7547182016-05-18 09:06:38 +000010037 }
Erich Keane39309482019-07-25 17:14:45 +000010038 return Target->getDefaultCallingConv();
Charles Davis99202b32010-11-09 18:04:24 +000010039}
10040
Jay Foad39c79802011-01-12 09:06:06 +000010041bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +000010042 // Pass through to the C++ ABI object
10043 return ABI->isNearlyEmpty(RD);
10044}
10045
Reid Kleckner96f8f932014-02-05 17:27:08 +000010046VTableContextBase *ASTContext::getVTableContext() {
10047 if (!VTContext.get()) {
10048 if (Target->getCXXABI().isMicrosoft())
10049 VTContext.reset(new MicrosoftVTableContext(*this));
10050 else
10051 VTContext.reset(new ItaniumVTableContext(*this));
10052 }
10053 return VTContext.get();
10054}
10055
Yaxun Liuc18e9ec2019-02-14 02:00:09 +000010056MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
10057 if (!T)
10058 T = Target;
10059 switch (T->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000010060 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +000010061 case TargetCXXABI::GenericItanium:
10062 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +000010063 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +000010064 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000010065 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +000010066 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +000010067 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010068 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +000010069 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010070 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010071 }
David Blaikie83d382b2011-09-23 05:06:16 +000010072 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010073}
10074
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010075CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010076
10077size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +000010078 return ASTRecordLayouts.getMemorySize() +
10079 llvm::capacity_in_bytes(ObjCLayouts) +
10080 llvm::capacity_in_bytes(KeyFunctions) +
10081 llvm::capacity_in_bytes(ObjCImpls) +
10082 llvm::capacity_in_bytes(BlockVarCopyInits) +
10083 llvm::capacity_in_bytes(DeclAttrs) +
10084 llvm::capacity_in_bytes(TemplateOrInstantiation) +
10085 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10086 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10087 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10088 llvm::capacity_in_bytes(OverriddenMethods) +
10089 llvm::capacity_in_bytes(Types) +
Richard Smithf19a8b02019-05-02 00:49:14 +000010090 llvm::capacity_in_bytes(VariableArrayTypes);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010091}
Ted Kremenek540017e2011-10-06 05:00:56 +000010092
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010093/// getIntTypeForBitwidth -
10094/// sets integer QualTy according to specified details:
10095/// bitwidth, signed/unsigned.
10096/// Returns empty type if there is no appropriate target types.
10097QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
10098 unsigned Signed) const {
10099 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10100 CanQualType QualTy = getFromTargetType(Ty);
10101 if (!QualTy && DestWidth == 128)
10102 return Signed ? Int128Ty : UnsignedInt128Ty;
10103 return QualTy;
10104}
10105
10106/// getRealTypeForBitwidth -
10107/// sets floating point QualTy according to specified bitwidth.
10108/// Returns empty type if there is no appropriate target types.
10109QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
10110 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
10111 switch (Ty) {
10112 case TargetInfo::Float:
10113 return FloatTy;
10114 case TargetInfo::Double:
10115 return DoubleTy;
10116 case TargetInfo::LongDouble:
10117 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000010118 case TargetInfo::Float128:
10119 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010120 case TargetInfo::NoFloat:
Eugene Zelenko7855e772018-04-03 00:11:50 +000010121 return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010122 }
10123
10124 llvm_unreachable("Unhandled TargetInfo::RealType value");
10125}
10126
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010127void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10128 if (Number > 1)
10129 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +000010130}
10131
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010132unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010133 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010134 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +000010135}
10136
David Majnemer2206bf52014-03-05 08:57:59 +000010137void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10138 if (Number > 1)
10139 StaticLocalNumbers[VD] = Number;
10140}
10141
10142unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010143 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +000010144 return I != StaticLocalNumbers.end() ? I->second : 1;
10145}
10146
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010147MangleNumberingContext &
10148ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010149 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +000010150 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +000010151 if (!MCtx)
10152 MCtx = createMangleNumberingContext();
10153 return *MCtx;
10154}
10155
Justin Lebar20ebffc2016-10-10 16:26:19 +000010156std::unique_ptr<MangleNumberingContext>
10157ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010158 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +000010159}
10160
David Majnemere7a818f2015-03-06 18:53:55 +000010161const CXXConstructorDecl *
10162ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
10163 return ABI->getCopyConstructorForExceptionObject(
10164 cast<CXXRecordDecl>(RD->getFirstDecl()));
10165}
10166
10167void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
10168 CXXConstructorDecl *CD) {
10169 return ABI->addCopyConstructorForExceptionObject(
10170 cast<CXXRecordDecl>(RD->getFirstDecl()),
10171 cast<CXXConstructorDecl>(CD->getFirstDecl()));
10172}
10173
David Majnemer00350522015-08-31 18:48:39 +000010174void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10175 TypedefNameDecl *DD) {
10176 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10177}
10178
10179TypedefNameDecl *
10180ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10181 return ABI->getTypedefNameForUnnamedTagDecl(TD);
10182}
10183
10184void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10185 DeclaratorDecl *DD) {
10186 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10187}
10188
10189DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10190 return ABI->getDeclaratorForUnnamedTagDecl(TD);
10191}
10192
Ted Kremenek540017e2011-10-06 05:00:56 +000010193void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10194 ParamIndices[D] = index;
10195}
10196
10197unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10198 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
Fangrui Song6907ce22018-07-30 19:24:48 +000010199 assert(I != ParamIndices.end() &&
Ted Kremenek540017e2011-10-06 05:00:56 +000010200 "ParmIndices lacks entry set by ParmVarDecl");
10201 return I->second;
10202}
Fariborz Jahanian615de762013-05-28 17:37:39 +000010203
Richard Smithe6c01442013-06-05 00:46:14 +000010204APValue *
10205ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
10206 bool MayCreate) {
10207 assert(E && E->getStorageDuration() == SD_Static &&
10208 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +000010209 if (MayCreate) {
10210 APValue *&MTVI = MaterializedTemporaryValues[E];
10211 if (!MTVI)
10212 MTVI = new (*this) APValue;
10213 return MTVI;
10214 }
Richard Smithe6c01442013-06-05 00:46:14 +000010215
David Majnemer2dcef9e2015-08-13 23:50:15 +000010216 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +000010217}
10218
Eric Fiselier708afb52019-05-16 21:04:15 +000010219QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
10220 unsigned Length) const {
10221 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
10222 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
10223 EltTy = EltTy.withConst();
10224
10225 EltTy = adjustStringLiteralBaseType(EltTy);
10226
10227 // Get an array type for the string, according to C99 6.4.5. This includes
10228 // the null terminator character.
10229 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1),
10230 ArrayType::Normal, /*IndexTypeQuals*/ 0);
10231}
10232
10233StringLiteral *
10234ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
10235 StringLiteral *&Result = StringLiteralCache[Key];
10236 if (!Result)
10237 Result = StringLiteral::Create(
10238 *this, Key, StringLiteral::Ascii,
10239 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
10240 SourceLocation());
10241 return Result;
10242}
10243
Fariborz Jahanian615de762013-05-28 17:37:39 +000010244bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10245 const llvm::Triple &T = getTargetInfo().getTriple();
10246 if (!T.isOSDarwin())
10247 return false;
10248
Bob Wilson2c82c3d2013-11-02 23:27:49 +000010249 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10250 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10251 return false;
10252
Fariborz Jahanian615de762013-05-28 17:37:39 +000010253 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10254 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10255 uint64_t Size = sizeChars.getQuantity();
10256 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10257 unsigned Align = alignChars.getQuantity();
10258 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10259 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10260}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010261
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010262/// Template specializations to abstract away from pointers and TypeLocs.
10263/// @{
10264template <typename T>
Sam McCall814e7972018-11-14 10:33:30 +000010265static ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010266 return ast_type_traits::DynTypedNode::create(*Node);
10267}
10268template <>
10269ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
10270 return ast_type_traits::DynTypedNode::create(Node);
10271}
10272template <>
10273ast_type_traits::DynTypedNode
10274createDynTypedNode(const NestedNameSpecifierLoc &Node) {
10275 return ast_type_traits::DynTypedNode::create(Node);
10276}
10277/// @}
10278
Sam McCall814e7972018-11-14 10:33:30 +000010279/// A \c RecursiveASTVisitor that builds a map from nodes to their
10280/// parents as defined by the \c RecursiveASTVisitor.
10281///
10282/// Note that the relationship described here is purely in terms of AST
10283/// traversal - there are other relationships (for example declaration context)
10284/// in the AST that are better modeled by special matchers.
10285///
10286/// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
10287class ASTContext::ParentMap::ASTVisitor
10288 : public RecursiveASTVisitor<ASTVisitor> {
10289public:
10290 ASTVisitor(ParentMap &Map) : Map(Map) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010291
Sam McCall814e7972018-11-14 10:33:30 +000010292private:
10293 friend class RecursiveASTVisitor<ASTVisitor>;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010294
Sam McCall814e7972018-11-14 10:33:30 +000010295 using VisitorBase = RecursiveASTVisitor<ASTVisitor>;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010296
Sam McCall814e7972018-11-14 10:33:30 +000010297 bool shouldVisitTemplateInstantiations() const { return true; }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010298
Sam McCall814e7972018-11-14 10:33:30 +000010299 bool shouldVisitImplicitCode() const { return true; }
10300
10301 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
10302 typename MapTy>
10303 bool TraverseNode(T Node, MapNodeTy MapNode, BaseTraverseFn BaseTraverse,
10304 MapTy *Parents) {
10305 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010306 return true;
Sam McCall814e7972018-11-14 10:33:30 +000010307 if (ParentStack.size() > 0) {
10308 // FIXME: Currently we add the same parent multiple times, but only
10309 // when no memoization data is available for the type.
10310 // For example when we visit all subexpressions of template
10311 // instantiations; this is suboptimal, but benign: the only way to
10312 // visit those is with hasAncestor / hasParent, and those do not create
10313 // new matches.
10314 // The plan is to enable DynTypedNode to be storable in a map or hash
10315 // map. The main problem there is to implement hash functions /
10316 // comparison operators for all types that DynTypedNode supports that
10317 // do not have pointer identity.
10318 auto &NodeOrVector = (*Parents)[MapNode];
10319 if (NodeOrVector.isNull()) {
10320 if (const auto *D = ParentStack.back().get<Decl>())
10321 NodeOrVector = D;
10322 else if (const auto *S = ParentStack.back().get<Stmt>())
10323 NodeOrVector = S;
10324 else
10325 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
10326 } else {
10327 if (!NodeOrVector.template is<ParentVector *>()) {
10328 auto *Vector = new ParentVector(
10329 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
10330 delete NodeOrVector
10331 .template dyn_cast<ast_type_traits::DynTypedNode *>();
10332 NodeOrVector = Vector;
Manuel Klimek95403e62014-05-21 13:28:59 +000010333 }
Sam McCall814e7972018-11-14 10:33:30 +000010334
10335 auto *Vector = NodeOrVector.template get<ParentVector *>();
10336 // Skip duplicates for types that have memoization data.
10337 // We must check that the type has memoization data before calling
10338 // std::find() because DynTypedNode::operator== can't compare all
10339 // types.
10340 bool Found = ParentStack.back().getMemoizationData() &&
10341 std::find(Vector->begin(), Vector->end(),
10342 ParentStack.back()) != Vector->end();
10343 if (!Found)
10344 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +000010345 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010346 }
Sam McCall814e7972018-11-14 10:33:30 +000010347 ParentStack.push_back(createDynTypedNode(Node));
10348 bool Result = BaseTraverse();
10349 ParentStack.pop_back();
10350 return Result;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010351 }
Sam McCall814e7972018-11-14 10:33:30 +000010352
10353 bool TraverseDecl(Decl *DeclNode) {
10354 return TraverseNode(
10355 DeclNode, DeclNode, [&] { return VisitorBase::TraverseDecl(DeclNode); },
10356 &Map.PointerParents);
Manuel Klimek95403e62014-05-21 13:28:59 +000010357 }
Sam McCall814e7972018-11-14 10:33:30 +000010358
10359 bool TraverseStmt(Stmt *StmtNode) {
10360 return TraverseNode(
10361 StmtNode, StmtNode, [&] { return VisitorBase::TraverseStmt(StmtNode); },
10362 &Map.PointerParents);
10363 }
10364
10365 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
10366 return TraverseNode(
10367 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
10368 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
10369 &Map.OtherParents);
10370 }
10371
10372 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
10373 return TraverseNode(
10374 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
10375 [&] { return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); },
10376 &Map.OtherParents);
10377 }
10378
10379 ParentMap &Map;
10380 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
10381};
10382
10383ASTContext::ParentMap::ParentMap(ASTContext &Ctx) {
10384 ASTVisitor(*this).TraverseAST(Ctx);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010385}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010386
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010387ASTContext::DynTypedNodeList
10388ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
Sam McCall814e7972018-11-14 10:33:30 +000010389 if (!Parents)
10390 // We build the parent map for the traversal scope (usually whole TU), as
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010391 // hasAncestor can escape any subtree.
Sam McCall814e7972018-11-14 10:33:30 +000010392 Parents = llvm::make_unique<ParentMap>(*this);
10393 return Parents->getParents(Node);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010394}
10395
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010396bool
10397ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10398 const ObjCMethodDecl *MethodImpl) {
10399 // No point trying to match an unavailable/deprecated mothod.
10400 if (MethodDecl->hasAttr<UnavailableAttr>()
10401 || MethodDecl->hasAttr<DeprecatedAttr>())
10402 return false;
10403 if (MethodDecl->getObjCDeclQualifier() !=
10404 MethodImpl->getObjCDeclQualifier())
10405 return false;
Alp Toker314cc812014-01-25 16:55:45 +000010406 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010407 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010408
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010409 if (MethodDecl->param_size() != MethodImpl->param_size())
10410 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010411
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010412 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10413 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10414 EF = MethodDecl->param_end();
10415 IM != EM && IF != EF; ++IM, ++IF) {
10416 const ParmVarDecl *DeclVar = (*IF);
10417 const ParmVarDecl *ImplVar = (*IM);
10418 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10419 return false;
10420 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10421 return false;
10422 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010423
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010424 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010425}
Richard Smith053f6c62014-05-16 23:01:30 +000010426
Yaxun Liu402804b2016-12-15 08:09:08 +000010427uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +000010428 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +000010429 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +000010430 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +000010431 else
10432 AS = QT->getPointeeType().getAddressSpace();
10433
10434 return getTargetInfo().getNullPointerValue(AS);
10435}
10436
Alexander Richardson6d989432017-10-15 18:48:14 +000010437unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10438 if (isTargetAddressSpace(AS))
10439 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +000010440 else
Alexander Richardson6d989432017-10-15 18:48:14 +000010441 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +000010442}
10443
Leonard Chanab80f3c2018-06-14 14:53:51 +000010444QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
10445 assert(Ty->isFixedPointType());
10446
10447 if (Ty->isSaturatedFixedPointType()) return Ty;
10448
10449 const auto &BT = Ty->getAs<BuiltinType>();
10450 switch (BT->getKind()) {
10451 default:
10452 llvm_unreachable("Not a fixed point type!");
10453 case BuiltinType::ShortAccum:
10454 return SatShortAccumTy;
10455 case BuiltinType::Accum:
10456 return SatAccumTy;
10457 case BuiltinType::LongAccum:
10458 return SatLongAccumTy;
10459 case BuiltinType::UShortAccum:
10460 return SatUnsignedShortAccumTy;
10461 case BuiltinType::UAccum:
10462 return SatUnsignedAccumTy;
10463 case BuiltinType::ULongAccum:
10464 return SatUnsignedLongAccumTy;
10465 case BuiltinType::ShortFract:
10466 return SatShortFractTy;
10467 case BuiltinType::Fract:
10468 return SatFractTy;
10469 case BuiltinType::LongFract:
10470 return SatLongFractTy;
10471 case BuiltinType::UShortFract:
10472 return SatUnsignedShortFractTy;
10473 case BuiltinType::UFract:
10474 return SatUnsignedFractTy;
10475 case BuiltinType::ULongFract:
10476 return SatUnsignedLongFractTy;
10477 }
10478}
10479
Matt Arsenaultc65f9662018-08-02 12:14:28 +000010480LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
10481 if (LangOpts.OpenCL)
10482 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
10483
10484 if (LangOpts.CUDA)
10485 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
10486
10487 return getLangASFromTargetAS(AS);
10488}
10489
Richard Smith053f6c62014-05-16 23:01:30 +000010490// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10491// doesn't include ASTContext.h
10492template
10493clang::LazyGenerationalUpdatePtr<
10494 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10495clang::LazyGenerationalUpdatePtr<
10496 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10497 const clang::ASTContext &Ctx, Decl *Value);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010498
10499unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10500 assert(Ty->isFixedPointType());
10501
10502 const auto *BT = Ty->getAs<BuiltinType>();
10503 const TargetInfo &Target = getTargetInfo();
10504 switch (BT->getKind()) {
10505 default:
10506 llvm_unreachable("Not a fixed point type!");
10507 case BuiltinType::ShortAccum:
10508 case BuiltinType::SatShortAccum:
10509 return Target.getShortAccumScale();
10510 case BuiltinType::Accum:
10511 case BuiltinType::SatAccum:
10512 return Target.getAccumScale();
10513 case BuiltinType::LongAccum:
10514 case BuiltinType::SatLongAccum:
10515 return Target.getLongAccumScale();
10516 case BuiltinType::UShortAccum:
10517 case BuiltinType::SatUShortAccum:
10518 return Target.getUnsignedShortAccumScale();
10519 case BuiltinType::UAccum:
10520 case BuiltinType::SatUAccum:
10521 return Target.getUnsignedAccumScale();
10522 case BuiltinType::ULongAccum:
10523 case BuiltinType::SatULongAccum:
10524 return Target.getUnsignedLongAccumScale();
10525 case BuiltinType::ShortFract:
10526 case BuiltinType::SatShortFract:
10527 return Target.getShortFractScale();
10528 case BuiltinType::Fract:
10529 case BuiltinType::SatFract:
10530 return Target.getFractScale();
10531 case BuiltinType::LongFract:
10532 case BuiltinType::SatLongFract:
10533 return Target.getLongFractScale();
10534 case BuiltinType::UShortFract:
10535 case BuiltinType::SatUShortFract:
10536 return Target.getUnsignedShortFractScale();
10537 case BuiltinType::UFract:
10538 case BuiltinType::SatUFract:
10539 return Target.getUnsignedFractScale();
10540 case BuiltinType::ULongFract:
10541 case BuiltinType::SatULongFract:
10542 return Target.getUnsignedLongFractScale();
10543 }
10544}
10545
10546unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10547 assert(Ty->isFixedPointType());
10548
10549 const auto *BT = Ty->getAs<BuiltinType>();
10550 const TargetInfo &Target = getTargetInfo();
10551 switch (BT->getKind()) {
10552 default:
10553 llvm_unreachable("Not a fixed point type!");
10554 case BuiltinType::ShortAccum:
10555 case BuiltinType::SatShortAccum:
10556 return Target.getShortAccumIBits();
10557 case BuiltinType::Accum:
10558 case BuiltinType::SatAccum:
10559 return Target.getAccumIBits();
10560 case BuiltinType::LongAccum:
10561 case BuiltinType::SatLongAccum:
10562 return Target.getLongAccumIBits();
10563 case BuiltinType::UShortAccum:
10564 case BuiltinType::SatUShortAccum:
10565 return Target.getUnsignedShortAccumIBits();
10566 case BuiltinType::UAccum:
10567 case BuiltinType::SatUAccum:
10568 return Target.getUnsignedAccumIBits();
10569 case BuiltinType::ULongAccum:
10570 case BuiltinType::SatULongAccum:
10571 return Target.getUnsignedLongAccumIBits();
10572 case BuiltinType::ShortFract:
10573 case BuiltinType::SatShortFract:
10574 case BuiltinType::Fract:
10575 case BuiltinType::SatFract:
10576 case BuiltinType::LongFract:
10577 case BuiltinType::SatLongFract:
10578 case BuiltinType::UShortFract:
10579 case BuiltinType::SatUShortFract:
10580 case BuiltinType::UFract:
10581 case BuiltinType::SatUFract:
10582 case BuiltinType::ULongFract:
10583 case BuiltinType::SatULongFract:
10584 return 0;
10585 }
10586}
Leonard Chana6779422018-08-06 16:42:37 +000010587
10588FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
Erich Keane8e772162019-01-18 19:31:54 +000010589 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
10590 "Can only get the fixed point semantics for a "
10591 "fixed point or integer type.");
Leonard Chan2044ac82019-01-16 18:13:59 +000010592 if (Ty->isIntegerType())
10593 return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty),
10594 Ty->isSignedIntegerType());
10595
Leonard Chana6779422018-08-06 16:42:37 +000010596 bool isSigned = Ty->isSignedFixedPointType();
10597 return FixedPointSemantics(
10598 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
10599 Ty->isSaturatedFixedPointType(),
10600 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
10601}
10602
10603APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
10604 assert(Ty->isFixedPointType());
10605 return APFixedPoint::getMax(getFixedPointSemantics(Ty));
10606}
10607
10608APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
10609 assert(Ty->isFixedPointType());
10610 return APFixedPoint::getMin(getFixedPointSemantics(Ty));
10611}
Leonard Chan2044ac82019-01-16 18:13:59 +000010612
10613QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
10614 assert(Ty->isUnsignedFixedPointType() &&
10615 "Expected unsigned fixed point type");
10616 const auto *BTy = Ty->getAs<BuiltinType>();
10617
10618 switch (BTy->getKind()) {
10619 case BuiltinType::UShortAccum:
10620 return ShortAccumTy;
10621 case BuiltinType::UAccum:
10622 return AccumTy;
10623 case BuiltinType::ULongAccum:
10624 return LongAccumTy;
10625 case BuiltinType::SatUShortAccum:
10626 return SatShortAccumTy;
10627 case BuiltinType::SatUAccum:
10628 return SatAccumTy;
10629 case BuiltinType::SatULongAccum:
10630 return SatLongAccumTy;
10631 case BuiltinType::UShortFract:
10632 return ShortFractTy;
10633 case BuiltinType::UFract:
10634 return FractTy;
10635 case BuiltinType::ULongFract:
10636 return LongFractTy;
10637 case BuiltinType::SatUShortFract:
10638 return SatShortFractTy;
10639 case BuiltinType::SatUFract:
10640 return SatFractTy;
10641 case BuiltinType::SatULongFract:
10642 return SatLongFractTy;
10643 default:
10644 llvm_unreachable("Unexpected unsigned fixed point type");
10645 }
10646}