blob: 4b095ce45ab4e42bbfa29bcb3e246822e61cb1e4 [file] [log] [blame]
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001//===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
Chris Lattnerddc135e2006-11-10 06:34:16 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000016#include "clang/AST/APValue.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/ASTMutationListener.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000018#include "clang/AST/ASTTypeTraits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Attr.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000020#include "clang/AST/AttrIterator.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000021#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000022#include "clang/AST/Comment.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000023#include "clang/AST/Decl.h"
24#include "clang/AST/DeclBase.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000025#include "clang/AST/DeclCXX.h"
Chandler Carruthaa36b892015-12-30 03:40:23 +000026#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000027#include "clang/AST/DeclObjC.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000028#include "clang/AST/DeclOpenMP.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000029#include "clang/AST/DeclTemplate.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000030#include "clang/AST/DeclarationName.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000031#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000032#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000033#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000034#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000035#include "clang/AST/MangleNumberingContext.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000036#include "clang/AST/NestedNameSpecifier.h"
37#include "clang/AST/RawCommentList.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000038#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000039#include "clang/AST/RecursiveASTVisitor.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000040#include "clang/AST/Stmt.h"
41#include "clang/AST/TemplateBase.h"
42#include "clang/AST/TemplateName.h"
43#include "clang/AST/Type.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000044#include "clang/AST/TypeLoc.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000045#include "clang/AST/UnresolvedSet.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000046#include "clang/AST/VTableBuilder.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000047#include "clang/Basic/AddressSpaces.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000048#include "clang/Basic/Builtins.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000049#include "clang/Basic/CommentOptions.h"
Eugene Zelenko7855e772018-04-03 00:11:50 +000050#include "clang/Basic/ExceptionSpecificationType.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
Douglas Gregor9672f922010-07-03 00:47:00 +000097unsigned ASTContext::NumImplicitDefaultConstructors;
98unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000099unsigned ASTContext::NumImplicitCopyConstructors;
100unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +0000101unsigned ASTContext::NumImplicitMoveConstructors;
102unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000103unsigned ASTContext::NumImplicitCopyAssignmentOperators;
104unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +0000105unsigned ASTContext::NumImplicitMoveAssignmentOperators;
106unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +0000107unsigned ASTContext::NumImplicitDestructors;
108unsigned ASTContext::NumImplicitDestructorsDeclared;
109
Steve Naroff0af91202007-04-27 21:51:21 +0000110enum FloatingRank {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +0000111 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +0000112};
113
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000114RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000115 if (!CommentsLoaded && ExternalSource) {
116 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +0000117
118#ifndef NDEBUG
119 ArrayRef<RawComment *> RawComments = Comments.getComments();
120 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
121 BeforeThanCompare<RawComment>(SourceMgr)));
122#endif
123
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000124 CommentsLoaded = true;
125 }
126
127 assert(D);
128
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000129 // User can not attach documentation to implicit declarations.
130 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +0000131 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000132
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000133 // User can not attach documentation to implicit instantiations.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000134 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000135 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000136 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000137 }
138
Eugene Zelenko7855e772018-04-03 00:11:50 +0000139 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000140 if (VD->isStaticDataMember() &&
141 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000142 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000143 }
144
Eugene Zelenko7855e772018-04-03 00:11:50 +0000145 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000146 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000147 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000148 }
149
Eugene Zelenko7855e772018-04-03 00:11:50 +0000150 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000151 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
152 if (TSK == TSK_ImplicitInstantiation ||
153 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000154 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000155 }
156
Eugene Zelenko7855e772018-04-03 00:11:50 +0000157 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000158 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000159 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000160 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000161 if (const auto *TD = dyn_cast<TagDecl>(D)) {
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000162 // When tag declaration (but not definition!) is part of the
163 // decl-specifier-seq of some other declaration, it doesn't get comment
164 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000165 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000166 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 // TODO: handle comments for function parameters properly.
168 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000169 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000170
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000171 // TODO: we could look up template parameter documentation in the template
172 // documentation.
173 if (isa<TemplateTypeParmDecl>(D) ||
174 isa<NonTypeTemplateParmDecl>(D) ||
175 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000176 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000177
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000178 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000179
180 // If there are no comments anywhere, we won't find anything.
181 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000182 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000183
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000184 // Find declaration location.
185 // For Objective-C declarations we generally don't expect to have multiple
186 // declarators, thus use declaration starting location as the "declaration
187 // location".
188 // For all other declarations multiple declarators are used quite frequently,
189 // so we use the location of the identifier as the "declaration location".
190 SourceLocation DeclLoc;
191 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000192 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000193 isa<RedeclarableTemplateDecl>(D) ||
194 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000195 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000196 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000197 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000198 if (DeclLoc.isMacroID()) {
199 if (isa<TypedefDecl>(D)) {
200 // If location of the typedef name is in a macro, it is because being
201 // declared via a macro. Try using declaration's starting location as
202 // the "declaration location".
203 DeclLoc = D->getLocStart();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000204 } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000205 // If location of the tag decl is inside a macro, but the spelling of
206 // the tag name comes from a macro argument, it looks like a special
207 // macro like NS_ENUM is being used to define the tag decl. In that
208 // case, adjust the source location to the expansion loc so that we can
209 // attach the comment to the tag decl.
210 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
211 TD->isCompleteDefinition())
212 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
213 }
214 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000215 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000216
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000217 // If the declaration doesn't map directly to a location in a file, we
218 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000219 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000220 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000221
222 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000223 ArrayRef<RawComment *>::iterator Comment;
224 {
225 // When searching for comments during parsing, the comment we are looking
226 // for is usually among the last two comments we parsed -- check them
227 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000228 RawComment CommentAtDeclLoc(
David L. Jones13d5a872018-03-02 00:07:45 +0000229 SourceMgr, SourceRange(DeclLoc), LangOpts.CommentOpts, false);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000230 BeforeThanCompare<RawComment> Compare(SourceMgr);
231 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
232 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
233 if (!Found && RawComments.size() >= 2) {
234 MaybeBeforeDecl--;
235 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
236 }
237
238 if (Found) {
239 Comment = MaybeBeforeDecl + 1;
240 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
241 &CommentAtDeclLoc, Compare));
242 } else {
243 // Slow path.
244 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
245 &CommentAtDeclLoc, Compare);
246 }
247 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000248
249 // Decompose the location for the declaration and find the beginning of the
250 // file buffer.
251 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
252
253 // First check whether we have a trailing comment.
254 if (Comment != RawComments.end() &&
David L. Jones13d5a872018-03-02 00:07:45 +0000255 ((*Comment)->isDocumentation() || LangOpts.CommentOpts.ParseAllComments)
256 && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000257 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000258 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000259 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000260 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000261 // Check that Doxygen trailing comment comes after the declaration, starts
262 // on the same line and in the same file as the declaration.
263 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
264 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
265 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
266 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000267 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000268 }
269 }
270
271 // The comment just after the declaration was not a trailing comment.
272 // Let's look at the previous comment.
273 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000274 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000275 --Comment;
276
277 // Check that we actually have a non-member Doxygen comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000278 if (!((*Comment)->isDocumentation() ||
279 LangOpts.CommentOpts.ParseAllComments) ||
280 (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000281 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000282
283 // Decompose the end of the comment.
284 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000285 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000286
287 // If the comment and the declaration aren't in the same file, then they
288 // aren't related.
289 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000290 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000291
292 // Get the corresponding buffer.
293 bool Invalid = false;
294 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
295 &Invalid).data();
296 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000297 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000298
299 // Extract text between the comment and declaration.
300 StringRef Text(Buffer + CommentEndDecomp.second,
301 DeclLocDecomp.second - CommentEndDecomp.second);
302
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000303 // There should be no other declarations or preprocessor directives between
304 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000305 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000306 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000307
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000308 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000309}
310
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000311/// If we have a 'templated' declaration for a template, adjust 'D' to
312/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000313/// If we have an implicit instantiation, adjust 'D' to refer to template.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000314static const Decl *adjustDeclToTemplate(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000315 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000316 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000317 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000318 return FTD;
319
320 // Nothing to do if function is not an implicit instantiation.
321 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
322 return D;
323
324 // Function is an implicit instantiation of a function template?
325 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
326 return FTD;
327
328 // Function is instantiated from a member definition of a class template?
329 if (const FunctionDecl *MemberDecl =
330 FD->getInstantiatedFromMemberFunction())
331 return MemberDecl;
332
333 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000334 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000335 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000336 // Static data member is instantiated from a member definition of a class
337 // template?
338 if (VD->isStaticDataMember())
339 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
340 return MemberDecl;
341
342 return D;
343 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000344 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000345 // Is this class declaration part of a class template?
346 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
347 return CTD;
348
349 // Class is an implicit instantiation of a class template or partial
350 // specialization?
Eugene Zelenko7855e772018-04-03 00:11:50 +0000351 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000352 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
353 return D;
354 llvm::PointerUnion<ClassTemplateDecl *,
355 ClassTemplatePartialSpecializationDecl *>
356 PU = CTSD->getSpecializedTemplateOrPartial();
357 return PU.is<ClassTemplateDecl*>() ?
358 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
359 static_cast<const Decl*>(
360 PU.get<ClassTemplatePartialSpecializationDecl *>());
361 }
362
363 // Class is instantiated from a member definition of a class template?
364 if (const MemberSpecializationInfo *Info =
365 CRD->getMemberSpecializationInfo())
366 return Info->getInstantiatedFrom();
367
368 return D;
369 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000370 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000371 // Enum is instantiated from a member definition of a class template?
372 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
373 return MemberDecl;
374
375 return D;
376 }
377 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000378 return D;
379}
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000380
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000381const RawComment *ASTContext::getRawCommentForAnyRedecl(
382 const Decl *D,
383 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000384 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000385
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000386 // Check whether we have cached a comment for this declaration already.
387 {
388 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
389 RedeclComments.find(D);
390 if (Pos != RedeclComments.end()) {
391 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000392 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
393 if (OriginalDecl)
394 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000395 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000396 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000397 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000398 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000399
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000400 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000401 const RawComment *RC = nullptr;
402 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000403 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000404 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000405 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000406 if (Pos != RedeclComments.end()) {
407 const RawCommentAndCacheFlags &Raw = Pos->second;
408 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
409 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000410 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000411 break;
412 }
413 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000414 RC = getRawCommentForDeclNoCache(I);
415 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000416 RawCommentAndCacheFlags Raw;
417 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000418 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
419 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000420 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000421 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000422 } else
423 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000424 Raw.setOriginalDecl(I);
425 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000426 if (RC)
427 break;
428 }
429 }
430
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000431 // If we found a comment, it should be a documentation comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000432 assert(!RC || RC->isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000433
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000434 if (OriginalDecl)
435 *OriginalDecl = OriginalDeclForRC;
436
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000437 // Update cache for every declaration in the redeclaration chain.
438 RawCommentAndCacheFlags Raw;
439 Raw.setRaw(RC);
440 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000441 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000442
Aaron Ballman86c93902014-03-06 23:45:36 +0000443 for (auto I : D->redecls()) {
444 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000445 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
446 R = Raw;
447 }
448
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000449 return RC;
450}
451
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000452static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
453 SmallVectorImpl<const NamedDecl *> &Redeclared) {
454 const DeclContext *DC = ObjCMethod->getDeclContext();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000455 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000456 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
457 if (!ID)
458 return;
459 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000460 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000461 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000462 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000463 ObjCMethod->isInstanceMethod()))
464 Redeclared.push_back(RedeclaredMethod);
465 }
466 }
467}
468
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000469comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
470 const Decl *D) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000471 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000472 ThisDeclInfo->CommentDecl = D;
473 ThisDeclInfo->IsFilled = false;
474 ThisDeclInfo->fill();
475 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000476 if (!ThisDeclInfo->TemplateParameters)
477 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000478 comments::FullComment *CFC =
479 new (*this) comments::FullComment(FC->getBlocks(),
480 ThisDeclInfo);
481 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000482}
483
Richard Smithb39b9d52013-05-21 05:24:00 +0000484comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
485 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000486 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000487}
488
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000489comments::FullComment *ASTContext::getCommentForDecl(
490 const Decl *D,
491 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000492 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000493 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000494 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000495
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000496 const Decl *Canonical = D->getCanonicalDecl();
497 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
498 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000499
500 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000501 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000502 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000503 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000504 return CFC;
505 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000506 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000507 }
508
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000509 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000510
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000511 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000512 if (!RC) {
513 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000514 SmallVector<const NamedDecl*, 8> Overridden;
Eugene Zelenko7855e772018-04-03 00:11:50 +0000515 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000516 if (OMD && OMD->isPropertyAccessor())
517 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
518 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
519 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000520 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000521 addRedeclaredMethods(OMD, Overridden);
522 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000523 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
524 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
525 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000526 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000527 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000528 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000529 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000530 QualType QT = TD->getUnderlyingType();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000531 if (const auto *TT = QT->getAs<TagType>())
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000532 if (const Decl *TD = TT->getDecl())
533 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000534 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000535 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000536 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000537 while (IC->getSuperClass()) {
538 IC = IC->getSuperClass();
539 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
540 return cloneFullComment(FC, D);
541 }
542 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000543 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000544 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
545 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
546 return cloneFullComment(FC, D);
547 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000548 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000549 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000550 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000551 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000552 for (const auto &I : RD->bases()) {
553 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000554 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000555 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000556 if (Ty.isNull())
557 continue;
558 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
559 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
560 continue;
561
562 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
563 return cloneFullComment(FC, D);
564 }
565 }
566 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000567 for (const auto &I : RD->vbases()) {
568 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000569 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000570 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000571 if (Ty.isNull())
572 continue;
573 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
574 if (!(VirtualBase= VirtualBase->getDefinition()))
575 continue;
576 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
577 return cloneFullComment(FC, D);
578 }
579 }
580 }
Craig Topper36250ad2014-05-12 05:36:57 +0000581 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000582 }
583
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000584 // If the RawComment was attached to other redeclaration of this Decl, we
585 // should parse the comment in context of that other Decl. This is important
586 // because comments can contain references to parameter names which can be
587 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000588 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000589 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000590
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000591 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000592 ParsedComments[Canonical] = FC;
593 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000594}
595
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000596void
597ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
598 TemplateTemplateParmDecl *Parm) {
599 ID.AddInteger(Parm->getDepth());
600 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000601 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000602
603 TemplateParameterList *Params = Parm->getTemplateParameters();
604 ID.AddInteger(Params->size());
605 for (TemplateParameterList::const_iterator P = Params->begin(),
606 PEnd = Params->end();
607 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000608 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000609 ID.AddInteger(0);
610 ID.AddBoolean(TTP->isParameterPack());
611 continue;
612 }
613
Eugene Zelenko7855e772018-04-03 00:11:50 +0000614 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000615 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000616 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000617 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000618 if (NTTP->isExpandedParameterPack()) {
619 ID.AddBoolean(true);
620 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000621 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
622 QualType T = NTTP->getExpansionType(I);
623 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
624 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000625 } else
626 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000627 continue;
628 }
629
Eugene Zelenko7855e772018-04-03 00:11:50 +0000630 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000631 ID.AddInteger(2);
632 Profile(ID, TTP);
633 }
634}
635
636TemplateTemplateParmDecl *
637ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000638 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000639 // Check if we already have a canonical template template parameter.
640 llvm::FoldingSetNodeID ID;
641 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000642 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000643 CanonicalTemplateTemplateParm *Canonical
644 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
645 if (Canonical)
646 return Canonical->getParam();
647
648 // Build a canonical template parameter list.
649 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000650 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000651 CanonParams.reserve(Params->size());
652 for (TemplateParameterList::const_iterator P = Params->begin(),
653 PEnd = Params->end();
654 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000655 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000656 CanonParams.push_back(
657 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000658 SourceLocation(),
659 SourceLocation(),
660 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000661 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000662 TTP->isParameterPack()));
Eugene Zelenko7855e772018-04-03 00:11:50 +0000663 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000664 QualType T = getCanonicalType(NTTP->getType());
665 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
666 NonTypeTemplateParmDecl *Param;
667 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000668 SmallVector<QualType, 2> ExpandedTypes;
669 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000670 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
671 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
672 ExpandedTInfos.push_back(
673 getTrivialTypeSourceInfo(ExpandedTypes.back()));
674 }
675
676 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000677 SourceLocation(),
678 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000679 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000680 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000681 T,
682 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000683 ExpandedTypes,
684 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000685 } else {
686 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000687 SourceLocation(),
688 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000689 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000690 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000691 T,
692 NTTP->isParameterPack(),
693 TInfo);
694 }
695 CanonParams.push_back(Param);
696
697 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000698 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
699 cast<TemplateTemplateParmDecl>(*P)));
700 }
701
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000702 assert(!TTP->getRequiresClause() &&
703 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000704 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000705
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000706 TemplateTemplateParmDecl *CanonTTP
707 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
708 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000709 TTP->getPosition(),
710 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000711 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000712 TemplateParameterList::Create(*this, SourceLocation(),
713 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000714 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000715 SourceLocation(),
716 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000717
718 // Get the new insert position for the node we care about.
719 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000720 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000721 (void)Canonical;
722
723 // Create the canonical template template parameter entry.
724 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
725 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
726 return CanonTTP;
727}
728
Charles Davis53c59df2010-08-16 03:33:14 +0000729CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000730 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000731
John McCall359b8852013-01-25 22:30:49 +0000732 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000733 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000734 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000735 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000736 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000737 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000738 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000739 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000740 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000741 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000742 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000743 return CreateMicrosoftCXXABI(*this);
744 }
David Blaikie8a40f702012-01-17 06:56:22 +0000745 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000746}
747
Alexander Richardson6d989432017-10-15 18:48:14 +0000748static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
749 const LangOptions &LOpts) {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000750 if (LOpts.FakeAddressSpaceMap) {
751 // The fake address space map must have a distinct entry for each
752 // language-specific address space.
753 static const unsigned FakeAddrSpaceMap[] = {
Yaxun Liub34ec822017-04-11 17:24:23 +0000754 0, // Default
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000755 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000756 3, // opencl_local
757 2, // opencl_constant
Yaxun Liub7318e02017-10-13 03:37:48 +0000758 0, // opencl_private
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000759 4, // opencl_generic
760 5, // cuda_device
761 6, // cuda_constant
762 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000763 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000764 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000765 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000766 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000767 }
768}
769
David Tweed31d09b02013-09-13 12:04:22 +0000770static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
771 const LangOptions &LangOpts) {
772 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000773 case LangOptions::ASMM_Target:
774 return TI.useAddressSpaceMapMangling();
775 case LangOptions::ASMM_On:
776 return true;
777 case LangOptions::ASMM_Off:
778 return false;
779 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000780 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000781}
782
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000783ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000784 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000785 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000786 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
787 DependentTemplateSpecializationTypes(this_()),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000788 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000789 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000790 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +0000791 LangOpts.XRayNeverInstrumentFiles,
792 LangOpts.XRayAttrListFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000793 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000794 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000795 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000796 TUDecl = TranslationUnitDecl::Create(*this);
797}
798
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000799ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000800 ReleaseParentMapEntries();
801
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000802 // Release the DenseMaps associated with DeclContext objects.
803 // FIXME: Is this the ideal solution?
804 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000805
Manuel Klimeka7328992013-06-03 13:51:33 +0000806 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000807 for (auto &Pair : Deallocations)
808 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000809
Ted Kremenek076baeb2010-06-08 23:00:58 +0000810 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000811 // because they can contain DenseMaps.
812 for (llvm::DenseMap<const ObjCContainerDecl*,
813 const ASTRecordLayout*>::iterator
814 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
815 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000816 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Douglas Gregor5b11d492010-07-25 17:53:33 +0000817 R->Destroy(*this);
818
Ted Kremenek076baeb2010-06-08 23:00:58 +0000819 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
820 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
821 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000822 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Ted Kremenek076baeb2010-06-08 23:00:58 +0000823 R->Destroy(*this);
824 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000825
826 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
827 AEnd = DeclAttrs.end();
828 A != AEnd; ++A)
829 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000830
David Majnemere694f3e2015-08-14 14:43:50 +0000831 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
832 MaterializedTemporaryValues)
833 MTVPair.second->~APValue();
834
Richard Smith423f46f2016-07-20 21:38:26 +0000835 for (const auto &Value : ModuleInitializers)
836 Value.second->~PerModuleInitializers();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000837}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000838
Manuel Klimek95403e62014-05-21 13:28:59 +0000839void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000840 if (!PointerParents) return;
841 for (const auto &Entry : *PointerParents) {
842 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
843 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
844 } else if (Entry.second.is<ParentVector *>()) {
845 delete Entry.second.get<ParentVector *>();
846 }
847 }
848 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000849 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
850 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000851 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000852 delete Entry.second.get<ParentVector *>();
853 }
854 }
855}
856
Douglas Gregor1a809332010-05-23 18:26:36 +0000857void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000858 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000859}
860
Mike Stump11289f42009-09-09 15:08:12 +0000861void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000862ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000863 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000864}
865
Chris Lattner4eb445d2007-01-26 01:27:23 +0000866void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000867 llvm::errs() << "\n*** AST Context Stats:\n";
868 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000869
Douglas Gregora30d0462009-05-26 14:40:08 +0000870 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000871#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000872#define ABSTRACT_TYPE(Name, Parent)
873#include "clang/AST/TypeNodes.def"
874 0 // Extra
875 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000876
Chris Lattner4eb445d2007-01-26 01:27:23 +0000877 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
878 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000879 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000880 }
881
Douglas Gregora30d0462009-05-26 14:40:08 +0000882 unsigned Idx = 0;
883 unsigned TotalBytes = 0;
884#define TYPE(Name, Parent) \
885 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000886 llvm::errs() << " " << counts[Idx] << " " << #Name \
887 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000888 TotalBytes += counts[Idx] * sizeof(Name##Type); \
889 ++Idx;
890#define ABSTRACT_TYPE(Name, Parent)
891#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000892
Chandler Carruth3c147a72011-07-04 05:32:14 +0000893 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
894
Douglas Gregor7454c562010-07-02 20:37:36 +0000895 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000896 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
897 << NumImplicitDefaultConstructors
898 << " implicit default constructors created\n";
899 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
900 << NumImplicitCopyConstructors
901 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000902 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000903 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
904 << NumImplicitMoveConstructors
905 << " implicit move constructors created\n";
906 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
907 << NumImplicitCopyAssignmentOperators
908 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000909 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000910 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
911 << NumImplicitMoveAssignmentOperators
912 << " implicit move assignment operators created\n";
913 llvm::errs() << NumImplicitDestructorsDeclared << "/"
914 << NumImplicitDestructors
915 << " implicit destructors created\n";
916
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000917 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000918 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000919 ExternalSource->PrintStats();
920 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000921
Douglas Gregor5b11d492010-07-25 17:53:33 +0000922 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000923}
924
Richard Smith42413142015-05-15 20:05:43 +0000925void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
926 bool NotifyListeners) {
927 if (NotifyListeners)
928 if (auto *Listener = getASTMutationListener())
929 Listener->RedefinedHiddenDefinition(ND, M);
930
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000931 if (getLangOpts().ModulesLocalVisibility)
932 MergedDefModules[ND].push_back(M);
933 else
Richard Smith90dc5252017-06-23 01:04:34 +0000934 ND->setVisibleDespiteOwningModule();
Richard Smith42413142015-05-15 20:05:43 +0000935}
936
937void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
938 auto It = MergedDefModules.find(ND);
939 if (It == MergedDefModules.end())
940 return;
941
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000942 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000943 llvm::DenseSet<Module*> Found;
944 for (Module *&M : Merged)
945 if (!Found.insert(M).second)
946 M = nullptr;
947 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
948}
949
Richard Smithdc1f0422016-07-20 19:10:16 +0000950void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
951 if (LazyInitializers.empty())
952 return;
953
954 auto *Source = Ctx.getExternalSource();
955 assert(Source && "lazy initializers but no external source");
956
957 auto LazyInits = std::move(LazyInitializers);
958 LazyInitializers.clear();
959
960 for (auto ID : LazyInits)
961 Initializers.push_back(Source->GetExternalDecl(ID));
962
963 assert(LazyInitializers.empty() &&
964 "GetExternalDecl for lazy module initializer added more inits");
965}
966
967void ASTContext::addModuleInitializer(Module *M, Decl *D) {
968 // One special case: if we add a module initializer that imports another
969 // module, and that module's only initializer is an ImportDecl, simplify.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000970 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
Richard Smithdc1f0422016-07-20 19:10:16 +0000971 auto It = ModuleInitializers.find(ID->getImportedModule());
972
973 // Maybe the ImportDecl does nothing at all. (Common case.)
974 if (It == ModuleInitializers.end())
975 return;
976
977 // Maybe the ImportDecl only imports another ImportDecl.
978 auto &Imported = *It->second;
979 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
980 Imported.resolve(*this);
981 auto *OnlyDecl = Imported.Initializers.front();
982 if (isa<ImportDecl>(OnlyDecl))
983 D = OnlyDecl;
984 }
985 }
986
987 auto *&Inits = ModuleInitializers[M];
988 if (!Inits)
989 Inits = new (*this) PerModuleInitializers;
990 Inits->Initializers.push_back(D);
991}
992
993void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
994 auto *&Inits = ModuleInitializers[M];
995 if (!Inits)
996 Inits = new (*this) PerModuleInitializers;
997 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
998 IDs.begin(), IDs.end());
999}
1000
Eugene Zelenko7855e772018-04-03 00:11:50 +00001001ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001002 auto It = ModuleInitializers.find(M);
1003 if (It == ModuleInitializers.end())
1004 return None;
1005
1006 auto *Inits = It->second;
1007 Inits->resolve(*this);
1008 return Inits->Initializers;
1009}
1010
Richard Smithf19e1272015-03-07 00:04:49 +00001011ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1012 if (!ExternCContext)
1013 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1014
1015 return ExternCContext;
1016}
1017
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001018BuiltinTemplateDecl *
1019ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1020 const IdentifierInfo *II) const {
1021 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1022 BuiltinTemplate->setImplicit();
1023 TUDecl->addDecl(BuiltinTemplate);
1024
1025 return BuiltinTemplate;
1026}
1027
1028BuiltinTemplateDecl *
1029ASTContext::getMakeIntegerSeqDecl() const {
1030 if (!MakeIntegerSeqDecl)
1031 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1032 getMakeIntegerSeqName());
1033 return MakeIntegerSeqDecl;
1034}
1035
Eric Fiselier6ad68552016-07-01 01:24:09 +00001036BuiltinTemplateDecl *
1037ASTContext::getTypePackElementDecl() const {
1038 if (!TypePackElementDecl)
1039 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1040 getTypePackElementName());
1041 return TypePackElementDecl;
1042}
1043
Alp Toker2dea15b2013-12-17 01:22:38 +00001044RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1045 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001046 SourceLocation Loc;
1047 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001048 if (getLangOpts().CPlusPlus)
1049 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1050 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001051 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001052 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1053 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001054 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001055 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1056 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001057 return NewDecl;
1058}
1059
1060TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1061 StringRef Name) const {
1062 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1063 TypedefDecl *NewDecl = TypedefDecl::Create(
1064 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1065 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1066 NewDecl->setImplicit();
1067 return NewDecl;
1068}
1069
Douglas Gregor801c99d2011-08-12 06:49:56 +00001070TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001071 if (!Int128Decl)
1072 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001073 return Int128Decl;
1074}
1075
1076TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001077 if (!UInt128Decl)
1078 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001079 return UInt128Decl;
1080}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001081
John McCall48f2d582009-10-23 23:03:21 +00001082void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001083 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001084 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001085 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001086}
1087
Artem Belevichb5bc9232015-09-22 17:23:22 +00001088void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1089 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001090 assert((!this->Target || this->Target == &Target) &&
1091 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001092 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001093
Douglas Gregore8bbc122011-09-02 00:18:52 +00001094 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001095 this->AuxTarget = AuxTarget;
1096
Douglas Gregore8bbc122011-09-02 00:18:52 +00001097 ABI.reset(createCXXABI(Target));
1098 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001099 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001100
Chris Lattner970e54e2006-11-12 00:37:36 +00001101 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001102 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001103
Chris Lattner970e54e2006-11-12 00:37:36 +00001104 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001105 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001106 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001107 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001108 InitBuiltinType(CharTy, BuiltinType::Char_S);
1109 else
1110 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001111 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001112 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1113 InitBuiltinType(ShortTy, BuiltinType::Short);
1114 InitBuiltinType(IntTy, BuiltinType::Int);
1115 InitBuiltinType(LongTy, BuiltinType::Long);
1116 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001117
Chris Lattner970e54e2006-11-12 00:37:36 +00001118 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001119 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1120 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1121 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1122 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1123 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001124
Chris Lattner970e54e2006-11-12 00:37:36 +00001125 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001126 InitBuiltinType(FloatTy, BuiltinType::Float);
1127 InitBuiltinType(DoubleTy, BuiltinType::Double);
1128 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001129
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001130 // GNU extension, __float128 for IEEE quadruple precision
1131 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1132
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001133 // C11 extension ISO/IEC TS 18661-3
1134 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1135
Chris Lattnerf122cef2009-04-30 02:43:43 +00001136 // GNU extension, 128-bit integers.
1137 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1138 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1139
Hans Wennborg0d81e012013-05-10 10:08:40 +00001140 // C++ 3.9.1p5
1141 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1142 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1143 else // -fshort-wchar makes wchar_t be unsigned.
1144 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1145 if (LangOpts.CPlusPlus && LangOpts.WChar)
1146 WideCharTy = WCharTy;
1147 else {
1148 // C99 (or C++ using -fno-wchar).
1149 WideCharTy = getFromTargetType(Target.getWCharType());
1150 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001151
James Molloy36365542012-05-04 10:55:22 +00001152 WIntTy = getFromTargetType(Target.getWIntType());
1153
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001154 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1155 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1156 else // C99
1157 Char16Ty = getFromTargetType(Target.getChar16Type());
1158
1159 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1160 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1161 else // C99
1162 Char32Ty = getFromTargetType(Target.getChar32Type());
1163
Douglas Gregor4619e432008-12-05 23:32:09 +00001164 // Placeholder type for type-dependent expressions whose type is
1165 // completely unknown. No code should ever check a type against
1166 // DependentTy and users should never see it; however, it is here to
1167 // help diagnose failures to properly check for type-dependent
1168 // expressions.
1169 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001170
John McCall36e7fe32010-10-12 00:20:44 +00001171 // Placeholder type for functions.
1172 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1173
John McCall0009fcc2011-04-26 20:42:42 +00001174 // Placeholder type for bound members.
1175 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1176
John McCall526ab472011-10-25 17:37:35 +00001177 // Placeholder type for pseudo-objects.
1178 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1179
John McCall31996342011-04-07 08:22:57 +00001180 // "any" type; useful for debugger-like clients.
1181 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1182
John McCall8a6b59a2011-10-17 18:09:15 +00001183 // Placeholder type for unbridged ARC casts.
1184 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1185
Eli Friedman34866c72012-08-31 00:14:07 +00001186 // Placeholder type for builtin functions.
1187 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1188
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001189 // Placeholder type for OMP array sections.
1190 if (LangOpts.OpenMP)
1191 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1192
Chris Lattner970e54e2006-11-12 00:37:36 +00001193 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001194 FloatComplexTy = getComplexType(FloatTy);
1195 DoubleComplexTy = getComplexType(DoubleTy);
1196 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001197 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001198
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001199 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001200 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1201 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001202 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001203
Alexey Bader954ba212016-04-08 13:40:33 +00001204 if (LangOpts.OpenCL) {
1205#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1206 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001207#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001208
Guy Benyei61054192013-02-07 10:55:47 +00001209 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001210 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001211 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1212 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001213 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001214 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001215
1216 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001217 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1218 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001219
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001220 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001221
1222 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001223
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001224 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001225 if (LangOpts.OpenCLVersion >= 200) {
1226 auto Q = VoidTy.getQualifiers();
1227 Q.setAddressSpace(LangAS::opencl_generic);
1228 VoidPtrTy = getPointerType(getCanonicalType(
1229 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1230 } else {
1231 VoidPtrTy = getPointerType(VoidTy);
1232 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001233
1234 // nullptr type (C++0x 2.14.7)
1235 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001236
1237 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1238 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001239
1240 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001241 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001242}
1243
David Blaikie9c902b52011-09-25 23:23:43 +00001244DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001245 return SourceMgr.getDiagnostics();
1246}
1247
Douglas Gregor561eceb2010-08-30 16:49:28 +00001248AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1249 AttrVec *&Result = DeclAttrs[D];
1250 if (!Result) {
1251 void *Mem = Allocate(sizeof(AttrVec));
1252 Result = new (Mem) AttrVec;
1253 }
1254
1255 return *Result;
1256}
1257
1258/// \brief Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001259void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001260 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1261 if (Pos != DeclAttrs.end()) {
1262 Pos->second->~AttrVec();
1263 DeclAttrs.erase(Pos);
1264 }
1265}
1266
Larisse Voufo39a1e502013-08-06 01:03:05 +00001267// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001268MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001269ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001270 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001271 return getTemplateOrSpecializationInfo(Var)
1272 .dyn_cast<MemberSpecializationInfo *>();
1273}
1274
1275ASTContext::TemplateOrSpecializationInfo
1276ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1277 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1278 TemplateOrInstantiation.find(Var);
1279 if (Pos == TemplateOrInstantiation.end())
Eugene Zelenko7855e772018-04-03 00:11:50 +00001280 return {};
Mike Stump11289f42009-09-09 15:08:12 +00001281
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001282 return Pos->second;
1283}
1284
Mike Stump11289f42009-09-09 15:08:12 +00001285void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001286ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001287 TemplateSpecializationKind TSK,
1288 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001289 assert(Inst->isStaticDataMember() && "Not a static data member");
1290 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001291 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1292 Tmpl, TSK, PointOfInstantiation));
1293}
1294
1295void
1296ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1297 TemplateOrSpecializationInfo TSI) {
1298 assert(!TemplateOrInstantiation[Inst] &&
1299 "Already noted what the variable was instantiated from");
1300 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001301}
1302
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001303FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1304 const FunctionDecl *FD){
1305 assert(FD && "Specialization is 0");
1306 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001307 = ClassScopeSpecializationPattern.find(FD);
1308 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001309 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001310
1311 return Pos->second;
1312}
1313
1314void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1315 FunctionDecl *Pattern) {
1316 assert(FD && "Specialization is 0");
1317 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001318 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001319}
1320
John McCalle61f2ba2009-11-18 02:36:19 +00001321NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001322ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1323 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001324 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001325 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001326
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001327 return Pos->second;
1328}
1329
1330void
Richard Smithd8a9e372016-12-18 21:39:37 +00001331ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001332 assert((isa<UsingDecl>(Pattern) ||
1333 isa<UnresolvedUsingValueDecl>(Pattern) ||
1334 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1335 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001336 assert((isa<UsingDecl>(Inst) ||
1337 isa<UnresolvedUsingValueDecl>(Inst) ||
1338 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1339 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001340 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1341 InstantiatedFromUsingDecl[Inst] = Pattern;
1342}
1343
1344UsingShadowDecl *
1345ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1346 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1347 = InstantiatedFromUsingShadowDecl.find(Inst);
1348 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001349 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001350
1351 return Pos->second;
1352}
1353
1354void
1355ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1356 UsingShadowDecl *Pattern) {
1357 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1358 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001359}
1360
Anders Carlsson5da84842009-09-01 04:26:58 +00001361FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1362 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1363 = InstantiatedFromUnnamedFieldDecl.find(Field);
1364 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001365 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001366
Anders Carlsson5da84842009-09-01 04:26:58 +00001367 return Pos->second;
1368}
1369
1370void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1371 FieldDecl *Tmpl) {
1372 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1373 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1374 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1375 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001376
Anders Carlsson5da84842009-09-01 04:26:58 +00001377 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1378}
1379
Douglas Gregor832940b2010-03-02 23:58:15 +00001380ASTContext::overridden_cxx_method_iterator
1381ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001382 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001383}
1384
1385ASTContext::overridden_cxx_method_iterator
1386ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001387 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001388}
1389
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001390unsigned
1391ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001392 auto Range = overridden_methods(Method);
1393 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001394}
1395
Clement Courbet6ecaec82016-07-05 07:49:31 +00001396ASTContext::overridden_method_range
1397ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001398 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1399 OverriddenMethods.find(Method->getCanonicalDecl());
1400 if (Pos == OverriddenMethods.end())
1401 return overridden_method_range(nullptr, nullptr);
1402 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001403}
1404
Douglas Gregor832940b2010-03-02 23:58:15 +00001405void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1406 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001407 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001408 OverriddenMethods[Method].push_back(Overridden);
1409}
1410
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001411void ASTContext::getOverriddenMethods(
1412 const NamedDecl *D,
1413 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001414 assert(D);
1415
Eugene Zelenko7855e772018-04-03 00:11:50 +00001416 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001417 Overridden.append(overridden_methods_begin(CXXMethod),
1418 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001419 return;
1420 }
1421
Eugene Zelenko7855e772018-04-03 00:11:50 +00001422 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001423 if (!Method)
1424 return;
1425
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001426 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1427 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001428 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001429}
1430
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001431void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1432 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1433 assert(!Import->isFromASTFile() && "Non-local import declaration");
1434 if (!FirstLocalImport) {
1435 FirstLocalImport = Import;
1436 LastLocalImport = Import;
1437 return;
1438 }
1439
1440 LastLocalImport->NextLocalImport = Import;
1441 LastLocalImport = Import;
1442}
1443
Chris Lattner53cfe802007-07-18 17:52:12 +00001444//===----------------------------------------------------------------------===//
1445// Type Sizing and Analysis
1446//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001447
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001448/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1449/// scalar floating point type.
1450const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001451 const auto *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001452 assert(BT && "Not a floating point type!");
1453 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001454 default: llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001455 case BuiltinType::Float16:
1456 case BuiltinType::Half:
1457 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001458 case BuiltinType::Float: return Target->getFloatFormat();
1459 case BuiltinType::Double: return Target->getDoubleFormat();
1460 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001461 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001462 }
1463}
1464
Rafael Espindola71eccb32013-08-08 19:53:46 +00001465CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001466 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001467
John McCall94268702010-10-08 18:24:19 +00001468 bool UseAlignAttrOnly = false;
1469 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1470 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001471
John McCall94268702010-10-08 18:24:19 +00001472 // __attribute__((aligned)) can increase or decrease alignment
1473 // *except* on a struct or struct member, where it only increases
1474 // alignment unless 'packed' is also specified.
1475 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001476 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001477 // ignore that possibility; Sema should diagnose it.
1478 if (isa<FieldDecl>(D)) {
1479 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1480 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1481 } else {
1482 UseAlignAttrOnly = true;
1483 }
1484 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001485 else if (isa<FieldDecl>(D))
1486 UseAlignAttrOnly =
1487 D->hasAttr<PackedAttr>() ||
1488 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001489
John McCall4e819612011-01-20 07:57:12 +00001490 // If we're using the align attribute only, just ignore everything
1491 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001492 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001493 // do nothing
Eugene Zelenko7855e772018-04-03 00:11:50 +00001494 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001495 QualType T = VD->getType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001496 if (const auto *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001497 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001498 T = RT->getPointeeType();
1499 else
1500 T = getPointerType(RT->getPointeeType());
1501 }
Richard Smithf6d70302014-06-10 23:34:28 +00001502 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001503 if (T->isFunctionType())
1504 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1505 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001506 // Adjust alignments of declarations with array type by the
1507 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001508 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001509 unsigned MinWidth = Target->getLargeArrayMinWidth();
1510 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001511 if (isa<VariableArrayType>(arrayType))
1512 Align = std::max(Align, Target->getLargeArrayAlign());
1513 else if (isa<ConstantArrayType>(arrayType) &&
1514 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1515 Align = std::max(Align, Target->getLargeArrayAlign());
1516 }
John McCall33ddac02011-01-19 10:06:00 +00001517 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001518 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001519 if (BaseT.getQualifiers().hasUnaligned())
1520 Align = Target->getCharWidth();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001521 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001522 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001523 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1524 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001525 }
John McCall4e819612011-01-20 07:57:12 +00001526
1527 // Fields can be subject to extra alignment constraints, like if
1528 // the field is packed, the struct is packed, or the struct has a
1529 // a max-field-alignment constraint (#pragma pack). So calculate
1530 // the actual alignment of the field within the struct, and then
1531 // (as we're expected to) constrain that by the alignment of the type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001532 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001533 const RecordDecl *Parent = Field->getParent();
1534 // We can only produce a sensible answer if the record is valid.
1535 if (!Parent->isInvalidDecl()) {
1536 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001537
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001538 // Start with the record's overall alignment.
1539 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001540
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001541 // Use the GCD of that and the offset within the record.
1542 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1543 if (Offset > 0) {
1544 // Alignment is always a power of 2, so the GCD will be a power of 2,
1545 // which means we get to do this crazy thing instead of Euclid's.
1546 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1547 if (LowBitOfOffset < FieldAlign)
1548 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1549 }
1550
1551 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001552 }
Charles Davis3fc51072010-02-23 04:52:00 +00001553 }
Chris Lattner68061312009-01-24 21:53:27 +00001554 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001555
Ken Dyckcc56c542011-01-15 18:38:59 +00001556 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001557}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001558
John McCallf1249922012-08-21 04:10:00 +00001559// getTypeInfoDataSizeInChars - Return the size of a type, in
1560// chars. If the type is a record, its data size is returned. This is
1561// the size of the memcpy that's performed when assigning this type
1562// using a trivial copy/move assignment operator.
1563std::pair<CharUnits, CharUnits>
1564ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1565 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1566
1567 // In C++, objects can sometimes be allocated into the tail padding
1568 // of a base-class subobject. We decide whether that's possible
1569 // during class layout, so here we can just trust the layout results.
1570 if (getLangOpts().CPlusPlus) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001571 if (const auto *RT = T->getAs<RecordType>()) {
John McCallf1249922012-08-21 04:10:00 +00001572 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1573 sizeAndAlign.first = layout.getDataSize();
1574 }
1575 }
1576
1577 return sizeAndAlign;
1578}
1579
Richard Trieu04d2d942013-05-14 21:59:17 +00001580/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1581/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1582std::pair<CharUnits, CharUnits>
1583static getConstantArrayInfoInChars(const ASTContext &Context,
1584 const ConstantArrayType *CAT) {
1585 std::pair<CharUnits, CharUnits> EltInfo =
1586 Context.getTypeInfoInChars(CAT->getElementType());
1587 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001588 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1589 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001590 "Overflow in array type char size evaluation");
1591 uint64_t Width = EltInfo.first.getQuantity() * Size;
1592 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001593 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1594 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001595 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001596 return std::make_pair(CharUnits::fromQuantity(Width),
1597 CharUnits::fromQuantity(Align));
1598}
1599
John McCall87fe5d52010-05-20 01:18:31 +00001600std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001601ASTContext::getTypeInfoInChars(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001602 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
Richard Trieu04d2d942013-05-14 21:59:17 +00001603 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001604 TypeInfo Info = getTypeInfo(T);
1605 return std::make_pair(toCharUnitsFromBits(Info.Width),
1606 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001607}
1608
1609std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001610ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001611 return getTypeInfoInChars(T.getTypePtr());
1612}
1613
David Majnemer34b57492014-07-30 01:30:47 +00001614bool ASTContext::isAlignmentRequired(const Type *T) const {
1615 return getTypeInfo(T).AlignIsRequired;
1616}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001617
David Majnemer34b57492014-07-30 01:30:47 +00001618bool ASTContext::isAlignmentRequired(QualType T) const {
1619 return isAlignmentRequired(T.getTypePtr());
1620}
1621
Richard Smithb2f0f052016-10-10 18:54:32 +00001622unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1623 // An alignment on a typedef overrides anything else.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001624 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001625 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1626 return Align;
1627
1628 // If we have an (array of) complete type, we're done.
1629 T = getBaseElementType(T);
1630 if (!T->isIncompleteType())
1631 return getTypeAlign(T);
1632
1633 // If we had an array type, its element type might be a typedef
1634 // type with an alignment attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001635 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001636 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1637 return Align;
1638
1639 // Otherwise, see if the declaration of the type had an attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001640 if (const auto *TT = T->getAs<TagType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001641 return TT->getDecl()->getMaxAlignment();
1642
1643 return 0;
1644}
1645
David Majnemer34b57492014-07-30 01:30:47 +00001646TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001647 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1648 if (I != MemoizedTypeInfo.end())
1649 return I->second;
1650
1651 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1652 TypeInfo TI = getTypeInfoImpl(T);
1653 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001654 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001655}
1656
1657/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1658/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001659///
1660/// FIXME: Pointers into different addr spaces could have different sizes and
1661/// alignment requirements: getPointerInfo should take an AddrSpace, this
1662/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001663TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1664 uint64_t Width = 0;
1665 unsigned Align = 8;
1666 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001667 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001668 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001669#define TYPE(Class, Base)
1670#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001671#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001672#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001673#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1674 case Type::Class: \
1675 assert(!T->isDependentType() && "should not see dependent types here"); \
1676 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001677#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001678 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001679
Chris Lattner355332d2007-07-13 22:27:08 +00001680 case Type::FunctionNoProto:
1681 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001682 // GCC extension: alignof(function) = 32 bits
1683 Width = 0;
1684 Align = 32;
1685 break;
1686
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001687 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001688 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001689 Width = 0;
1690 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1691 break;
1692
Steve Naroff5c131802007-08-30 01:06:46 +00001693 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001694 const auto *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001695
David Majnemer34b57492014-07-30 01:30:47 +00001696 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001697 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001698 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001699 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001700 Width = EltInfo.Width * Size;
1701 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001702 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1703 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001704 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001705 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001706 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001707 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001708 case Type::Vector: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001709 const auto *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001710 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1711 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001712 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001713 // If the alignment is not a power of 2, round up to the next power of 2.
1714 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001715 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001716 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001717 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001718 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001719 // Adjust the alignment based on the target max.
1720 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1721 if (TargetVectorAlign && TargetVectorAlign < Align)
1722 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001723 break;
1724 }
Chris Lattner647fb222007-07-18 18:26:58 +00001725
Chris Lattner7570e9c2008-03-08 08:52:55 +00001726 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001727 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001728 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001729 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001730 // GCC extension: alignof(void) = 8 bits.
1731 Width = 0;
1732 Align = 8;
1733 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001734 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001735 Width = Target->getBoolWidth();
1736 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001737 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001738 case BuiltinType::Char_S:
1739 case BuiltinType::Char_U:
1740 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001741 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001742 Width = Target->getCharWidth();
1743 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001744 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001745 case BuiltinType::WChar_S:
1746 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001747 Width = Target->getWCharWidth();
1748 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001749 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001750 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001751 Width = Target->getChar16Width();
1752 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001753 break;
1754 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001755 Width = Target->getChar32Width();
1756 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001757 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001758 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001759 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001760 Width = Target->getShortWidth();
1761 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001762 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001763 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001764 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001765 Width = Target->getIntWidth();
1766 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001767 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001768 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001769 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001770 Width = Target->getLongWidth();
1771 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001772 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001773 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001774 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001775 Width = Target->getLongLongWidth();
1776 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001777 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001778 case BuiltinType::Int128:
1779 case BuiltinType::UInt128:
1780 Width = 128;
1781 Align = 128; // int128_t is 128-bit aligned on all targets.
1782 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001783 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001784 case BuiltinType::Half:
1785 Width = Target->getHalfWidth();
1786 Align = Target->getHalfAlign();
1787 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001788 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001789 Width = Target->getFloatWidth();
1790 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001791 break;
1792 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001793 Width = Target->getDoubleWidth();
1794 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001795 break;
1796 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001797 Width = Target->getLongDoubleWidth();
1798 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001799 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001800 case BuiltinType::Float128:
1801 Width = Target->getFloat128Width();
1802 Align = Target->getFloat128Align();
1803 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001804 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001805 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1806 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001807 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001808 case BuiltinType::ObjCId:
1809 case BuiltinType::ObjCClass:
1810 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001811 Width = Target->getPointerWidth(0);
1812 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001813 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001814 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001815 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001816 case BuiltinType::OCLClkEvent:
1817 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001818 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00001819#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1820 case BuiltinType::Id:
1821#include "clang/Basic/OpenCLImageTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00001822 AS = getTargetAddressSpace(
1823 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001824 Width = Target->getPointerWidth(AS);
1825 Align = Target->getPointerAlign(AS);
1826 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001827 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001828 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001829 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001830 Width = Target->getPointerWidth(0);
1831 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001832 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001833 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001834 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001835 Width = Target->getPointerWidth(AS);
1836 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001837 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001838 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001839 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001840 // alignof and sizeof should never enter this code path here, so we go
1841 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001842 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001843 Width = Target->getPointerWidth(AS);
1844 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001845 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001846 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001847 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001848 Width = Target->getPointerWidth(AS);
1849 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001850 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001851 case Type::MemberPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001852 const auto *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00001853 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
1854 Width = MPI.Width;
1855 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00001856 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001857 }
Chris Lattner647fb222007-07-18 18:26:58 +00001858 case Type::Complex: {
1859 // Complex types have the same alignment as their elements, but twice the
1860 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001861 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1862 Width = EltInfo.Width * 2;
1863 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001864 break;
1865 }
John McCall8b07ec22010-05-15 11:32:37 +00001866 case Type::ObjCObject:
1867 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001868 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001869 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001870 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001871 case Type::ObjCInterface: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001872 const auto *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001873 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001874 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001875 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001876 break;
1877 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001878 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001879 case Type::Enum: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001880 const auto *TT = cast<TagType>(T);
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001881
1882 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001883 Width = 8;
1884 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001885 break;
1886 }
Mike Stump11289f42009-09-09 15:08:12 +00001887
Eugene Zelenko7855e772018-04-03 00:11:50 +00001888 if (const auto *ET = dyn_cast<EnumType>(TT)) {
David Majnemer475b25e2015-01-21 10:54:38 +00001889 const EnumDecl *ED = ET->getDecl();
1890 TypeInfo Info =
1891 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1892 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1893 Info.Align = AttrAlign;
1894 Info.AlignIsRequired = true;
1895 }
1896 return Info;
1897 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001898
Eugene Zelenko7855e772018-04-03 00:11:50 +00001899 const auto *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001900 const RecordDecl *RD = RT->getDecl();
1901 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001902 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001903 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001904 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001905 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001906 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001907
Chris Lattner63d2b362009-10-22 05:17:15 +00001908 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001909 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1910 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001911
Richard Smith600b5262017-01-26 20:40:47 +00001912 case Type::Auto:
1913 case Type::DeducedTemplateSpecialization: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001914 const auto *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001915 assert(!A->getDeducedType().isNull() &&
1916 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001917 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001918 }
1919
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001920 case Type::Paren:
1921 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1922
Manman Rene6be26c2016-09-13 17:25:08 +00001923 case Type::ObjCTypeParam:
1924 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1925
Douglas Gregoref462e62009-04-30 17:32:17 +00001926 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001927 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001928 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001929 // If the typedef has an aligned attribute on it, it overrides any computed
1930 // alignment we have. This violates the GCC documentation (which says that
1931 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001932 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001933 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001934 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001935 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001936 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001937 AlignIsRequired = Info.AlignIsRequired;
1938 }
David Majnemer34b57492014-07-30 01:30:47 +00001939 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001940 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001941 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001942
Abramo Bagnara6150c882010-05-11 21:36:43 +00001943 case Type::Elaborated:
1944 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001945
John McCall81904512011-01-06 01:58:22 +00001946 case Type::Attributed:
1947 return getTypeInfo(
1948 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1949
Eli Friedman0dfb8892011-10-06 23:00:33 +00001950 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001951 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001952 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1953 Width = Info.Width;
1954 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001955
1956 // If the size of the type doesn't exceed the platform's max
1957 // atomic promotion width, make the size and alignment more
1958 // favorable to atomic operations:
1959 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1960 // Round the size up to a power of 2.
1961 if (!llvm::isPowerOf2_64(Width))
1962 Width = llvm::NextPowerOf2(Width);
1963
1964 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001965 Align = static_cast<unsigned>(Width);
1966 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001967 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001968 break;
1969
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001970 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00001971 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
1972 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001973 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00001974 }
Mike Stump11289f42009-09-09 15:08:12 +00001975
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001976 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001977 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001978}
1979
Alexey Bataev00396512015-07-02 03:40:19 +00001980unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1981 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1982 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1983 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1984 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1985 getTargetInfo().getABI() == "elfv1-qpx" &&
1986 T->isSpecificBuiltinType(BuiltinType::Double))
1987 SimdAlign = 256;
1988 return SimdAlign;
1989}
1990
Ken Dyckcc56c542011-01-15 18:38:59 +00001991/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1992CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1993 return CharUnits::fromQuantity(BitSize / getCharWidth());
1994}
1995
Ken Dyckb0fcc592011-02-11 01:54:29 +00001996/// toBits - Convert a size in characters to a size in characters.
1997int64_t ASTContext::toBits(CharUnits CharSize) const {
1998 return CharSize.getQuantity() * getCharWidth();
1999}
2000
Ken Dyck8c89d592009-12-22 14:23:30 +00002001/// getTypeSizeInChars - Return the size of the specified type, in characters.
2002/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002003CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002004 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002005}
Jay Foad39c79802011-01-12 09:06:06 +00002006CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002007 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002008}
2009
Ken Dycka6046ab2010-01-26 17:25:18 +00002010/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002011/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002012CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002013 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002014}
Jay Foad39c79802011-01-12 09:06:06 +00002015CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002016 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002017}
2018
Chris Lattnera3402cd2009-01-27 18:08:34 +00002019/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2020/// type for the current target in bits. This can be different than the ABI
2021/// alignment in cases where it is beneficial for performance to overalign
2022/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002023unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002024 TypeInfo TI = getTypeInfo(T);
2025 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002026
David Majnemere1544562015-04-24 01:25:05 +00002027 T = T->getBaseElementTypeUnsafe();
2028
2029 // The preferred alignment of member pointers is that of a pointer.
2030 if (T->isMemberPointerType())
2031 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2032
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002033 if (!Target->allowsLargerPreferedTypeAlignment())
2034 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002035
Eli Friedman7ab09572009-05-25 21:27:19 +00002036 // Double and long long should be naturally aligned if possible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002037 if (const auto *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002038 T = CT->getElementType().getTypePtr();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002039 if (const auto *ET = T->getAs<EnumType>())
David Majnemer475b25e2015-01-21 10:54:38 +00002040 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002041 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002042 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2043 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002044 // Don't increase the alignment if an alignment attribute was specified on a
2045 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002046 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002047 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002048
Chris Lattnera3402cd2009-01-27 18:08:34 +00002049 return ABIAlign;
2050}
2051
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002052/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2053/// for __attribute__((aligned)) on this target, to be used if no alignment
2054/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002055unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002056 return getTargetInfo().getDefaultAlignForAttributeAligned();
2057}
2058
Ulrich Weigandfa806422013-05-06 16:23:57 +00002059/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2060/// to a global variable of the specified type.
2061unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2062 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2063}
2064
2065/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2066/// should be given to a global variable of the specified type.
2067CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2068 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2069}
2070
David Majnemer08ef2ba2015-06-23 20:34:18 +00002071CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2072 CharUnits Offset = CharUnits::Zero();
2073 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2074 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2075 Offset += Layout->getBaseClassOffset(Base);
2076 Layout = &getASTRecordLayout(Base);
2077 }
2078 return Offset;
2079}
2080
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002081/// DeepCollectObjCIvars -
2082/// This routine first collects all declared, but not synthesized, ivars in
2083/// super class and then collects all ivars, including those synthesized for
2084/// current class. This routine is used for implementation of current class
2085/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002086void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2087 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002088 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002089 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2090 DeepCollectObjCIvars(SuperClass, false, Ivars);
2091 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002092 for (const auto *I : OI->ivars())
2093 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002094 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002095 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00002096 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002097 Iv= Iv->getNextIvar())
2098 Ivars.push_back(Iv);
2099 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002100}
2101
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002102/// CollectInheritedProtocols - Collect all protocols in current class and
2103/// those inherited by it.
2104void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002105 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002106 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002107 // We can use protocol_iterator here instead of
2108 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002109 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002110 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002111 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002112
2113 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002114 for (const auto *Cat : OI->visible_categories())
2115 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002116
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002117 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2118 while (SD) {
2119 CollectInheritedProtocols(SD, Protocols);
2120 SD = SD->getSuperClass();
2121 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002122 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002123 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002124 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002125 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002126 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002127 // Insert the protocol.
2128 if (!Protocols.insert(
2129 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2130 return;
2131
2132 for (auto *Proto : OP->protocols())
2133 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002134 }
2135}
2136
Erich Keane8a6b7402017-11-30 16:37:02 +00002137static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2138 const RecordDecl *RD) {
2139 assert(RD->isUnion() && "Must be union type");
2140 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2141
2142 for (const auto *Field : RD->fields()) {
2143 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2144 return false;
2145 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2146 if (FieldSize != UnionSize)
2147 return false;
2148 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002149 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002150}
2151
Benjamin Kramer802e6252017-12-24 12:46:22 +00002152static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002153 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2154
2155 if (!RD->field_empty())
2156 return false;
2157
2158 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2159 return ClassDecl->isEmpty();
2160
2161 return true;
2162}
2163
2164static llvm::Optional<int64_t>
2165structHasUniqueObjectRepresentations(const ASTContext &Context,
2166 const RecordDecl *RD) {
2167 assert(!RD->isUnion() && "Must be struct/class type");
2168 const auto &Layout = Context.getASTRecordLayout(RD);
2169
2170 int64_t CurOffsetInBits = 0;
2171 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2172 if (ClassDecl->isDynamicClass())
2173 return llvm::None;
2174
2175 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2176 for (const auto Base : ClassDecl->bases()) {
2177 // Empty types can be inherited from, and non-empty types can potentially
2178 // have tail padding, so just make sure there isn't an error.
2179 if (!isStructEmpty(Base.getType())) {
2180 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2181 Context, Base.getType()->getAs<RecordType>()->getDecl());
2182 if (!Size)
2183 return llvm::None;
2184 Bases.emplace_back(Base.getType(), Size.getValue());
2185 }
2186 }
2187
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00002188 llvm::sort(
Erich Keane8a6b7402017-11-30 16:37:02 +00002189 Bases.begin(), Bases.end(), [&](const std::pair<QualType, int64_t> &L,
2190 const std::pair<QualType, int64_t> &R) {
2191 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2192 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2193 });
2194
2195 for (const auto Base : Bases) {
2196 int64_t BaseOffset = Context.toBits(
2197 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2198 int64_t BaseSize = Base.second;
2199 if (BaseOffset != CurOffsetInBits)
2200 return llvm::None;
2201 CurOffsetInBits = BaseOffset + BaseSize;
2202 }
2203 }
2204
2205 for (const auto *Field : RD->fields()) {
2206 if (!Field->getType()->isReferenceType() &&
2207 !Context.hasUniqueObjectRepresentations(Field->getType()))
2208 return llvm::None;
2209
2210 int64_t FieldSizeInBits =
2211 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2212 if (Field->isBitField()) {
2213 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2214
2215 if (BitfieldSize > FieldSizeInBits)
2216 return llvm::None;
2217 FieldSizeInBits = BitfieldSize;
2218 }
2219
2220 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2221
2222 if (FieldOffsetInBits != CurOffsetInBits)
2223 return llvm::None;
2224
2225 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2226 }
2227
2228 return CurOffsetInBits;
2229}
2230
2231bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2232 // C++17 [meta.unary.prop]:
2233 // The predicate condition for a template specialization
2234 // has_unique_object_representations<T> shall be
2235 // satisfied if and only if:
2236 // (9.1) - T is trivially copyable, and
2237 // (9.2) - any two objects of type T with the same value have the same
2238 // object representation, where two objects
2239 // of array or non-union class type are considered to have the same value
2240 // if their respective sequences of
2241 // direct subobjects have the same values, and two objects of union type
2242 // are considered to have the same
2243 // value if they have the same active member and the corresponding members
2244 // have the same value.
2245 // The set of scalar types for which this condition holds is
2246 // implementation-defined. [ Note: If a type has padding
2247 // bits, the condition does not hold; otherwise, the condition holds true
2248 // for unsigned integral types. -- end note ]
2249 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2250
2251 // Arrays are unique only if their element type is unique.
2252 if (Ty->isArrayType())
2253 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2254
2255 // (9.1) - T is trivially copyable...
2256 if (!Ty.isTriviallyCopyableType(*this))
2257 return false;
2258
2259 // All integrals and enums are unique.
2260 if (Ty->isIntegralOrEnumerationType())
2261 return true;
2262
2263 // All other pointers are unique.
2264 if (Ty->isPointerType())
2265 return true;
2266
2267 if (Ty->isMemberPointerType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002268 const auto *MPT = Ty->getAs<MemberPointerType>();
Erich Keane8a6b7402017-11-30 16:37:02 +00002269 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2270 }
2271
2272 if (Ty->isRecordType()) {
2273 const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
2274
Erich Keanebd2197c2017-12-12 16:02:06 +00002275 if (Record->isInvalidDecl())
2276 return false;
2277
Erich Keane8a6b7402017-11-30 16:37:02 +00002278 if (Record->isUnion())
2279 return unionHasUniqueObjectRepresentations(*this, Record);
2280
2281 Optional<int64_t> StructSize =
2282 structHasUniqueObjectRepresentations(*this, Record);
2283
2284 return StructSize &&
2285 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2286 }
2287
2288 // FIXME: More cases to handle here (list by rsmith):
2289 // vectors (careful about, eg, vector of 3 foo)
2290 // _Complex int and friends
2291 // _Atomic T
2292 // Obj-C block pointers
2293 // Obj-C object pointers
2294 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2295 // clk_event_t, queue_t, reserve_id_t)
2296 // There're also Obj-C class types and the Obj-C selector type, but I think it
2297 // makes sense for those to return false here.
2298
2299 return false;
2300}
2301
Jay Foad39c79802011-01-12 09:06:06 +00002302unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002303 unsigned count = 0;
2304 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002305 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002306 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002307
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002308 // Count ivar defined in this class's implementation. This
2309 // includes synthesized ivars.
2310 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002311 count += ImplDecl->ivar_size();
2312
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002313 return count;
2314}
2315
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002316bool ASTContext::isSentinelNullExpr(const Expr *E) {
2317 if (!E)
2318 return false;
2319
2320 // nullptr_t is always treated as null.
2321 if (E->getType()->isNullPtrType()) return true;
2322
2323 if (E->getType()->isAnyPointerType() &&
2324 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2325 Expr::NPC_ValueDependentIsNull))
2326 return true;
2327
2328 // Unfortunately, __null has type 'int'.
2329 if (isa<GNUNullExpr>(E)) return true;
2330
2331 return false;
2332}
2333
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002334/// \brief Get the implementation of ObjCInterfaceDecl, or nullptr if none
2335/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002336ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2337 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2338 I = ObjCImpls.find(D);
2339 if (I != ObjCImpls.end())
2340 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002341 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002342}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002343
2344/// \brief Get the implementation of ObjCCategoryDecl, or nullptr if none
2345/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002346ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2347 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2348 I = ObjCImpls.find(D);
2349 if (I != ObjCImpls.end())
2350 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002351 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002352}
2353
2354/// \brief Set the implementation of ObjCInterfaceDecl.
2355void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2356 ObjCImplementationDecl *ImplD) {
2357 assert(IFaceD && ImplD && "Passed null params");
2358 ObjCImpls[IFaceD] = ImplD;
2359}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002360
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002361/// \brief Set the implementation of ObjCCategoryDecl.
2362void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2363 ObjCCategoryImplDecl *ImplD) {
2364 assert(CatD && ImplD && "Passed null params");
2365 ObjCImpls[CatD] = ImplD;
2366}
2367
Chandler Carruth21c90602015-12-30 03:24:14 +00002368const ObjCMethodDecl *
2369ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2370 return ObjCMethodRedecls.lookup(MD);
2371}
2372
2373void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2374 const ObjCMethodDecl *Redecl) {
2375 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2376 ObjCMethodRedecls[MD] = Redecl;
2377}
2378
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002379const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2380 const NamedDecl *ND) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002381 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002382 return ID;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002383 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002384 return CD->getClassInterface();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002385 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002386 return IMD->getClassInterface();
2387
Craig Topper36250ad2014-05-12 05:36:57 +00002388 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002389}
2390
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002391/// \brief Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002392/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002393Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002394 assert(VD && "Passed null params");
2395 assert(VD->hasAttr<BlocksAttr>() &&
2396 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002397 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002398 I = BlockVarCopyInits.find(VD);
George Burgess IV00f70bd2018-03-01 05:43:23 +00002399 return (I != BlockVarCopyInits.end()) ? I->second : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002400}
2401
2402/// \brief Set the copy inialization expression of a block var decl.
2403void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2404 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002405 assert(VD->hasAttr<BlocksAttr>() &&
2406 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002407 BlockVarCopyInits[VD] = Init;
2408}
2409
John McCallbcd03502009-12-07 02:54:59 +00002410TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002411 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002412 if (!DataSize)
2413 DataSize = TypeLoc::getFullDataSizeForType(T);
2414 else
2415 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002416 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002417
Eugene Zelenko7855e772018-04-03 00:11:50 +00002418 auto *TInfo =
John McCallbcd03502009-12-07 02:54:59 +00002419 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2420 new (TInfo) TypeSourceInfo(T);
2421 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002422}
2423
John McCallbcd03502009-12-07 02:54:59 +00002424TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002425 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002426 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002427 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002428 return DI;
2429}
2430
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002431const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002432ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002433 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002434}
2435
2436const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002437ASTContext::getASTObjCImplementationLayout(
2438 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002439 return getObjCLayout(D->getClassInterface(), D);
2440}
2441
Chris Lattner983a8bb2007-07-13 22:13:22 +00002442//===----------------------------------------------------------------------===//
2443// Type creation/memoization methods
2444//===----------------------------------------------------------------------===//
2445
Jay Foad39c79802011-01-12 09:06:06 +00002446QualType
John McCall33ddac02011-01-19 10:06:00 +00002447ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2448 unsigned fastQuals = quals.getFastQualifiers();
2449 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002450
2451 // Check if we've already instantiated this type.
2452 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002453 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002454 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002455 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2456 assert(eq->getQualifiers() == quals);
2457 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002458 }
2459
John McCall33ddac02011-01-19 10:06:00 +00002460 // If the base type is not canonical, make the appropriate canonical type.
2461 QualType canon;
2462 if (!baseType->isCanonicalUnqualified()) {
2463 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002464 canonSplit.Quals.addConsistentQualifiers(quals);
2465 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002466
2467 // Re-find the insert position.
2468 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2469 }
2470
Eugene Zelenko7855e772018-04-03 00:11:50 +00002471 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
John McCall33ddac02011-01-19 10:06:00 +00002472 ExtQualNodes.InsertNode(eq, insertPos);
2473 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002474}
2475
Alexander Richardson6d989432017-10-15 18:48:14 +00002476QualType ASTContext::getAddrSpaceQualType(QualType T,
2477 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002478 QualType CanT = getCanonicalType(T);
2479 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002480 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002481
John McCall8ccfcb52009-09-24 19:53:00 +00002482 // If we are composing extended qualifiers together, merge together
2483 // into one ExtQuals node.
2484 QualifierCollector Quals;
2485 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002486
John McCall8ccfcb52009-09-24 19:53:00 +00002487 // If this type already has an address space specified, it cannot get
2488 // another one.
2489 assert(!Quals.hasAddressSpace() &&
2490 "Type cannot be in multiple addr spaces!");
2491 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002492
John McCall8ccfcb52009-09-24 19:53:00 +00002493 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002494}
2495
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002496QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2497 // If we are composing extended qualifiers together, merge together
2498 // into one ExtQuals node.
2499 QualifierCollector Quals;
2500 const Type *TypeNode = Quals.strip(T);
2501
2502 // If the qualifier doesn't have an address space just return it.
2503 if (!Quals.hasAddressSpace())
2504 return T;
2505
2506 Quals.removeAddressSpace();
2507
2508 // Removal of the address space can mean there are no longer any
2509 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2510 // or required.
2511 if (Quals.hasNonFastQualifiers())
2512 return getExtQualType(TypeNode, Quals);
2513 else
2514 return QualType(TypeNode, Quals.getFastQualifiers());
2515}
2516
Chris Lattnerd60183d2009-02-18 22:53:11 +00002517QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002518 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002519 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002520 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002521 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002522
Eugene Zelenko7855e772018-04-03 00:11:50 +00002523 if (const auto *ptr = T->getAs<PointerType>()) {
John McCall53fa7142010-12-24 02:08:15 +00002524 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002525 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002526 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2527 return getPointerType(ResultType);
2528 }
2529 }
Mike Stump11289f42009-09-09 15:08:12 +00002530
John McCall8ccfcb52009-09-24 19:53:00 +00002531 // If we are composing extended qualifiers together, merge together
2532 // into one ExtQuals node.
2533 QualifierCollector Quals;
2534 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002535
John McCall8ccfcb52009-09-24 19:53:00 +00002536 // If this type already has an ObjCGC specified, it cannot get
2537 // another one.
2538 assert(!Quals.hasObjCGCAttr() &&
2539 "Type cannot have multiple ObjCGCs!");
2540 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002541
John McCall8ccfcb52009-09-24 19:53:00 +00002542 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002543}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002544
John McCall4f5019e2010-12-19 02:44:49 +00002545const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2546 FunctionType::ExtInfo Info) {
2547 if (T->getExtInfo() == Info)
2548 return T;
2549
2550 QualType Result;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002551 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002552 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002553 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002554 const auto *FPT = cast<FunctionProtoType>(T);
John McCall4f5019e2010-12-19 02:44:49 +00002555 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2556 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002557 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002558 }
2559
2560 return cast<FunctionType>(Result.getTypePtr());
2561}
2562
Richard Smith2a7d4812013-05-04 07:00:32 +00002563void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2564 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002565 FD = FD->getMostRecentDecl();
2566 while (true) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002567 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smith2a7d4812013-05-04 07:00:32 +00002568 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002569 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002570 if (FunctionDecl *Next = FD->getPreviousDecl())
2571 FD = Next;
2572 else
2573 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002574 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002575 if (ASTMutationListener *L = getASTMutationListener())
2576 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002577}
2578
Richard Smith0b3a4622014-11-13 20:01:57 +00002579/// Get a function type and produce the equivalent function type with the
2580/// specified exception specification. Type sugar that can be present on a
2581/// declaration of a function with an exception specification is permitted
2582/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002583QualType ASTContext::getFunctionTypeWithExceptionSpec(
2584 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002585 // Might have some parens.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002586 if (const auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002587 return getParenType(
2588 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002589
2590 // Might have a calling-convention attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002591 if (const auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002592 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002593 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002594 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2595 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002596
2597 // Anything else must be a function type. Rebuild it with the new exception
2598 // specification.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002599 const auto *Proto = cast<FunctionProtoType>(Orig);
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002600 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002601 Proto->getReturnType(), Proto->getParamTypes(),
2602 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2603}
2604
Richard Smithdfe85e22016-12-15 02:35:39 +00002605bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2606 QualType U) {
2607 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002608 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002609 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2610 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002611}
2612
Richard Smith0b3a4622014-11-13 20:01:57 +00002613void ASTContext::adjustExceptionSpec(
2614 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2615 bool AsWritten) {
2616 // Update the type.
2617 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002618 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002619 FD->setType(Updated);
2620
2621 if (!AsWritten)
2622 return;
2623
2624 // Update the type in the type source information too.
2625 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2626 // If the type and the type-as-written differ, we may need to update
2627 // the type-as-written too.
2628 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002629 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002630
2631 // FIXME: When we get proper type location information for exceptions,
2632 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2633 // up the TypeSourceInfo;
2634 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2635 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2636 "TypeLoc size mismatch from updating exception specification");
2637 TSInfo->overrideType(Updated);
2638 }
2639}
2640
Akira Hatanaka02914dc2018-02-05 20:23:22 +00002641bool ASTContext::isParamDestroyedInCallee(QualType T) const {
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00002642 if (getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
2643 return true;
2644 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2645 return RT->getDecl()->isParamDestroyedInCallee();
2646 return false;
Akira Hatanaka02914dc2018-02-05 20:23:22 +00002647}
2648
Chris Lattnerc6395932007-06-22 20:56:16 +00002649/// getComplexType - Return the uniqued reference to the type for a complex
2650/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002651QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002652 // Unique pointers, to guarantee there is only one pointer of a particular
2653 // structure.
2654 llvm::FoldingSetNodeID ID;
2655 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002656
Craig Topper36250ad2014-05-12 05:36:57 +00002657 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002658 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2659 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002660
Chris Lattnerc6395932007-06-22 20:56:16 +00002661 // If the pointee type isn't canonical, this won't be a canonical type either,
2662 // so fill in the canonical type field.
2663 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002664 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002665 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002666
Chris Lattnerc6395932007-06-22 20:56:16 +00002667 // Get the new insert position for the node we care about.
2668 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002669 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002670 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002671 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002672 Types.push_back(New);
2673 ComplexTypes.InsertNode(New, InsertPos);
2674 return QualType(New, 0);
2675}
2676
Chris Lattner970e54e2006-11-12 00:37:36 +00002677/// getPointerType - Return the uniqued reference to the type for a pointer to
2678/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002679QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002680 // Unique pointers, to guarantee there is only one pointer of a particular
2681 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002682 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002683 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002684
Craig Topper36250ad2014-05-12 05:36:57 +00002685 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002686 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002687 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002688
Chris Lattner7ccecb92006-11-12 08:50:50 +00002689 // If the pointee type isn't canonical, this won't be a canonical type either,
2690 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002691 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002692 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002693 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002694
Bob Wilsonc8541f22013-03-15 17:12:43 +00002695 // Get the new insert position for the node we care about.
2696 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002697 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002698 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002699 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002700 Types.push_back(New);
2701 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002702 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002703}
2704
Reid Kleckner0503a872013-12-05 01:23:43 +00002705QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2706 llvm::FoldingSetNodeID ID;
2707 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002708 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002709 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2710 if (AT)
2711 return QualType(AT, 0);
2712
2713 QualType Canonical = getCanonicalType(New);
2714
2715 // Get the new insert position for the node we care about.
2716 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002717 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002718
2719 AT = new (*this, TypeAlignment)
2720 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2721 Types.push_back(AT);
2722 AdjustedTypes.InsertNode(AT, InsertPos);
2723 return QualType(AT, 0);
2724}
2725
Reid Kleckner8a365022013-06-24 17:51:48 +00002726QualType ASTContext::getDecayedType(QualType T) const {
2727 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2728
Reid Kleckner8a365022013-06-24 17:51:48 +00002729 QualType Decayed;
2730
2731 // C99 6.7.5.3p7:
2732 // A declaration of a parameter as "array of type" shall be
2733 // adjusted to "qualified pointer to type", where the type
2734 // qualifiers (if any) are those specified within the [ and ] of
2735 // the array type derivation.
2736 if (T->isArrayType())
2737 Decayed = getArrayDecayedType(T);
2738
2739 // C99 6.7.5.3p8:
2740 // A declaration of a parameter as "function returning type"
2741 // shall be adjusted to "pointer to function returning type", as
2742 // in 6.3.2.1.
2743 if (T->isFunctionType())
2744 Decayed = getPointerType(T);
2745
Reid Kleckner0503a872013-12-05 01:23:43 +00002746 llvm::FoldingSetNodeID ID;
2747 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002748 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002749 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2750 if (AT)
2751 return QualType(AT, 0);
2752
Reid Kleckner8a365022013-06-24 17:51:48 +00002753 QualType Canonical = getCanonicalType(Decayed);
2754
2755 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002756 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002757 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002758
Reid Kleckner0503a872013-12-05 01:23:43 +00002759 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2760 Types.push_back(AT);
2761 AdjustedTypes.InsertNode(AT, InsertPos);
2762 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002763}
2764
Mike Stump11289f42009-09-09 15:08:12 +00002765/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002766/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002767QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002768 assert(T->isFunctionType() && "block of function types only");
2769 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002770 // structure.
2771 llvm::FoldingSetNodeID ID;
2772 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002773
Craig Topper36250ad2014-05-12 05:36:57 +00002774 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002775 if (BlockPointerType *PT =
2776 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2777 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002778
2779 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002780 // type either so fill in the canonical type field.
2781 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002782 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002783 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002784
Steve Naroffec33ed92008-08-27 16:04:49 +00002785 // Get the new insert position for the node we care about.
2786 BlockPointerType *NewIP =
2787 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002788 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002789 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002790 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002791 Types.push_back(New);
2792 BlockPointerTypes.InsertNode(New, InsertPos);
2793 return QualType(New, 0);
2794}
2795
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002796/// getLValueReferenceType - Return the uniqued reference to the type for an
2797/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002798QualType
2799ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002800 assert(getCanonicalType(T) != OverloadTy &&
2801 "Unresolved overloaded function type");
2802
Bill Wendling3708c182007-05-27 10:15:43 +00002803 // Unique pointers, to guarantee there is only one pointer of a particular
2804 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002805 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002806 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002807
Craig Topper36250ad2014-05-12 05:36:57 +00002808 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002809 if (LValueReferenceType *RT =
2810 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002811 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002812
Eugene Zelenko7855e772018-04-03 00:11:50 +00002813 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00002814
Bill Wendling3708c182007-05-27 10:15:43 +00002815 // If the referencee type isn't canonical, this won't be a canonical type
2816 // either, so fill in the canonical type field.
2817 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002818 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2819 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2820 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002821
Bill Wendling3708c182007-05-27 10:15:43 +00002822 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002823 LValueReferenceType *NewIP =
2824 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002825 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002826 }
2827
Eugene Zelenko7855e772018-04-03 00:11:50 +00002828 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2829 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002830 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002831 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002832
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002833 return QualType(New, 0);
2834}
2835
2836/// getRValueReferenceType - Return the uniqued reference to the type for an
2837/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002838QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002839 // Unique pointers, to guarantee there is only one pointer of a particular
2840 // structure.
2841 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002842 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002843
Craig Topper36250ad2014-05-12 05:36:57 +00002844 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002845 if (RValueReferenceType *RT =
2846 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2847 return QualType(RT, 0);
2848
Eugene Zelenko7855e772018-04-03 00:11:50 +00002849 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00002850
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002851 // If the referencee type isn't canonical, this won't be a canonical type
2852 // either, so fill in the canonical type field.
2853 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002854 if (InnerRef || !T.isCanonical()) {
2855 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2856 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002857
2858 // Get the new insert position for the node we care about.
2859 RValueReferenceType *NewIP =
2860 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002861 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002862 }
2863
Eugene Zelenko7855e772018-04-03 00:11:50 +00002864 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002865 Types.push_back(New);
2866 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002867 return QualType(New, 0);
2868}
2869
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002870/// getMemberPointerType - Return the uniqued reference to the type for a
2871/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002872QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002873 // Unique pointers, to guarantee there is only one pointer of a particular
2874 // structure.
2875 llvm::FoldingSetNodeID ID;
2876 MemberPointerType::Profile(ID, T, Cls);
2877
Craig Topper36250ad2014-05-12 05:36:57 +00002878 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002879 if (MemberPointerType *PT =
2880 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2881 return QualType(PT, 0);
2882
2883 // If the pointee or class type isn't canonical, this won't be a canonical
2884 // type either, so fill in the canonical type field.
2885 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002886 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002887 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2888
2889 // Get the new insert position for the node we care about.
2890 MemberPointerType *NewIP =
2891 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002892 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002893 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002894 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002895 Types.push_back(New);
2896 MemberPointerTypes.InsertNode(New, InsertPos);
2897 return QualType(New, 0);
2898}
2899
Mike Stump11289f42009-09-09 15:08:12 +00002900/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002901/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002902QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002903 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002904 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002905 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002906 assert((EltTy->isDependentType() ||
2907 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002908 "Constant array of VLAs is illegal!");
2909
Chris Lattnere2df3f92009-05-13 04:12:56 +00002910 // Convert the array size into a canonical width matching the pointer size for
2911 // the target.
2912 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00002913 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00002914
Chris Lattner23b7eb62007-06-15 23:05:46 +00002915 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002916 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002917
Craig Topper36250ad2014-05-12 05:36:57 +00002918 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002919 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002920 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002921 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002922
John McCall33ddac02011-01-19 10:06:00 +00002923 // If the element type isn't canonical or has qualifiers, this won't
2924 // be a canonical type either, so fill in the canonical type field.
2925 QualType Canon;
2926 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2927 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002928 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002929 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002930 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002931
Chris Lattner36f8e652007-01-27 08:31:04 +00002932 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002933 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002934 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002935 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002936 }
Mike Stump11289f42009-09-09 15:08:12 +00002937
Eugene Zelenko7855e772018-04-03 00:11:50 +00002938 auto *New = new (*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002939 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002940 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002941 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002942 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002943}
2944
John McCall06549462011-01-18 08:40:38 +00002945/// getVariableArrayDecayedType - Turns the given type, which may be
2946/// variably-modified, into the corresponding type with all the known
2947/// sizes replaced with [*].
2948QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2949 // Vastly most common case.
2950 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002951
John McCall06549462011-01-18 08:40:38 +00002952 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002953
John McCall06549462011-01-18 08:40:38 +00002954 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002955 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002956 switch (ty->getTypeClass()) {
2957#define TYPE(Class, Base)
2958#define ABSTRACT_TYPE(Class, Base)
2959#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2960#include "clang/AST/TypeNodes.def"
2961 llvm_unreachable("didn't desugar past all non-canonical types?");
2962
2963 // These types should never be variably-modified.
2964 case Type::Builtin:
2965 case Type::Complex:
2966 case Type::Vector:
2967 case Type::ExtVector:
2968 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002969 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00002970 case Type::ObjCObject:
2971 case Type::ObjCInterface:
2972 case Type::ObjCObjectPointer:
2973 case Type::Record:
2974 case Type::Enum:
2975 case Type::UnresolvedUsing:
2976 case Type::TypeOfExpr:
2977 case Type::TypeOf:
2978 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002979 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002980 case Type::DependentName:
2981 case Type::InjectedClassName:
2982 case Type::TemplateSpecialization:
2983 case Type::DependentTemplateSpecialization:
2984 case Type::TemplateTypeParm:
2985 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002986 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002987 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00002988 case Type::PackExpansion:
2989 llvm_unreachable("type should never be variably-modified");
2990
2991 // These types can be variably-modified but should never need to
2992 // further decay.
2993 case Type::FunctionNoProto:
2994 case Type::FunctionProto:
2995 case Type::BlockPointer:
2996 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002997 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00002998 return type;
2999
3000 // These types can be variably-modified. All these modifications
3001 // preserve structure except as noted by comments.
3002 // TODO: if we ever care about optimizing VLAs, there are no-op
3003 // optimizations available here.
3004 case Type::Pointer:
3005 result = getPointerType(getVariableArrayDecayedType(
3006 cast<PointerType>(ty)->getPointeeType()));
3007 break;
3008
3009 case Type::LValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003010 const auto *lv = cast<LValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003011 result = getLValueReferenceType(
3012 getVariableArrayDecayedType(lv->getPointeeType()),
3013 lv->isSpelledAsLValue());
3014 break;
3015 }
3016
3017 case Type::RValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003018 const auto *lv = cast<RValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003019 result = getRValueReferenceType(
3020 getVariableArrayDecayedType(lv->getPointeeType()));
3021 break;
3022 }
3023
Eli Friedman0dfb8892011-10-06 23:00:33 +00003024 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003025 const auto *at = cast<AtomicType>(ty);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003026 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3027 break;
3028 }
3029
John McCall06549462011-01-18 08:40:38 +00003030 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003031 const auto *cat = cast<ConstantArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003032 result = getConstantArrayType(
3033 getVariableArrayDecayedType(cat->getElementType()),
3034 cat->getSize(),
3035 cat->getSizeModifier(),
3036 cat->getIndexTypeCVRQualifiers());
3037 break;
3038 }
3039
3040 case Type::DependentSizedArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003041 const auto *dat = cast<DependentSizedArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003042 result = getDependentSizedArrayType(
3043 getVariableArrayDecayedType(dat->getElementType()),
3044 dat->getSizeExpr(),
3045 dat->getSizeModifier(),
3046 dat->getIndexTypeCVRQualifiers(),
3047 dat->getBracketsRange());
3048 break;
3049 }
3050
3051 // Turn incomplete types into [*] types.
3052 case Type::IncompleteArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003053 const auto *iat = cast<IncompleteArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003054 result = getVariableArrayType(
3055 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003056 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003057 ArrayType::Normal,
3058 iat->getIndexTypeCVRQualifiers(),
3059 SourceRange());
3060 break;
3061 }
3062
3063 // Turn VLA types into [*] types.
3064 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003065 const auto *vat = cast<VariableArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003066 result = getVariableArrayType(
3067 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003068 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003069 ArrayType::Star,
3070 vat->getIndexTypeCVRQualifiers(),
3071 vat->getBracketsRange());
3072 break;
3073 }
3074 }
3075
3076 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003077 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003078}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003079
Steve Naroffcadebd02007-08-30 18:14:25 +00003080/// getVariableArrayType - Returns a non-unique reference to the type for a
3081/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003082QualType ASTContext::getVariableArrayType(QualType EltTy,
3083 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003084 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003085 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003086 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003087 // Since we don't unique expressions, it isn't possible to unique VLA's
3088 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003089 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003090
John McCall33ddac02011-01-19 10:06:00 +00003091 // Be sure to pull qualifiers off the element type.
3092 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3093 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003094 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003095 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003096 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003097 }
3098
Eugene Zelenko7855e772018-04-03 00:11:50 +00003099 auto *New = new (*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003100 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003101
3102 VariableArrayTypes.push_back(New);
3103 Types.push_back(New);
3104 return QualType(New, 0);
3105}
3106
Douglas Gregor4619e432008-12-05 23:32:09 +00003107/// getDependentSizedArrayType - Returns a non-unique reference to
3108/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003109/// type.
John McCall33ddac02011-01-19 10:06:00 +00003110QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3111 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003112 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003113 unsigned elementTypeQuals,
3114 SourceRange brackets) const {
3115 assert((!numElements || numElements->isTypeDependent() ||
3116 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003117 "Size must be type- or value-dependent!");
3118
John McCall33ddac02011-01-19 10:06:00 +00003119 // Dependently-sized array types that do not have a specified number
3120 // of elements will have their sizes deduced from a dependent
3121 // initializer. We do no canonicalization here at all, which is okay
3122 // because they can't be used in most locations.
3123 if (!numElements) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003124 auto *newType
John McCall33ddac02011-01-19 10:06:00 +00003125 = new (*this, TypeAlignment)
3126 DependentSizedArrayType(*this, elementType, QualType(),
3127 numElements, ASM, elementTypeQuals,
3128 brackets);
3129 Types.push_back(newType);
3130 return QualType(newType, 0);
3131 }
3132
3133 // Otherwise, we actually build a new type every time, but we
3134 // also build a canonical type.
3135
3136 SplitQualType canonElementType = getCanonicalType(elementType).split();
3137
Craig Topper36250ad2014-05-12 05:36:57 +00003138 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003139 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003140 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003141 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003142 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003143
John McCall33ddac02011-01-19 10:06:00 +00003144 // Look for an existing type with these properties.
3145 DependentSizedArrayType *canonTy =
3146 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003147
John McCall33ddac02011-01-19 10:06:00 +00003148 // If we don't have one, build one.
3149 if (!canonTy) {
3150 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003151 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003152 QualType(), numElements, ASM, elementTypeQuals,
3153 brackets);
3154 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3155 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003156 }
3157
John McCall33ddac02011-01-19 10:06:00 +00003158 // Apply qualifiers from the element type to the array.
3159 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003160 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003161
David Majnemer16a74702015-07-24 05:54:19 +00003162 // If we didn't need extra canonicalization for the element type or the size
3163 // expression, then just use that as our result.
3164 if (QualType(canonElementType.Ty, 0) == elementType &&
3165 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003166 return canon;
3167
3168 // Otherwise, we need to build a type which follows the spelling
3169 // of the element type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00003170 auto *sugaredType
John McCall33ddac02011-01-19 10:06:00 +00003171 = new (*this, TypeAlignment)
3172 DependentSizedArrayType(*this, elementType, canon, numElements,
3173 ASM, elementTypeQuals, brackets);
3174 Types.push_back(sugaredType);
3175 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003176}
3177
John McCall33ddac02011-01-19 10:06:00 +00003178QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003179 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003180 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003181 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003182 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003183
Craig Topper36250ad2014-05-12 05:36:57 +00003184 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003185 if (IncompleteArrayType *iat =
3186 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3187 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003188
3189 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003190 // either, so fill in the canonical type field. We also have to pull
3191 // qualifiers off the element type.
3192 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003193
John McCall33ddac02011-01-19 10:06:00 +00003194 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3195 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003196 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003197 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003198 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003199
3200 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003201 IncompleteArrayType *existing =
3202 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3203 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003204 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003205
Eugene Zelenko7855e772018-04-03 00:11:50 +00003206 auto *newType = new (*this, TypeAlignment)
John McCall33ddac02011-01-19 10:06:00 +00003207 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003208
John McCall33ddac02011-01-19 10:06:00 +00003209 IncompleteArrayTypes.InsertNode(newType, insertPos);
3210 Types.push_back(newType);
3211 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003212}
3213
Steve Naroff91fcddb2007-07-18 18:00:27 +00003214/// getVectorType - Return the unique reference to a vector type of
3215/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003216QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003217 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003218 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003219
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003220 // Check if we've already instantiated a vector of this type.
3221 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003222 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003223
Craig Topper36250ad2014-05-12 05:36:57 +00003224 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003225 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3226 return QualType(VTP, 0);
3227
3228 // If the element type isn't canonical, this won't be a canonical type either,
3229 // so fill in the canonical type field.
3230 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003231 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003232 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003233
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003234 // Get the new insert position for the node we care about.
3235 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003236 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003237 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003238 auto *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003239 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003240 VectorTypes.InsertNode(New, InsertPos);
3241 Types.push_back(New);
3242 return QualType(New, 0);
3243}
3244
Nate Begemance4d7fc2008-04-18 23:10:10 +00003245/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003246/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003247QualType
3248ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003249 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003250
Steve Naroff91fcddb2007-07-18 18:00:27 +00003251 // Check if we've already instantiated a vector of this type.
3252 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003253 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003254 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003255 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003256 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3257 return QualType(VTP, 0);
3258
3259 // If the element type isn't canonical, this won't be a canonical type either,
3260 // so fill in the canonical type field.
3261 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003262 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003263 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003264
Steve Naroff91fcddb2007-07-18 18:00:27 +00003265 // Get the new insert position for the node we care about.
3266 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003267 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003268 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003269 auto *New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003270 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003271 VectorTypes.InsertNode(New, InsertPos);
3272 Types.push_back(New);
3273 return QualType(New, 0);
3274}
3275
Jay Foad39c79802011-01-12 09:06:06 +00003276QualType
3277ASTContext::getDependentSizedExtVectorType(QualType vecType,
3278 Expr *SizeExpr,
3279 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003280 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003281 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003282 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003283
Craig Topper36250ad2014-05-12 05:36:57 +00003284 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003285 DependentSizedExtVectorType *Canon
3286 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3287 DependentSizedExtVectorType *New;
3288 if (Canon) {
3289 // We already have a canonical version of this array type; use it as
3290 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003291 New = new (*this, TypeAlignment)
3292 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3293 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003294 } else {
3295 QualType CanonVecTy = getCanonicalType(vecType);
3296 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003297 New = new (*this, TypeAlignment)
3298 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3299 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003300
3301 DependentSizedExtVectorType *CanonCheck
3302 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3303 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3304 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003305 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3306 } else {
3307 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3308 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00003309 New = new (*this, TypeAlignment)
3310 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003311 }
3312 }
Mike Stump11289f42009-09-09 15:08:12 +00003313
Douglas Gregor758a8692009-06-17 21:51:59 +00003314 Types.push_back(New);
3315 return QualType(New, 0);
3316}
3317
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003318QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3319 Expr *AddrSpaceExpr,
3320 SourceLocation AttrLoc) const {
3321 assert(AddrSpaceExpr->isInstantiationDependent());
3322
3323 QualType canonPointeeType = getCanonicalType(PointeeType);
3324
3325 void *insertPos = nullptr;
3326 llvm::FoldingSetNodeID ID;
3327 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3328 AddrSpaceExpr);
3329
3330 DependentAddressSpaceType *canonTy =
3331 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3332
3333 if (!canonTy) {
3334 canonTy = new (*this, TypeAlignment)
3335 DependentAddressSpaceType(*this, canonPointeeType,
3336 QualType(), AddrSpaceExpr, AttrLoc);
3337 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3338 Types.push_back(canonTy);
3339 }
3340
3341 if (canonPointeeType == PointeeType &&
3342 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
3343 return QualType(canonTy, 0);
3344
Eugene Zelenko7855e772018-04-03 00:11:50 +00003345 auto *sugaredType
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003346 = new (*this, TypeAlignment)
3347 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
3348 AddrSpaceExpr, AttrLoc);
3349 Types.push_back(sugaredType);
3350 return QualType(sugaredType, 0);
3351}
3352
John McCall18afab72016-03-01 00:49:02 +00003353/// \brief Determine whether \p T is canonical as the result type of a function.
3354static bool isCanonicalResultType(QualType T) {
3355 return T.isCanonical() &&
3356 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3357 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3358}
3359
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003360/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003361QualType
3362ASTContext::getFunctionNoProtoType(QualType ResultTy,
3363 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003364 // Unique functions, to guarantee there is only one function of a particular
3365 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003366 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003367 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003368
Craig Topper36250ad2014-05-12 05:36:57 +00003369 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003370 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003371 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003372 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003373
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003374 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003375 if (!isCanonicalResultType(ResultTy)) {
3376 Canonical =
3377 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003378
Chris Lattner47955de2007-01-27 08:37:20 +00003379 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003380 FunctionNoProtoType *NewIP =
3381 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003382 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003383 }
Mike Stump11289f42009-09-09 15:08:12 +00003384
Eugene Zelenko7855e772018-04-03 00:11:50 +00003385 auto *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003386 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003387 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003388 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003389 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003390}
3391
Douglas Gregora602a152015-10-01 20:20:47 +00003392CanQualType
3393ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3394 CanQualType CanResultType = getCanonicalType(ResultType);
3395
3396 // Canonical result types do not have ARC lifetime qualifiers.
3397 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3398 Qualifiers Qs = CanResultType.getQualifiers();
3399 Qs.removeObjCLifetime();
3400 return CanQualType::CreateUnsafe(
3401 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3402 }
3403
3404 return CanResultType;
3405}
3406
Richard Smith3c4f8d22016-10-16 17:54:23 +00003407static bool isCanonicalExceptionSpecification(
3408 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3409 if (ESI.Type == EST_None)
3410 return true;
3411 if (!NoexceptInType)
3412 return false;
3413
3414 // C++17 onwards: exception specification is part of the type, as a simple
3415 // boolean "can this function type throw".
3416 if (ESI.Type == EST_BasicNoexcept)
3417 return true;
3418
3419 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003420 // expansions (so we can't tell whether it's non-throwing) and all its
3421 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003422 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003423 bool AnyPackExpansions = false;
3424 for (QualType ET : ESI.Exceptions) {
3425 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003426 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003427 if (ET->getAs<PackExpansionType>())
3428 AnyPackExpansions = true;
3429 }
3430 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003431 }
3432
Richard Smith2a2cda52016-10-18 19:29:18 +00003433 // A noexcept(expr) specification is (possibly) canonical if expr is
3434 // value-dependent.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003435 if (ESI.Type == EST_ComputedNoexcept)
3436 return ESI.NoexceptExpr && ESI.NoexceptExpr->isValueDependent();
3437
3438 return false;
3439}
3440
Richard Smith304b1242016-10-18 20:13:25 +00003441QualType ASTContext::getFunctionTypeInternal(
3442 QualType ResultTy, ArrayRef<QualType> ArgArray,
3443 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003444 size_t NumArgs = ArgArray.size();
3445
Richard Smith2a2cda52016-10-18 19:29:18 +00003446 // Unique functions, to guarantee there is only one function of a particular
3447 // structure.
3448 llvm::FoldingSetNodeID ID;
3449 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3450 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003451
Richard Smith2a2cda52016-10-18 19:29:18 +00003452 QualType Canonical;
3453 bool Unique = false;
3454
3455 void *InsertPos = nullptr;
3456 if (FunctionProtoType *FPT =
3457 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3458 QualType Existing = QualType(FPT, 0);
3459
3460 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3461 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003462 // noexcept expression, or we're just looking for a canonical type.
3463 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003464 // sugar node to hold the concrete expression.
Richard Smith304b1242016-10-18 20:13:25 +00003465 if (OnlyWantCanonical || EPI.ExceptionSpec.Type != EST_ComputedNoexcept ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003466 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3467 return Existing;
3468
3469 // We need a new type sugar node for this one, to hold the new noexcept
3470 // expression. We do no canonicalization here, but that's OK since we don't
3471 // expect to see the same noexcept expression much more than once.
3472 Canonical = getCanonicalType(Existing);
3473 Unique = true;
3474 }
3475
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003476 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003477 bool IsCanonicalExceptionSpec =
3478 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3479
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003480 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003481 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003482 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003483 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003484 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003485 isCanonical = false;
3486
Richard Smith304b1242016-10-18 20:13:25 +00003487 if (OnlyWantCanonical)
3488 assert(isCanonical &&
3489 "given non-canonical parameters constructing canonical type");
3490
Richard Smith2a2cda52016-10-18 19:29:18 +00003491 // If this type isn't canonical, get the canonical version of it if we don't
3492 // already have it. The exception spec is only partially part of the
3493 // canonical type, and only in C++17 onwards.
3494 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003495 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003496 CanonicalArgs.reserve(NumArgs);
3497 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003498 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003499
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003500 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003501 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003502 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003503
3504 if (IsCanonicalExceptionSpec) {
3505 // Exception spec is already OK.
3506 } else if (NoexceptInType) {
3507 switch (EPI.ExceptionSpec.Type) {
3508 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3509 // We don't know yet. It shouldn't matter what we pick here; no-one
3510 // should ever look at this.
3511 LLVM_FALLTHROUGH;
Richard Smith2a2cda52016-10-18 19:29:18 +00003512 case EST_None: case EST_MSAny:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003513 CanonicalEPI.ExceptionSpec.Type = EST_None;
3514 break;
3515
Richard Smith2a2cda52016-10-18 19:29:18 +00003516 // A dynamic exception specification is almost always "not noexcept",
3517 // with the exception that a pack expansion might expand to no types.
3518 case EST_Dynamic: {
3519 bool AnyPacks = false;
3520 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3521 if (ET->getAs<PackExpansionType>())
3522 AnyPacks = true;
3523 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3524 }
3525 if (!AnyPacks)
3526 CanonicalEPI.ExceptionSpec.Type = EST_None;
3527 else {
3528 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3529 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3530 }
3531 break;
3532 }
3533
Richard Smith3c4f8d22016-10-16 17:54:23 +00003534 case EST_DynamicNone: case EST_BasicNoexcept:
3535 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3536 break;
3537
3538 case EST_ComputedNoexcept:
3539 llvm::APSInt Value(1);
3540 auto *E = CanonicalEPI.ExceptionSpec.NoexceptExpr;
3541 if (!E || !E->isIntegerConstantExpr(Value, *this, nullptr,
3542 /*IsEvaluated*/false)) {
3543 // This noexcept specification is invalid.
3544 // FIXME: Should this be able to happen?
3545 CanonicalEPI.ExceptionSpec.Type = EST_None;
3546 break;
3547 }
3548
3549 CanonicalEPI.ExceptionSpec.Type =
3550 Value.getBoolValue() ? EST_BasicNoexcept : EST_None;
3551 break;
3552 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003553 } else {
3554 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3555 }
John McCalldb40c7f2010-12-14 08:05:40 +00003556
Douglas Gregora602a152015-10-01 20:20:47 +00003557 // Adjust the canonical function result type.
3558 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003559 Canonical =
3560 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003561
Chris Lattnerfd4de792007-01-27 01:15:32 +00003562 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003563 FunctionProtoType *NewIP =
3564 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003565 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003566 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003567
John McCall31168b02011-06-15 23:02:42 +00003568 // FunctionProtoType objects are allocated with extra bytes after
3569 // them for three variable size arrays at the end:
3570 // - parameter types
3571 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003572 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003573 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003574 // expression, or information used to resolve the exception
3575 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003576 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003577 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003578
Richard Smith8acb4282014-07-31 21:57:55 +00003579 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3580 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3581 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003582 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003583 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003584 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003585 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003586 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003587 }
John McCall18afab72016-03-01 00:49:02 +00003588
3589 // Put the ExtParameterInfos last. If all were equal, it would make
3590 // more sense to put these before the exception specification, because
3591 // it's much easier to skip past them compared to the elaborate switch
3592 // required to skip the exception specification. However, all is not
3593 // equal; ExtParameterInfos are used to model very uncommon features,
3594 // and it's better not to burden the more common paths.
3595 if (EPI.ExtParameterInfos) {
3596 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3597 }
John McCall31168b02011-06-15 23:02:42 +00003598
Eugene Zelenko7855e772018-04-03 00:11:50 +00003599 auto *FTP = (FunctionProtoType *) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003600 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003601 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003602 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003603 if (!Unique)
3604 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003605 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003606}
Chris Lattneref51c202006-11-10 07:17:23 +00003607
Joey Goulye3c85de2016-12-01 11:30:49 +00003608QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003609 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003610 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003611
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00003612 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00003613 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003614 return QualType(PT, 0);
3615
3616 // If the pipe element type isn't canonical, this won't be a canonical type
3617 // either, so fill in the canonical type field.
3618 QualType Canonical;
3619 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003620 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003621
3622 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003623 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003624 assert(!NewIP && "Shouldn't be in the map!");
3625 (void)NewIP;
3626 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003627 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003628 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003629 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003630 return QualType(New, 0);
3631}
3632
Joey Goulye3c85de2016-12-01 11:30:49 +00003633QualType ASTContext::getReadPipeType(QualType T) const {
3634 return getPipeType(T, true);
3635}
3636
Joey Gouly5788b782016-11-18 14:10:54 +00003637QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003638 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003639}
3640
John McCalle78aac42010-03-10 03:28:59 +00003641#ifndef NDEBUG
3642static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3643 if (!isa<CXXRecordDecl>(D)) return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00003644 const auto *RD = cast<CXXRecordDecl>(D);
John McCalle78aac42010-03-10 03:28:59 +00003645 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3646 return true;
3647 if (RD->getDescribedClassTemplate() &&
3648 !isa<ClassTemplateSpecializationDecl>(RD))
3649 return true;
3650 return false;
3651}
3652#endif
3653
3654/// getInjectedClassNameType - Return the unique reference to the
3655/// injected class name type for the specified templated declaration.
3656QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003657 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003658 assert(NeedsInjectedClassNameType(Decl));
3659 if (Decl->TypeForDecl) {
3660 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003661 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003662 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3663 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3664 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3665 } else {
John McCall424cec92011-01-19 06:33:43 +00003666 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003667 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003668 Decl->TypeForDecl = newType;
3669 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003670 }
3671 return QualType(Decl->TypeForDecl, 0);
3672}
3673
Douglas Gregor83a586e2008-04-13 21:07:44 +00003674/// getTypeDeclType - Return the unique reference to the type for the
3675/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003676QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003677 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003678 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003679
Eugene Zelenko7855e772018-04-03 00:11:50 +00003680 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003681 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003682
John McCall96f0b5f2010-03-10 06:48:02 +00003683 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3684 "Template type parameter types are always available.");
3685
Eugene Zelenko7855e772018-04-03 00:11:50 +00003686 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003687 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003688 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003689 return getRecordType(Record);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003690 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003691 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003692 return getEnumType(Enum);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003693 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003694 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3695 Decl->TypeForDecl = newType;
3696 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003697 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003698 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003699
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003700 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003701}
3702
Chris Lattner32d920b2007-01-26 02:01:53 +00003703/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003704/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003705QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003706ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3707 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003708 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003709
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003710 if (Canonical.isNull())
3711 Canonical = getCanonicalType(Decl->getUnderlyingType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00003712 auto *newType = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003713 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003714 Decl->TypeForDecl = newType;
3715 Types.push_back(newType);
3716 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003717}
3718
Jay Foad39c79802011-01-12 09:06:06 +00003719QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003720 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3721
Douglas Gregorec9fd132012-01-14 16:38:05 +00003722 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003723 if (PrevDecl->TypeForDecl)
3724 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3725
Eugene Zelenko7855e772018-04-03 00:11:50 +00003726 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003727 Decl->TypeForDecl = newType;
3728 Types.push_back(newType);
3729 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003730}
3731
Jay Foad39c79802011-01-12 09:06:06 +00003732QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003733 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3734
Douglas Gregorec9fd132012-01-14 16:38:05 +00003735 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003736 if (PrevDecl->TypeForDecl)
3737 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3738
Eugene Zelenko7855e772018-04-03 00:11:50 +00003739 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003740 Decl->TypeForDecl = newType;
3741 Types.push_back(newType);
3742 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003743}
3744
John McCall81904512011-01-06 01:58:22 +00003745QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3746 QualType modifiedType,
3747 QualType equivalentType) {
3748 llvm::FoldingSetNodeID id;
3749 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3750
Craig Topper36250ad2014-05-12 05:36:57 +00003751 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003752 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3753 if (type) return QualType(type, 0);
3754
3755 QualType canon = getCanonicalType(equivalentType);
3756 type = new (*this, TypeAlignment)
3757 AttributedType(canon, attrKind, modifiedType, equivalentType);
3758
3759 Types.push_back(type);
3760 AttributedTypes.InsertNode(type, insertPos);
3761
3762 return QualType(type, 0);
3763}
3764
John McCallcebee162009-10-18 09:09:24 +00003765/// \brief Retrieve a substitution-result type.
3766QualType
3767ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003768 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003769 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003770 && "replacement types must always be canonical");
3771
3772 llvm::FoldingSetNodeID ID;
3773 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003774 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003775 SubstTemplateTypeParmType *SubstParm
3776 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3777
3778 if (!SubstParm) {
3779 SubstParm = new (*this, TypeAlignment)
3780 SubstTemplateTypeParmType(Parm, Replacement);
3781 Types.push_back(SubstParm);
3782 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3783 }
3784
3785 return QualType(SubstParm, 0);
3786}
3787
Douglas Gregorada4b792011-01-14 02:55:32 +00003788/// \brief Retrieve a
3789QualType ASTContext::getSubstTemplateTypeParmPackType(
3790 const TemplateTypeParmType *Parm,
3791 const TemplateArgument &ArgPack) {
3792#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003793 for (const auto &P : ArgPack.pack_elements()) {
3794 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3795 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003796 }
3797#endif
3798
3799 llvm::FoldingSetNodeID ID;
3800 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003801 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003802 if (SubstTemplateTypeParmPackType *SubstParm
3803 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3804 return QualType(SubstParm, 0);
3805
3806 QualType Canon;
3807 if (!Parm->isCanonicalUnqualified()) {
3808 Canon = getCanonicalType(QualType(Parm, 0));
3809 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3810 ArgPack);
3811 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3812 }
3813
Eugene Zelenko7855e772018-04-03 00:11:50 +00003814 auto *SubstParm
Douglas Gregorada4b792011-01-14 02:55:32 +00003815 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3816 ArgPack);
3817 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00003818 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Douglas Gregorada4b792011-01-14 02:55:32 +00003819 return QualType(SubstParm, 0);
3820}
3821
Douglas Gregoreff93e02009-02-05 23:33:38 +00003822/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003823/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003824/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003825QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003826 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003827 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003828 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003829 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003830 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003831 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003832 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3833
3834 if (TypeParm)
3835 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003836
Chandler Carruth08836322011-05-01 00:51:33 +00003837 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003838 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003839 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003840
3841 TemplateTypeParmType *TypeCheck
3842 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3843 assert(!TypeCheck && "Template type parameter canonical type broken");
3844 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003845 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003846 TypeParm = new (*this, TypeAlignment)
3847 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003848
3849 Types.push_back(TypeParm);
3850 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3851
3852 return QualType(TypeParm, 0);
3853}
3854
John McCalle78aac42010-03-10 03:28:59 +00003855TypeSourceInfo *
3856ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3857 SourceLocation NameLoc,
3858 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003859 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003860 assert(!Name.getAsDependentTemplateName() &&
3861 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003862 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003863
3864 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003865 TemplateSpecializationTypeLoc TL =
3866 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003867 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003868 TL.setTemplateNameLoc(NameLoc);
3869 TL.setLAngleLoc(Args.getLAngleLoc());
3870 TL.setRAngleLoc(Args.getRAngleLoc());
3871 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3872 TL.setArgLocInfo(i, Args[i].getLocInfo());
3873 return DI;
3874}
3875
Mike Stump11289f42009-09-09 15:08:12 +00003876QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003877ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003878 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003879 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003880 assert(!Template.getAsDependentTemplateName() &&
3881 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00003882
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003883 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00003884 ArgVec.reserve(Args.size());
3885 for (const TemplateArgumentLoc &Arg : Args.arguments())
3886 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00003887
David Majnemer6fbeee32016-07-07 04:43:07 +00003888 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003889}
3890
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003891#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00003892static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3893 for (const TemplateArgument &Arg : Args)
3894 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003895 return true;
3896
3897 return true;
3898}
3899#endif
3900
John McCall0ad16662009-10-29 08:12:44 +00003901QualType
3902ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00003903 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003904 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003905 assert(!Template.getAsDependentTemplateName() &&
3906 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003907 // Look through qualified template names.
3908 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3909 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003910
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003911 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003912 Template.getAsTemplateDecl() &&
3913 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003914 QualType CanonType;
3915 if (!Underlying.isNull())
3916 CanonType = getCanonicalType(Underlying);
3917 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003918 // We can get here with an alias template when the specialization contains
3919 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00003920 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003921 "Caller must compute aliased type");
3922 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003923 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003924 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003925
Douglas Gregora8e02e72009-07-28 23:00:59 +00003926 // Allocate the (non-canonical) template specialization type, but don't
3927 // try to unique it: these types typically have location information that
3928 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003929 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00003930 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003931 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003932 TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003933 auto *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00003934 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003935 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003936
Douglas Gregor8bf42052009-02-09 18:46:07 +00003937 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003938 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003939}
3940
David Majnemer6fbeee32016-07-07 04:43:07 +00003941QualType ASTContext::getCanonicalTemplateSpecializationType(
3942 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003943 assert(!Template.getAsDependentTemplateName() &&
3944 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003945
Douglas Gregore29139c2011-03-03 17:04:51 +00003946 // Look through qualified template names.
3947 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3948 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003949
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003950 // Build the canonical template specialization type.
3951 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003952 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00003953 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003954 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00003955 for (const TemplateArgument &Arg : Args)
3956 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003957
3958 // Determine whether this canonical template specialization type already
3959 // exists.
3960 llvm::FoldingSetNodeID ID;
3961 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003962 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003963
Craig Topper36250ad2014-05-12 05:36:57 +00003964 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003965 TemplateSpecializationType *Spec
3966 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3967
3968 if (!Spec) {
3969 // Allocate a new canonical template specialization type.
3970 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3971 sizeof(TemplateArgument) * NumArgs),
3972 TypeAlignment);
3973 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003974 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003975 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003976 Types.push_back(Spec);
3977 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3978 }
3979
3980 assert(Spec->isDependentType() &&
3981 "Non-dependent template-id type must have a canonical type");
3982 return QualType(Spec, 0);
3983}
3984
3985QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003986ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3987 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003988 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003989 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003990 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003991
Craig Topper36250ad2014-05-12 05:36:57 +00003992 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003993 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003994 if (T)
3995 return QualType(T, 0);
3996
Douglas Gregorc42075a2010-02-04 18:10:26 +00003997 QualType Canon = NamedType;
3998 if (!Canon.isCanonical()) {
3999 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004000 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4001 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004002 (void)CheckT;
4003 }
4004
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004005 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00004006 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004007 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004008 return QualType(T, 0);
4009}
4010
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004011QualType
Jay Foad39c79802011-01-12 09:06:06 +00004012ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004013 llvm::FoldingSetNodeID ID;
4014 ParenType::Profile(ID, InnerType);
4015
Craig Topper36250ad2014-05-12 05:36:57 +00004016 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004017 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4018 if (T)
4019 return QualType(T, 0);
4020
4021 QualType Canon = InnerType;
4022 if (!Canon.isCanonical()) {
4023 Canon = getCanonicalType(InnerType);
4024 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4025 assert(!CheckT && "Paren canonical type broken");
4026 (void)CheckT;
4027 }
4028
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004029 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004030 Types.push_back(T);
4031 ParenTypes.InsertNode(T, InsertPos);
4032 return QualType(T, 0);
4033}
4034
Douglas Gregor02085352010-03-31 20:19:30 +00004035QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4036 NestedNameSpecifier *NNS,
4037 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004038 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004039 if (Canon.isNull()) {
4040 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004041 if (CanonNNS != NNS)
4042 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004043 }
4044
4045 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004046 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004047
Craig Topper36250ad2014-05-12 05:36:57 +00004048 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004049 DependentNameType *T
4050 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004051 if (T)
4052 return QualType(T, 0);
4053
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004054 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004055 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004056 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004057 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004058}
4059
Mike Stump11289f42009-09-09 15:08:12 +00004060QualType
John McCallc392f372010-06-11 00:33:02 +00004061ASTContext::getDependentTemplateSpecializationType(
4062 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004063 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004064 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004065 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004066 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004067 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004068 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4069 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004070 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004071}
4072
4073QualType
4074ASTContext::getDependentTemplateSpecializationType(
4075 ElaboratedTypeKeyword Keyword,
4076 NestedNameSpecifier *NNS,
4077 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004078 ArrayRef<TemplateArgument> Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00004079 assert((!NNS || NNS->isDependent()) &&
4080 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004081
Douglas Gregorc42075a2010-02-04 18:10:26 +00004082 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004083 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004084 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004085
Craig Topper36250ad2014-05-12 05:36:57 +00004086 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004087 DependentTemplateSpecializationType *T
4088 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004089 if (T)
4090 return QualType(T, 0);
4091
John McCallc392f372010-06-11 00:33:02 +00004092 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004093
John McCallc392f372010-06-11 00:33:02 +00004094 ElaboratedTypeKeyword CanonKeyword = Keyword;
4095 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4096
4097 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004098 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004099 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004100 for (unsigned I = 0; I != NumArgs; ++I) {
4101 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4102 if (!CanonArgs[I].structurallyEquals(Args[I]))
4103 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004104 }
4105
John McCallc392f372010-06-11 00:33:02 +00004106 QualType Canon;
4107 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4108 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004109 Name,
4110 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004111
4112 // Find the insert position again.
4113 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4114 }
4115
4116 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4117 sizeof(TemplateArgument) * NumArgs),
4118 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004119 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004120 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004121 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004122 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004123 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004124}
4125
Richard Smith32918772017-02-14 00:25:28 +00004126TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4127 TemplateArgument Arg;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004128 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith32918772017-02-14 00:25:28 +00004129 QualType ArgType = getTypeDeclType(TTP);
4130 if (TTP->isParameterPack())
4131 ArgType = getPackExpansionType(ArgType, None);
4132
4133 Arg = TemplateArgument(ArgType);
4134 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4135 Expr *E = new (*this) DeclRefExpr(
4136 NTTP, /*enclosing*/false,
4137 NTTP->getType().getNonLValueExprType(*this),
4138 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4139
4140 if (NTTP->isParameterPack())
4141 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4142 None);
4143 Arg = TemplateArgument(E);
4144 } else {
4145 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4146 if (TTP->isParameterPack())
4147 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4148 else
4149 Arg = TemplateArgument(TemplateName(TTP));
4150 }
4151
4152 if (Param->isTemplateParameterPack())
4153 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4154
4155 return Arg;
4156}
4157
Richard Smith43e14d22016-12-23 02:10:11 +00004158void
4159ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4160 SmallVectorImpl<TemplateArgument> &Args) {
4161 Args.reserve(Args.size() + Params->size());
4162
Richard Smith32918772017-02-14 00:25:28 +00004163 for (NamedDecl *Param : *Params)
4164 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004165}
4166
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004167QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004168 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004169 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004170 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004171
4172 assert(Pattern->containsUnexpandedParameterPack() &&
4173 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004174 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004175 PackExpansionType *T
4176 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4177 if (T)
4178 return QualType(T, 0);
4179
4180 QualType Canon;
4181 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004182 Canon = getCanonicalType(Pattern);
4183 // The canonical type might not contain an unexpanded parameter pack, if it
4184 // contains an alias template specialization which ignores one of its
4185 // parameters.
4186 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004187 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004188
Richard Smith68eea502012-07-16 00:20:35 +00004189 // Find the insert position again, in case we inserted an element into
4190 // PackExpansionTypes and invalidated our insert position.
4191 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4192 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004193 }
4194
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004195 T = new (*this, TypeAlignment)
4196 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004197 Types.push_back(T);
4198 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004199 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004200}
4201
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004202/// CmpProtocolNames - Comparison predicate for sorting protocols
4203/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004204static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4205 ObjCProtocolDecl *const *RHS) {
4206 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004207}
4208
Craig Topper1f26d5b2016-01-03 19:43:23 +00004209static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4210 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004211
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004212 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4213 return false;
4214
Craig Topper1f26d5b2016-01-03 19:43:23 +00004215 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004216 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004217 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004218 return false;
4219 return true;
4220}
4221
Craig Topper6a8c1512015-10-22 01:56:18 +00004222static void
4223SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004224 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004225 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004226
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004227 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004228 for (ObjCProtocolDecl *&P : Protocols)
4229 P = P->getCanonicalDecl();
4230
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004231 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004232 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4233 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004234}
4235
John McCall8b07ec22010-05-15 11:32:37 +00004236QualType ASTContext::getObjCObjectType(QualType BaseType,
4237 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004238 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004239 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004240 llvm::makeArrayRef(Protocols, NumProtocols),
4241 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004242}
4243
4244QualType ASTContext::getObjCObjectType(
4245 QualType baseType,
4246 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004247 ArrayRef<ObjCProtocolDecl *> protocols,
4248 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004249 // If the base type is an interface and there aren't any protocols or
4250 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004251 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4252 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004253 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004254
4255 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004256 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004257 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004258 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004259 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4260 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004261
Douglas Gregore9d95f12015-07-07 03:57:35 +00004262 // Determine the type arguments to be used for canonicalization,
4263 // which may be explicitly specified here or written on the base
4264 // type.
4265 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4266 if (effectiveTypeArgs.empty()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004267 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
Douglas Gregore9d95f12015-07-07 03:57:35 +00004268 effectiveTypeArgs = baseObject->getTypeArgs();
4269 }
John McCallfc93cf92009-10-22 22:37:11 +00004270
Douglas Gregore9d95f12015-07-07 03:57:35 +00004271 // Build the canonical type, which has the canonical base type and a
4272 // sorted-and-uniqued list of protocols and the type arguments
4273 // canonicalized.
4274 QualType canonical;
4275 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4276 effectiveTypeArgs.end(),
4277 [&](QualType type) {
4278 return type.isCanonical();
4279 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004280 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004281 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4282 // Determine the canonical type arguments.
4283 ArrayRef<QualType> canonTypeArgs;
4284 SmallVector<QualType, 4> canonTypeArgsVec;
4285 if (!typeArgsAreCanonical) {
4286 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4287 for (auto typeArg : effectiveTypeArgs)
4288 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4289 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004290 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004291 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004292 }
4293
Douglas Gregore9d95f12015-07-07 03:57:35 +00004294 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4295 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4296 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004297 canonProtocolsVec.append(protocols.begin(), protocols.end());
4298 SortAndUniqueProtocols(canonProtocolsVec);
4299 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004300 } else {
4301 canonProtocols = protocols;
4302 }
4303
4304 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004305 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004306
John McCallfc93cf92009-10-22 22:37:11 +00004307 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004308 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4309 }
4310
Douglas Gregore9d95f12015-07-07 03:57:35 +00004311 unsigned size = sizeof(ObjCObjectTypeImpl);
4312 size += typeArgs.size() * sizeof(QualType);
4313 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4314 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004315 auto *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004316 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4317 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004318
4319 Types.push_back(T);
4320 ObjCObjectTypes.InsertNode(T, InsertPos);
4321 return QualType(T, 0);
4322}
4323
Manman Ren3569eb52016-09-13 17:03:12 +00004324/// Apply Objective-C protocol qualifiers to the given type.
4325/// If this is for the canonical type of a type parameter, we can apply
4326/// protocol qualifiers on the ObjCObjectPointerType.
4327QualType
4328ASTContext::applyObjCProtocolQualifiers(QualType type,
4329 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4330 bool allowOnPointerType) const {
4331 hasError = false;
4332
Eugene Zelenko7855e772018-04-03 00:11:50 +00004333 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
Manman Renc5705ba2016-09-13 17:41:05 +00004334 return getObjCTypeParamType(objT->getDecl(), protocols);
4335 }
4336
Manman Ren3569eb52016-09-13 17:03:12 +00004337 // Apply protocol qualifiers to ObjCObjectPointerType.
4338 if (allowOnPointerType) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004339 if (const auto *objPtr =
4340 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
Manman Ren3569eb52016-09-13 17:03:12 +00004341 const ObjCObjectType *objT = objPtr->getObjectType();
4342 // Merge protocol lists and construct ObjCObjectType.
4343 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4344 protocolsVec.append(objT->qual_begin(),
4345 objT->qual_end());
4346 protocolsVec.append(protocols.begin(), protocols.end());
4347 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4348 type = getObjCObjectType(
4349 objT->getBaseType(),
4350 objT->getTypeArgsAsWritten(),
4351 protocols,
4352 objT->isKindOfTypeAsWritten());
4353 return getObjCObjectPointerType(type);
4354 }
4355 }
4356
4357 // Apply protocol qualifiers to ObjCObjectType.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004358 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
Manman Ren3569eb52016-09-13 17:03:12 +00004359 // FIXME: Check for protocols to which the class type is already
4360 // known to conform.
4361
4362 return getObjCObjectType(objT->getBaseType(),
4363 objT->getTypeArgsAsWritten(),
4364 protocols,
4365 objT->isKindOfTypeAsWritten());
4366 }
4367
4368 // If the canonical type is ObjCObjectType, ...
4369 if (type->isObjCObjectType()) {
4370 // Silently overwrite any existing protocol qualifiers.
4371 // TODO: determine whether that's the right thing to do.
4372
4373 // FIXME: Check for protocols to which the class type is already
4374 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004375 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004376 }
4377
4378 // id<protocol-list>
4379 if (type->isObjCIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004380 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004381 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004382 objPtr->isKindOfType());
4383 return getObjCObjectPointerType(type);
4384 }
4385
4386 // Class<protocol-list>
4387 if (type->isObjCClassType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004388 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004389 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004390 objPtr->isKindOfType());
4391 return getObjCObjectPointerType(type);
4392 }
4393
4394 hasError = true;
4395 return type;
4396}
4397
Manman Rene6be26c2016-09-13 17:25:08 +00004398QualType
4399ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4400 ArrayRef<ObjCProtocolDecl *> protocols,
4401 QualType Canonical) const {
4402 // Look in the folding set for an existing type.
4403 llvm::FoldingSetNodeID ID;
4404 ObjCTypeParamType::Profile(ID, Decl, protocols);
4405 void *InsertPos = nullptr;
4406 if (ObjCTypeParamType *TypeParam =
4407 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4408 return QualType(TypeParam, 0);
4409
4410 if (Canonical.isNull()) {
4411 // We canonicalize to the underlying type.
4412 Canonical = getCanonicalType(Decl->getUnderlyingType());
4413 if (!protocols.empty()) {
4414 // Apply the protocol qualifers.
4415 bool hasError;
4416 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4417 true/*allowOnPointerType*/);
4418 assert(!hasError && "Error when apply protocol qualifier to bound type");
4419 }
4420 }
4421
4422 unsigned size = sizeof(ObjCTypeParamType);
4423 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4424 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004425 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
Manman Rene6be26c2016-09-13 17:25:08 +00004426
4427 Types.push_back(newType);
4428 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4429 return QualType(newType, 0);
4430}
4431
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004432/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4433/// protocol list adopt all protocols in QT's qualified-id protocol
4434/// list.
4435bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4436 ObjCInterfaceDecl *IC) {
4437 if (!QT->isObjCQualifiedIdType())
4438 return false;
4439
Eugene Zelenko7855e772018-04-03 00:11:50 +00004440 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004441 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004442 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004443 if (!IC->ClassImplementsProtocol(Proto, false))
4444 return false;
4445 }
4446 return true;
4447 }
4448 return false;
4449}
4450
4451/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4452/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4453/// of protocols.
4454bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4455 ObjCInterfaceDecl *IDecl) {
4456 if (!QT->isObjCQualifiedIdType())
4457 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004458 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004459 if (!OPT)
4460 return false;
4461 if (!IDecl->hasDefinition())
4462 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004463 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4464 CollectInheritedProtocols(IDecl, InheritedProtocols);
4465 if (InheritedProtocols.empty())
4466 return false;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004467 // Check that if every protocol in list of id<plist> conforms to a protocol
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004468 // of IDecl's, then bridge casting is ok.
4469 bool Conforms = false;
4470 for (auto *Proto : OPT->quals()) {
4471 Conforms = false;
4472 for (auto *PI : InheritedProtocols) {
4473 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4474 Conforms = true;
4475 break;
4476 }
4477 }
4478 if (!Conforms)
4479 break;
4480 }
4481 if (Conforms)
4482 return true;
4483
Aaron Ballman83731462014-03-17 16:14:00 +00004484 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004485 // If both the right and left sides have qualifiers.
4486 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004487 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004488 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004489 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004490 break;
4491 }
4492 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004493 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004494 }
4495 return true;
4496}
4497
John McCall8b07ec22010-05-15 11:32:37 +00004498/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4499/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004500QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004501 llvm::FoldingSetNodeID ID;
4502 ObjCObjectPointerType::Profile(ID, ObjectT);
4503
Craig Topper36250ad2014-05-12 05:36:57 +00004504 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004505 if (ObjCObjectPointerType *QT =
4506 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4507 return QualType(QT, 0);
4508
4509 // Find the canonical object type.
4510 QualType Canonical;
4511 if (!ObjectT.isCanonical()) {
4512 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4513
4514 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004515 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4516 }
4517
Douglas Gregorf85bee62010-02-08 22:59:26 +00004518 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004519 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004520 auto *QType =
John McCall8b07ec22010-05-15 11:32:37 +00004521 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004522
Steve Narofffb4330f2009-06-17 22:40:22 +00004523 Types.push_back(QType);
4524 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004525 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004526}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004527
Douglas Gregor1c283312010-08-11 12:19:30 +00004528/// getObjCInterfaceType - Return the unique reference to the type for the
4529/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004530QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4531 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004532 if (Decl->TypeForDecl)
4533 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004534
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004535 if (PrevDecl) {
4536 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4537 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4538 return QualType(PrevDecl->TypeForDecl, 0);
4539 }
4540
Douglas Gregor7671e532011-12-16 16:34:57 +00004541 // Prefer the definition, if there is one.
4542 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4543 Decl = Def;
4544
Douglas Gregor1c283312010-08-11 12:19:30 +00004545 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004546 auto *T = new (Mem) ObjCInterfaceType(Decl);
Douglas Gregor1c283312010-08-11 12:19:30 +00004547 Decl->TypeForDecl = T;
4548 Types.push_back(T);
4549 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004550}
4551
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004552/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4553/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004554/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004555/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004556/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004557QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004558 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004559 if (tofExpr->isTypeDependent()) {
4560 llvm::FoldingSetNodeID ID;
4561 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004562
Craig Topper36250ad2014-05-12 05:36:57 +00004563 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004564 DependentTypeOfExprType *Canon
4565 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4566 if (Canon) {
4567 // We already have a "canonical" version of an identical, dependent
4568 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004569 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004570 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004571 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004572 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004573 Canon
4574 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004575 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4576 toe = Canon;
4577 }
4578 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004579 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004580 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004581 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004582 Types.push_back(toe);
4583 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004584}
4585
Steve Naroffa773cd52007-08-01 18:02:17 +00004586/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004587/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004588/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004589/// an issue. This doesn't affect the type checker, since it operates
4590/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004591QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004592 QualType Canonical = getCanonicalType(tofType);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004593 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004594 Types.push_back(tot);
4595 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004596}
4597
Richard Smith8eb1d322014-06-05 20:13:13 +00004598/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4599/// nodes. This would never be helpful, since each such type has its own
4600/// expression, and would not give a significant memory saving, since there
4601/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004602QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004603 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004604
4605 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004606 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004607 // unique dependent type. Two such decltype-specifiers refer to the same
4608 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004609 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004610 llvm::FoldingSetNodeID ID;
4611 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004612
Craig Topper36250ad2014-05-12 05:36:57 +00004613 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004614 DependentDecltypeType *Canon
4615 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004616 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004617 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004618 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004619 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004620 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004621 dt = new (*this, TypeAlignment)
4622 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004623 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004624 dt = new (*this, TypeAlignment)
4625 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004626 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004627 Types.push_back(dt);
4628 return QualType(dt, 0);
4629}
4630
Alexis Hunte852b102011-05-24 22:41:36 +00004631/// getUnaryTransformationType - We don't unique these, since the memory
4632/// savings are minimal and these are rare.
4633QualType ASTContext::getUnaryTransformType(QualType BaseType,
4634 QualType UnderlyingType,
4635 UnaryTransformType::UTTKind Kind)
4636 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004637 UnaryTransformType *ut = nullptr;
4638
4639 if (BaseType->isDependentType()) {
4640 // Look in the folding set for an existing type.
4641 llvm::FoldingSetNodeID ID;
4642 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4643
4644 void *InsertPos = nullptr;
4645 DependentUnaryTransformType *Canon
4646 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4647
4648 if (!Canon) {
4649 // Build a new, canonical __underlying_type(type) type.
4650 Canon = new (*this, TypeAlignment)
4651 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4652 Kind);
4653 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4654 }
4655 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4656 QualType(), Kind,
4657 QualType(Canon, 0));
4658 } else {
4659 QualType CanonType = getCanonicalType(UnderlyingType);
4660 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4661 UnderlyingType, Kind,
4662 CanonType);
4663 }
4664 Types.push_back(ut);
4665 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004666}
4667
Richard Smith2a7d4812013-05-04 07:00:32 +00004668/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4669/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4670/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004671QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004672 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004673 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004674 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004675
Richard Smith2a7d4812013-05-04 07:00:32 +00004676 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004677 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004678 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004679 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004680 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4681 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004682
Eugene Zelenko7855e772018-04-03 00:11:50 +00004683 auto *AT = new (*this, TypeAlignment)
4684 AutoType(DeducedType, Keyword, IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004685 Types.push_back(AT);
4686 if (InsertPos)
4687 AutoTypes.InsertNode(AT, InsertPos);
4688 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004689}
4690
Richard Smith600b5262017-01-26 20:40:47 +00004691/// Return the uniqued reference to the deduced template specialization type
4692/// which has been deduced to the given type, or to the canonical undeduced
4693/// such type, or the canonical deduced-but-dependent such type.
4694QualType ASTContext::getDeducedTemplateSpecializationType(
4695 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4696 // Look in the folding set for an existing type.
4697 void *InsertPos = nullptr;
4698 llvm::FoldingSetNodeID ID;
4699 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4700 IsDependent);
4701 if (DeducedTemplateSpecializationType *DTST =
4702 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4703 return QualType(DTST, 0);
4704
Eugene Zelenko7855e772018-04-03 00:11:50 +00004705 auto *DTST = new (*this, TypeAlignment)
Richard Smith600b5262017-01-26 20:40:47 +00004706 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4707 Types.push_back(DTST);
4708 if (InsertPos)
4709 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4710 return QualType(DTST, 0);
4711}
4712
Eli Friedman0dfb8892011-10-06 23:00:33 +00004713/// getAtomicType - Return the uniqued reference to the atomic type for
4714/// the given value type.
4715QualType ASTContext::getAtomicType(QualType T) const {
4716 // Unique pointers, to guarantee there is only one pointer of a particular
4717 // structure.
4718 llvm::FoldingSetNodeID ID;
4719 AtomicType::Profile(ID, T);
4720
Craig Topper36250ad2014-05-12 05:36:57 +00004721 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004722 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4723 return QualType(AT, 0);
4724
4725 // If the atomic value type isn't canonical, this won't be a canonical type
4726 // either, so fill in the canonical type field.
4727 QualType Canonical;
4728 if (!T.isCanonical()) {
4729 Canonical = getAtomicType(getCanonicalType(T));
4730
4731 // Get the new insert position for the node we care about.
4732 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004733 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004734 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00004735 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
Eli Friedman0dfb8892011-10-06 23:00:33 +00004736 Types.push_back(New);
4737 AtomicTypes.InsertNode(New, InsertPos);
4738 return QualType(New, 0);
4739}
4740
Richard Smith02e85f32011-04-14 22:09:26 +00004741/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4742QualType ASTContext::getAutoDeductType() const {
4743 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004744 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004745 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004746 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004747 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004748 return AutoDeductTy;
4749}
4750
4751/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4752QualType ASTContext::getAutoRRefDeductType() const {
4753 if (AutoRRefDeductTy.isNull())
4754 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4755 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4756 return AutoRRefDeductTy;
4757}
4758
Chris Lattnerfb072462007-01-23 05:45:31 +00004759/// getTagDeclType - Return the unique reference to the type for the
4760/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004761QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004762 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004763 // FIXME: What is the design on getTagDeclType when it requires casting
4764 // away const? mutable?
4765 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004766}
4767
Mike Stump11289f42009-09-09 15:08:12 +00004768/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4769/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4770/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004771CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004772 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004773}
Chris Lattnerfb072462007-01-23 05:45:31 +00004774
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00004775/// Return the unique signed counterpart of the integer type
4776/// corresponding to size_t.
4777CanQualType ASTContext::getSignedSizeType() const {
4778 return getFromTargetType(Target->getSignedSizeType());
4779}
4780
Hans Wennborg27541db2011-10-27 08:29:09 +00004781/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4782CanQualType ASTContext::getIntMaxType() const {
4783 return getFromTargetType(Target->getIntMaxType());
4784}
4785
4786/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4787CanQualType ASTContext::getUIntMaxType() const {
4788 return getFromTargetType(Target->getUIntMaxType());
4789}
4790
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004791/// getSignedWCharType - Return the type of "signed wchar_t".
4792/// Used when in C++, as a GCC extension.
4793QualType ASTContext::getSignedWCharType() const {
4794 // FIXME: derive from "Target" ?
4795 return WCharTy;
4796}
4797
4798/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4799/// Used when in C++, as a GCC extension.
4800QualType ASTContext::getUnsignedWCharType() const {
4801 // FIXME: derive from "Target" ?
4802 return UnsignedIntTy;
4803}
4804
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004805QualType ASTContext::getIntPtrType() const {
4806 return getFromTargetType(Target->getIntPtrType());
4807}
4808
4809QualType ASTContext::getUIntPtrType() const {
4810 return getCorrespondingUnsignedType(getIntPtrType());
4811}
4812
Hans Wennborg27541db2011-10-27 08:29:09 +00004813/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004814/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4815QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004816 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004817}
4818
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00004819/// \brief Return the unique unsigned counterpart of "ptrdiff_t"
4820/// integer type. The standard (C11 7.21.6.1p7) refers to this type
4821/// in the definition of %tu format specifier.
4822QualType ASTContext::getUnsignedPointerDiffType() const {
4823 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
4824}
4825
Eli Friedman4e91899e2012-11-27 02:58:24 +00004826/// \brief Return the unique type for "pid_t" defined in
4827/// <sys/types.h>. We need this to compute the correct type for vfork().
4828QualType ASTContext::getProcessIDType() const {
4829 return getFromTargetType(Target->getProcessIDType());
4830}
4831
Chris Lattnera21ad802008-04-02 05:18:44 +00004832//===----------------------------------------------------------------------===//
4833// Type Operators
4834//===----------------------------------------------------------------------===//
4835
Jay Foad39c79802011-01-12 09:06:06 +00004836CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004837 // Push qualifiers into arrays, and then discard any remaining
4838 // qualifiers.
4839 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004840 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004841 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004842 QualType Result;
4843 if (isa<ArrayType>(Ty)) {
4844 Result = getArrayDecayedType(QualType(Ty,0));
4845 } else if (isa<FunctionType>(Ty)) {
4846 Result = getPointerType(QualType(Ty, 0));
4847 } else {
4848 Result = QualType(Ty, 0);
4849 }
4850
4851 return CanQualType::CreateUnsafe(Result);
4852}
4853
John McCall6c9dd522011-01-18 07:41:22 +00004854QualType ASTContext::getUnqualifiedArrayType(QualType type,
4855 Qualifiers &quals) {
4856 SplitQualType splitType = type.getSplitUnqualifiedType();
4857
4858 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4859 // the unqualified desugared type and then drops it on the floor.
4860 // We then have to strip that sugar back off with
4861 // getUnqualifiedDesugaredType(), which is silly.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004862 const auto *AT =
4863 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004864
4865 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004866 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004867 quals = splitType.Quals;
4868 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004869 }
4870
John McCall6c9dd522011-01-18 07:41:22 +00004871 // Otherwise, recurse on the array's element type.
4872 QualType elementType = AT->getElementType();
4873 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4874
4875 // If that didn't change the element type, AT has no qualifiers, so we
4876 // can just use the results in splitType.
4877 if (elementType == unqualElementType) {
4878 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004879 quals = splitType.Quals;
4880 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004881 }
4882
4883 // Otherwise, add in the qualifiers from the outermost type, then
4884 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004885 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004886
Eugene Zelenko7855e772018-04-03 00:11:50 +00004887 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004888 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004889 CAT->getSizeModifier(), 0);
4890 }
4891
Eugene Zelenko7855e772018-04-03 00:11:50 +00004892 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004893 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004894 }
4895
Eugene Zelenko7855e772018-04-03 00:11:50 +00004896 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004897 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004898 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004899 VAT->getSizeModifier(),
4900 VAT->getIndexTypeCVRQualifiers(),
4901 VAT->getBracketsRange());
4902 }
4903
Eugene Zelenko7855e772018-04-03 00:11:50 +00004904 const auto *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004905 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004906 DSAT->getSizeModifier(), 0,
4907 SourceRange());
4908}
4909
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004910/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4911/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4912/// they point to and return true. If T1 and T2 aren't pointer types
4913/// or pointer-to-member types, or if they are not similar at this
4914/// level, returns false and leaves T1 and T2 unchanged. Top-level
4915/// qualifiers on T1 and T2 are ignored. This function will typically
4916/// be called in a loop that successively "unwraps" pointer and
4917/// pointer-to-member types to compare them at each level.
4918bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004919 const auto *T1PtrType = T1->getAs<PointerType>();
4920 const auto *T2PtrType = T2->getAs<PointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004921 if (T1PtrType && T2PtrType) {
4922 T1 = T1PtrType->getPointeeType();
4923 T2 = T2PtrType->getPointeeType();
4924 return true;
4925 }
4926
Eugene Zelenko7855e772018-04-03 00:11:50 +00004927 const auto *T1MPType = T1->getAs<MemberPointerType>();
4928 const auto *T2MPType = T2->getAs<MemberPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004929 if (T1MPType && T2MPType &&
4930 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4931 QualType(T2MPType->getClass(), 0))) {
4932 T1 = T1MPType->getPointeeType();
4933 T2 = T2MPType->getPointeeType();
4934 return true;
4935 }
4936
David Blaikiebbafb8a2012-03-11 07:00:24 +00004937 if (getLangOpts().ObjC1) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004938 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
4939 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004940 if (T1OPType && T2OPType) {
4941 T1 = T1OPType->getPointeeType();
4942 T2 = T2OPType->getPointeeType();
4943 return true;
4944 }
4945 }
4946
4947 // FIXME: Block pointers, too?
4948
4949 return false;
4950}
4951
Jay Foad39c79802011-01-12 09:06:06 +00004952DeclarationNameInfo
4953ASTContext::getNameForTemplate(TemplateName Name,
4954 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004955 switch (Name.getKind()) {
4956 case TemplateName::QualifiedTemplate:
4957 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004958 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004959 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4960 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004961
John McCalld9dfe3a2011-06-30 08:33:18 +00004962 case TemplateName::OverloadedTemplate: {
4963 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4964 // DNInfo work in progress: CHECKME: what about DNLoc?
4965 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4966 }
4967
4968 case TemplateName::DependentTemplate: {
4969 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004970 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004971 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004972 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4973 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004974 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004975 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4976 // DNInfo work in progress: FIXME: source locations?
4977 DeclarationNameLoc DNLoc;
4978 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4979 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4980 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004981 }
4982 }
4983
John McCalld9dfe3a2011-06-30 08:33:18 +00004984 case TemplateName::SubstTemplateTemplateParm: {
4985 SubstTemplateTemplateParmStorage *subst
4986 = Name.getAsSubstTemplateTemplateParm();
4987 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4988 NameLoc);
4989 }
4990
4991 case TemplateName::SubstTemplateTemplateParmPack: {
4992 SubstTemplateTemplateParmPackStorage *subst
4993 = Name.getAsSubstTemplateTemplateParmPack();
4994 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4995 NameLoc);
4996 }
4997 }
4998
4999 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005000}
5001
Jay Foad39c79802011-01-12 09:06:06 +00005002TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005003 switch (Name.getKind()) {
5004 case TemplateName::QualifiedTemplate:
5005 case TemplateName::Template: {
5006 TemplateDecl *Template = Name.getAsTemplateDecl();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005007 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005008 Template = getCanonicalTemplateTemplateParmDecl(TTP);
5009
5010 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005011 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005012 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005013
John McCalld9dfe3a2011-06-30 08:33:18 +00005014 case TemplateName::OverloadedTemplate:
5015 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00005016
John McCalld9dfe3a2011-06-30 08:33:18 +00005017 case TemplateName::DependentTemplate: {
5018 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5019 assert(DTN && "Non-dependent template names must refer to template decls.");
5020 return DTN->CanonicalTemplateName;
5021 }
5022
5023 case TemplateName::SubstTemplateTemplateParm: {
5024 SubstTemplateTemplateParmStorage *subst
5025 = Name.getAsSubstTemplateTemplateParm();
5026 return getCanonicalTemplateName(subst->getReplacement());
5027 }
5028
5029 case TemplateName::SubstTemplateTemplateParmPack: {
5030 SubstTemplateTemplateParmPackStorage *subst
5031 = Name.getAsSubstTemplateTemplateParmPack();
5032 TemplateTemplateParmDecl *canonParameter
5033 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5034 TemplateArgument canonArgPack
5035 = getCanonicalTemplateArgument(subst->getArgumentPack());
5036 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5037 }
5038 }
5039
5040 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005041}
5042
Douglas Gregoradee3e32009-11-11 23:06:43 +00005043bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5044 X = getCanonicalTemplateName(X);
5045 Y = getCanonicalTemplateName(Y);
5046 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5047}
5048
Mike Stump11289f42009-09-09 15:08:12 +00005049TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005050ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005051 switch (Arg.getKind()) {
5052 case TemplateArgument::Null:
5053 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005054
Douglas Gregora8e02e72009-07-28 23:00:59 +00005055 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005056 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005057
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005058 case TemplateArgument::Declaration: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005059 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005060 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005061 }
Mike Stump11289f42009-09-09 15:08:12 +00005062
Eli Friedmanb826a002012-09-26 02:36:12 +00005063 case TemplateArgument::NullPtr:
5064 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5065 /*isNullPtr*/true);
5066
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005067 case TemplateArgument::Template:
5068 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005069
5070 case TemplateArgument::TemplateExpansion:
5071 return TemplateArgument(getCanonicalTemplateName(
5072 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005073 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005074
Douglas Gregora8e02e72009-07-28 23:00:59 +00005075 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005076 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005077
Douglas Gregora8e02e72009-07-28 23:00:59 +00005078 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005079 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005080
Douglas Gregora8e02e72009-07-28 23:00:59 +00005081 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005082 if (Arg.pack_size() == 0)
5083 return Arg;
5084
Eugene Zelenko7855e772018-04-03 00:11:50 +00005085 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005086 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005087 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005088 AEnd = Arg.pack_end();
5089 A != AEnd; (void)++A, ++Idx)
5090 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005091
Benjamin Kramercce63472015-08-05 09:40:22 +00005092 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005093 }
5094 }
5095
5096 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005097 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005098}
5099
Douglas Gregor333489b2009-03-27 23:10:48 +00005100NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005101ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005102 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005103 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005104
5105 switch (NNS->getKind()) {
5106 case NestedNameSpecifier::Identifier:
5107 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005108 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005109 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5110 NNS->getAsIdentifier());
5111
5112 case NestedNameSpecifier::Namespace:
5113 // A namespace is canonical; build a nested-name-specifier with
5114 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005115 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005116 NNS->getAsNamespace()->getOriginalNamespace());
5117
5118 case NestedNameSpecifier::NamespaceAlias:
5119 // A namespace is canonical; build a nested-name-specifier with
5120 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005121 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005122 NNS->getAsNamespaceAlias()->getNamespace()
5123 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005124
5125 case NestedNameSpecifier::TypeSpec:
5126 case NestedNameSpecifier::TypeSpecWithTemplate: {
5127 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005128
5129 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5130 // break it apart into its prefix and identifier, then reconsititute those
5131 // as the canonical nested-name-specifier. This is required to canonicalize
5132 // a dependent nested-name-specifier involving typedefs of dependent-name
5133 // types, e.g.,
5134 // typedef typename T::type T1;
5135 // typedef typename T1::type T2;
Eugene Zelenko7855e772018-04-03 00:11:50 +00005136 if (const auto *DNT = T->getAs<DependentNameType>())
Eli Friedman5358a0a2012-03-03 04:09:56 +00005137 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005138 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005139
Eli Friedman5358a0a2012-03-03 04:09:56 +00005140 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5141 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5142 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005143 return NestedNameSpecifier::Create(*this, nullptr, false,
5144 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005145 }
5146
5147 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005148 case NestedNameSpecifier::Super:
5149 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005150 return NNS;
5151 }
5152
David Blaikie8a40f702012-01-17 06:56:22 +00005153 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005154}
5155
Jay Foad39c79802011-01-12 09:06:06 +00005156const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005157 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005158 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005159 // Handle the common positive case fast.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005160 if (const auto *AT = dyn_cast<ArrayType>(T))
Chris Lattner7adf0762008-08-04 07:31:14 +00005161 return AT;
5162 }
Mike Stump11289f42009-09-09 15:08:12 +00005163
John McCall8ccfcb52009-09-24 19:53:00 +00005164 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005165 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005166 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005167
John McCall8ccfcb52009-09-24 19:53:00 +00005168 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005169 // implements C99 6.7.3p8: "If the specification of an array type includes
5170 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005171
Chris Lattner7adf0762008-08-04 07:31:14 +00005172 // If we get here, we either have type qualifiers on the type, or we have
5173 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005174 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005175
John McCall33ddac02011-01-19 10:06:00 +00005176 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005177 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005178
Chris Lattner7adf0762008-08-04 07:31:14 +00005179 // If we have a simple case, just return now.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005180 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005181 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005182 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005183
Chris Lattner7adf0762008-08-04 07:31:14 +00005184 // Otherwise, we have an array and we have qualifiers on it. Push the
5185 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005186 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005187
Eugene Zelenko7855e772018-04-03 00:11:50 +00005188 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005189 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5190 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005191 CAT->getIndexTypeCVRQualifiers()));
Eugene Zelenko7855e772018-04-03 00:11:50 +00005192 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005193 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5194 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005195 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005196
Eugene Zelenko7855e772018-04-03 00:11:50 +00005197 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
Douglas Gregor4619e432008-12-05 23:32:09 +00005198 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005199 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005200 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005201 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005202 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005203 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005204
Eugene Zelenko7855e772018-04-03 00:11:50 +00005205 const auto *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005206 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005207 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005208 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005209 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005210 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005211}
5212
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005213QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005214 if (T->isArrayType() || T->isFunctionType())
5215 return getDecayedType(T);
5216 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005217}
5218
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005219QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005220 T = getVariableArrayDecayedType(T);
5221 T = getAdjustedParameterType(T);
5222 return T.getUnqualifiedType();
5223}
5224
David Majnemerd09a51c2015-03-03 01:50:05 +00005225QualType ASTContext::getExceptionObjectType(QualType T) const {
5226 // C++ [except.throw]p3:
5227 // A throw-expression initializes a temporary object, called the exception
5228 // object, the type of which is determined by removing any top-level
5229 // cv-qualifiers from the static type of the operand of throw and adjusting
5230 // the type from "array of T" or "function returning T" to "pointer to T"
5231 // or "pointer to function returning T", [...]
5232 T = getVariableArrayDecayedType(T);
5233 if (T->isArrayType() || T->isFunctionType())
5234 T = getDecayedType(T);
5235 return T.getUnqualifiedType();
5236}
5237
Chris Lattnera21ad802008-04-02 05:18:44 +00005238/// getArrayDecayedType - Return the properly qualified result of decaying the
5239/// specified array type to a pointer. This operation is non-trivial when
5240/// handling typedefs etc. The canonical type of "T" must be an array type,
5241/// this returns a pointer to a properly qualified element of the array.
5242///
5243/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005244QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005245 // Get the element type with 'getAsArrayType' so that we don't lose any
5246 // typedefs in the element type of the array. This also handles propagation
5247 // of type qualifiers from the array type into the element type if present
5248 // (C99 6.7.3p8).
5249 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5250 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005251
Chris Lattner7adf0762008-08-04 07:31:14 +00005252 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005253
5254 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005255 QualType Result = getQualifiedType(PtrTy,
5256 PrettyArrayType->getIndexTypeQualifiers());
5257
5258 // int x[_Nullable] -> int * _Nullable
5259 if (auto Nullability = Ty->getNullability(*this)) {
5260 Result = const_cast<ASTContext *>(this)->getAttributedType(
5261 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5262 }
5263 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005264}
5265
John McCall33ddac02011-01-19 10:06:00 +00005266QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5267 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005268}
5269
John McCall33ddac02011-01-19 10:06:00 +00005270QualType ASTContext::getBaseElementType(QualType type) const {
5271 Qualifiers qs;
5272 while (true) {
5273 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005274 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005275 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005276
John McCall33ddac02011-01-19 10:06:00 +00005277 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005278 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005279 }
Mike Stump11289f42009-09-09 15:08:12 +00005280
John McCall33ddac02011-01-19 10:06:00 +00005281 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005282}
5283
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005284/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005285uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005286ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5287 uint64_t ElementCount = 1;
5288 do {
5289 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005290 CA = dyn_cast_or_null<ConstantArrayType>(
5291 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005292 } while (CA);
5293 return ElementCount;
5294}
5295
Steve Naroff0af91202007-04-27 21:51:21 +00005296/// getFloatingRank - Return a relative rank for floating point types.
5297/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005298static FloatingRank getFloatingRank(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005299 if (const auto *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005300 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005301
John McCall9dd450b2009-09-21 23:43:11 +00005302 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5303 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005304 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005305 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005306 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005307 case BuiltinType::Float: return FloatRank;
5308 case BuiltinType::Double: return DoubleRank;
5309 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005310 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005311 }
5312}
5313
Mike Stump11289f42009-09-09 15:08:12 +00005314/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5315/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005316/// 'typeDomain' is a real floating point or complex type.
5317/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005318QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5319 QualType Domain) const {
5320 FloatingRank EltRank = getFloatingRank(Size);
5321 if (Domain->isComplexType()) {
5322 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005323 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005324 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005325 case FloatRank: return FloatComplexTy;
5326 case DoubleRank: return DoubleComplexTy;
5327 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005328 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005329 }
Steve Naroff0af91202007-04-27 21:51:21 +00005330 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005331
5332 assert(Domain->isRealFloatingType() && "Unknown domain!");
5333 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005334 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005335 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005336 case FloatRank: return FloatTy;
5337 case DoubleRank: return DoubleTy;
5338 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005339 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005340 }
David Blaikief47fa302012-01-17 02:30:50 +00005341 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005342}
5343
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005344/// getFloatingTypeOrder - Compare the rank of the two specified floating
5345/// point types, ignoring the domain of the type (i.e. 'double' ==
5346/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005347/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005348int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005349 FloatingRank LHSR = getFloatingRank(LHS);
5350 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005351
Chris Lattnerb90739d2008-04-06 23:38:49 +00005352 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005353 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005354 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005355 return 1;
5356 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005357}
5358
Chris Lattner76a00cf2008-04-06 22:59:24 +00005359/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5360/// routine will assert if passed a built-in type that isn't an integer or enum,
5361/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005362unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005363 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005364
Chris Lattner76a00cf2008-04-06 22:59:24 +00005365 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005366 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005367 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005368 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005369 case BuiltinType::Char_S:
5370 case BuiltinType::Char_U:
5371 case BuiltinType::SChar:
5372 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005373 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005374 case BuiltinType::Short:
5375 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005376 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005377 case BuiltinType::Int:
5378 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005379 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005380 case BuiltinType::Long:
5381 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005382 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005383 case BuiltinType::LongLong:
5384 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005385 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005386 case BuiltinType::Int128:
5387 case BuiltinType::UInt128:
5388 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005389 }
5390}
5391
Eli Friedman629ffb92009-08-20 04:21:42 +00005392/// \brief Whether this is a promotable bitfield reference according
5393/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5394///
5395/// \returns the type this bit-field will promote to, or NULL if no
5396/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005397QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005398 if (E->isTypeDependent() || E->isValueDependent())
Eugene Zelenko7855e772018-04-03 00:11:50 +00005399 return {};
Richard Smith5b571672014-09-24 23:55:00 +00005400
5401 // FIXME: We should not do this unless E->refersToBitField() is true. This
5402 // matters in C where getSourceBitField() will find bit-fields for various
5403 // cases where the source expression is not a bit-field designator.
5404
John McCalld25db7e2013-05-06 21:39:12 +00005405 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005406 if (!Field)
Eugene Zelenko7855e772018-04-03 00:11:50 +00005407 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005408
5409 QualType FT = Field->getType();
5410
Richard Smithcaf33902011-10-10 18:28:20 +00005411 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005412 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005413 // C++ [conv.prom]p5:
5414 // A prvalue for an integral bit-field can be converted to a prvalue of type
5415 // int if int can represent all the values of the bit-field; otherwise, it
5416 // can be converted to unsigned int if unsigned int can represent all the
5417 // values of the bit-field. If the bit-field is larger yet, no integral
5418 // promotion applies to it.
5419 // C11 6.3.1.1/2:
5420 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5421 // If an int can represent all values of the original type (as restricted by
5422 // the width, for a bit-field), the value is converted to an int; otherwise,
5423 // it is converted to an unsigned int.
5424 //
5425 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5426 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00005427 if (BitWidth < IntSize)
5428 return IntTy;
5429
5430 if (BitWidth == IntSize)
5431 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5432
5433 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005434 // like the base type. GCC has some weird bugs in this area that we
5435 // deliberately do not follow (GCC follows a pre-standard resolution to
5436 // C's DR315 which treats bit-width as being part of the type, and this leaks
5437 // into their semantics in some cases).
Eugene Zelenko7855e772018-04-03 00:11:50 +00005438 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005439}
5440
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005441/// getPromotedIntegerType - Returns the type that Promotable will
5442/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5443/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005444QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005445 assert(!Promotable.isNull());
5446 assert(Promotable->isPromotableIntegerType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005447 if (const auto *ET = Promotable->getAs<EnumType>())
John McCall56774992009-12-09 09:09:27 +00005448 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005449
Eugene Zelenko7855e772018-04-03 00:11:50 +00005450 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005451 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5452 // (3.9.1) can be converted to a prvalue of the first of the following
5453 // types that can represent all the values of its underlying type:
5454 // int, unsigned int, long int, unsigned long int, long long int, or
5455 // unsigned long long int [...]
5456 // FIXME: Is there some better way to compute this?
5457 if (BT->getKind() == BuiltinType::WChar_S ||
5458 BT->getKind() == BuiltinType::WChar_U ||
5459 BT->getKind() == BuiltinType::Char16 ||
5460 BT->getKind() == BuiltinType::Char32) {
5461 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5462 uint64_t FromSize = getTypeSize(BT);
5463 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5464 LongLongTy, UnsignedLongLongTy };
5465 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5466 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5467 if (FromSize < ToSize ||
5468 (FromSize == ToSize &&
5469 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5470 return PromoteTypes[Idx];
5471 }
5472 llvm_unreachable("char type should fit into long long");
5473 }
5474 }
5475
5476 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005477 if (Promotable->isSignedIntegerType())
5478 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005479 uint64_t PromotableSize = getIntWidth(Promotable);
5480 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005481 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5482 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5483}
5484
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005485/// \brief Recurses in pointer/array types until it finds an objc retainable
5486/// type and returns its ownership.
5487Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5488 while (!T.isNull()) {
5489 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5490 return T.getObjCLifetime();
5491 if (T->isArrayType())
5492 T = getBaseElementType(T);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005493 else if (const auto *PT = T->getAs<PointerType>())
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005494 T = PT->getPointeeType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005495 else if (const auto *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005496 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005497 else
5498 break;
5499 }
5500
5501 return Qualifiers::OCL_None;
5502}
5503
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005504static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5505 // Incomplete enum types are not treated as integer types.
5506 // FIXME: In C++, enum types are never integer types.
5507 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5508 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005509 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005510}
5511
Mike Stump11289f42009-09-09 15:08:12 +00005512/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005513/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005514/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005515int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005516 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5517 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005518
5519 // Unwrap enums to their underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005520 if (const auto *ET = dyn_cast<EnumType>(LHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005521 LHSC = getIntegerTypeForEnum(ET);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005522 if (const auto *ET = dyn_cast<EnumType>(RHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005523 RHSC = getIntegerTypeForEnum(ET);
5524
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005525 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005526
Chris Lattner76a00cf2008-04-06 22:59:24 +00005527 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5528 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005529
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005530 unsigned LHSRank = getIntegerRank(LHSC);
5531 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005532
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005533 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5534 if (LHSRank == RHSRank) return 0;
5535 return LHSRank > RHSRank ? 1 : -1;
5536 }
Mike Stump11289f42009-09-09 15:08:12 +00005537
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005538 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5539 if (LHSUnsigned) {
5540 // If the unsigned [LHS] type is larger, return it.
5541 if (LHSRank >= RHSRank)
5542 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005543
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005544 // If the signed type can represent all values of the unsigned type, it
5545 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005546 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005547 return -1;
5548 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005549
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005550 // If the unsigned [RHS] type is larger, return it.
5551 if (RHSRank >= LHSRank)
5552 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005553
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005554 // If the signed type can represent all values of the unsigned type, it
5555 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005556 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005557 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005558}
Anders Carlsson98f07902007-08-17 05:31:46 +00005559
Ben Langmuirf5416742016-02-04 00:55:24 +00005560TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00005561 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005562 assert(!CFConstantStringTagDecl &&
5563 "tag and typedef should be initialized together");
5564 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5565 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00005566
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005567 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00005568 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00005569
Anders Carlsson98f07902007-08-17 05:31:46 +00005570 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00005571 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005572 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005573 // int flags;
5574 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005575 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00005576 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00005577 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005578 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00005579 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00005580 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005581 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00005582
Anders Carlsson98f07902007-08-17 05:31:46 +00005583 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00005584 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005585 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005586 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00005587 SourceLocation(),
5588 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005589 FieldTypes[i], /*TInfo=*/nullptr,
5590 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00005591 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00005592 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005593 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00005594 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00005595 }
5596
Ben Langmuirf5416742016-02-04 00:55:24 +00005597 CFConstantStringTagDecl->completeDefinition();
5598 // This type is designed to be compatible with NSConstantString, but cannot
5599 // use the same name, since NSConstantString is an interface.
5600 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5601 CFConstantStringTypeDecl =
5602 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00005603 }
Mike Stump11289f42009-09-09 15:08:12 +00005604
Quentin Colombet043406b2016-02-03 22:41:00 +00005605 return CFConstantStringTypeDecl;
5606}
5607
Ben Langmuirf5416742016-02-04 00:55:24 +00005608RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5609 if (!CFConstantStringTagDecl)
5610 getCFConstantStringDecl(); // Build the tag and the typedef.
5611 return CFConstantStringTagDecl;
5612}
5613
Quentin Colombet043406b2016-02-03 22:41:00 +00005614// getCFConstantStringType - Return the type used for constant CFStrings.
5615QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005616 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005617}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005618
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005619QualType ASTContext::getObjCSuperType() const {
5620 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005621 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005622 TUDecl->addDecl(ObjCSuperTypeDecl);
5623 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5624 }
5625 return ObjCSuperType;
5626}
5627
Douglas Gregor512b0772009-04-23 22:29:11 +00005628void ASTContext::setCFConstantStringType(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005629 const auto *TD = T->getAs<TypedefType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00005630 assert(TD && "Invalid CFConstantStringType");
5631 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005632 const auto *TagType =
Ben Langmuirf5416742016-02-04 00:55:24 +00005633 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5634 assert(TagType && "Invalid CFConstantStringType");
5635 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005636}
5637
Jay Foad39c79802011-01-12 09:06:06 +00005638QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005639 if (BlockDescriptorType)
5640 return getTagDeclType(BlockDescriptorType);
5641
Alp Toker2dea15b2013-12-17 01:22:38 +00005642 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005643 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005644 RD = buildImplicitRecord("__block_descriptor");
5645 RD->startDefinition();
5646
Mike Stumpd0153282009-10-20 02:12:22 +00005647 QualType FieldTypes[] = {
5648 UnsignedLongTy,
5649 UnsignedLongTy,
5650 };
5651
Craig Topperd6d31ac2013-07-15 08:24:27 +00005652 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005653 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005654 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005655 };
5656
5657 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005658 FieldDecl *Field = FieldDecl::Create(
5659 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005660 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5661 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005662 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005663 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005664 }
5665
Alp Toker2dea15b2013-12-17 01:22:38 +00005666 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005667
Alp Toker2dea15b2013-12-17 01:22:38 +00005668 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005669
5670 return getTagDeclType(BlockDescriptorType);
5671}
5672
Jay Foad39c79802011-01-12 09:06:06 +00005673QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005674 if (BlockDescriptorExtendedType)
5675 return getTagDeclType(BlockDescriptorExtendedType);
5676
Alp Toker2dea15b2013-12-17 01:22:38 +00005677 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005678 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005679 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5680 RD->startDefinition();
5681
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005682 QualType FieldTypes[] = {
5683 UnsignedLongTy,
5684 UnsignedLongTy,
5685 getPointerType(VoidPtrTy),
5686 getPointerType(VoidPtrTy)
5687 };
5688
Craig Topperd6d31ac2013-07-15 08:24:27 +00005689 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005690 "reserved",
5691 "Size",
5692 "CopyFuncPtr",
5693 "DestroyFuncPtr"
5694 };
5695
5696 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005697 FieldDecl *Field = FieldDecl::Create(
5698 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005699 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5700 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005701 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005702 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005703 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005704 }
5705
Alp Toker2dea15b2013-12-17 01:22:38 +00005706 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005707
Alp Toker2dea15b2013-12-17 01:22:38 +00005708 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005709 return getTagDeclType(BlockDescriptorExtendedType);
5710}
5711
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00005712TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005713 const auto *BT = dyn_cast<BuiltinType>(T);
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00005714
5715 if (!BT) {
5716 if (isa<PipeType>(T))
5717 return TargetInfo::OCLTK_Pipe;
5718
5719 return TargetInfo::OCLTK_Default;
5720 }
5721
5722 switch (BT->getKind()) {
5723#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5724 case BuiltinType::Id: \
5725 return TargetInfo::OCLTK_Image;
5726#include "clang/Basic/OpenCLImageTypes.def"
5727
5728 case BuiltinType::OCLClkEvent:
5729 return TargetInfo::OCLTK_ClkEvent;
5730
5731 case BuiltinType::OCLEvent:
5732 return TargetInfo::OCLTK_Event;
5733
5734 case BuiltinType::OCLQueue:
5735 return TargetInfo::OCLTK_Queue;
5736
5737 case BuiltinType::OCLReserveID:
5738 return TargetInfo::OCLTK_ReserveID;
5739
5740 case BuiltinType::OCLSampler:
5741 return TargetInfo::OCLTK_Sampler;
5742
5743 default:
5744 return TargetInfo::OCLTK_Default;
5745 }
5746}
5747
5748LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
5749 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
5750}
5751
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005752/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5753/// requires copy/dispose. Note that this must match the logic
5754/// in buildByrefHelpers.
5755bool ASTContext::BlockRequiresCopying(QualType Ty,
5756 const VarDecl *D) {
5757 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5758 const Expr *copyExpr = getBlockVarCopyInits(D);
5759 if (!copyExpr && record->hasTrivialDestructor()) return false;
5760
Mike Stump94967902009-10-21 18:16:27 +00005761 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005762 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005763
Akira Hatanaka7275da02018-02-28 07:15:55 +00005764 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
5765 // move or destroy.
5766 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
5767 return true;
5768
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005769 if (!Ty->isObjCRetainableType()) return false;
5770
5771 Qualifiers qs = Ty.getQualifiers();
5772
5773 // If we have lifetime, that dominates.
5774 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005775 switch (lifetime) {
5776 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5777
5778 // These are just bits as far as the runtime is concerned.
5779 case Qualifiers::OCL_ExplicitNone:
5780 case Qualifiers::OCL_Autoreleasing:
5781 return false;
Akira Hatanaka7275da02018-02-28 07:15:55 +00005782
5783 // These cases should have been taken care of when checking the type's
5784 // non-triviality.
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005785 case Qualifiers::OCL_Weak:
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005786 case Qualifiers::OCL_Strong:
Akira Hatanaka7275da02018-02-28 07:15:55 +00005787 llvm_unreachable("impossible");
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005788 }
5789 llvm_unreachable("fell out of lifetime switch!");
5790 }
5791 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5792 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005793}
5794
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005795bool ASTContext::getByrefLifetime(QualType Ty,
5796 Qualifiers::ObjCLifetime &LifeTime,
5797 bool &HasByrefExtendedLayout) const {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005798 if (!getLangOpts().ObjC1 ||
5799 getLangOpts().getGC() != LangOptions::NonGC)
5800 return false;
5801
5802 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005803 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005804 HasByrefExtendedLayout = true;
5805 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005806 } else if ((LifeTime = Ty.getObjCLifetime())) {
5807 // Honor the ARC qualifiers.
5808 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5809 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005810 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005811 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005812 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005813 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005814 return true;
5815}
5816
Douglas Gregorbab8a962011-09-08 01:46:34 +00005817TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5818 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005819 ObjCInstanceTypeDecl =
5820 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005821 return ObjCInstanceTypeDecl;
5822}
5823
Anders Carlsson18acd442007-10-29 06:33:42 +00005824// This returns true if a type has been typedefed to BOOL:
5825// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005826static bool isTypeTypedefedAsBOOL(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005827 if (const auto *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005828 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5829 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005830
Anders Carlssond8499822007-10-29 05:01:08 +00005831 return false;
5832}
5833
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005834/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005835/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005836CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005837 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5838 return CharUnits::Zero();
5839
Ken Dyck40775002010-01-11 17:06:35 +00005840 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005841
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005842 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005843 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005844 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005845 // Treat arrays as pointers, since that's how they're passed in.
5846 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005847 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005848 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005849}
5850
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005851bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005852 return getTargetInfo().getCXXABI().isMicrosoft() &&
5853 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00005854 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00005855 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005856}
5857
Richard Smithd9b90092016-07-02 01:32:16 +00005858ASTContext::InlineVariableDefinitionKind
5859ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5860 if (!VD->isInline())
5861 return InlineVariableDefinitionKind::None;
5862
5863 // In almost all cases, it's a weak definition.
5864 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00005865 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00005866 return InlineVariableDefinitionKind::Weak;
5867
5868 // If there's a file-context declaration in this translation unit, it's a
5869 // non-discardable definition.
5870 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00005871 if (D->getLexicalDeclContext()->isFileContext() &&
5872 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00005873 return InlineVariableDefinitionKind::Strong;
5874
5875 // If we've not seen one yet, we don't know.
5876 return InlineVariableDefinitionKind::WeakUnknown;
5877}
5878
Eugene Zelenko7855e772018-04-03 00:11:50 +00005879static std::string charUnitsToString(const CharUnits &CU) {
Ken Dyck40775002010-01-11 17:06:35 +00005880 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005881}
5882
John McCall351762c2011-02-07 10:33:21 +00005883/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005884/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005885std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5886 std::string S;
5887
David Chisnall950a9512009-11-17 19:33:30 +00005888 const BlockDecl *Decl = Expr->getBlockDecl();
5889 QualType BlockTy =
5890 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5891 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005892 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005893 getObjCEncodingForMethodParameter(
5894 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5895 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005896 else
Alp Toker314cc812014-01-25 16:55:45 +00005897 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005898 // Compute size of all parameters.
5899 // Start with computing size of a pointer in number of bytes.
5900 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00005901 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5902 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005903 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005904 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005905 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005906 if (sz.isZero())
5907 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00005908 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005909 ParmOffset += sz;
5910 }
5911 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005912 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005913 // Block pointer and offset.
5914 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005915
5916 // Argument types.
5917 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005918 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005919 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005920 if (const auto *AT =
5921 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall950a9512009-11-17 19:33:30 +00005922 // Use array's original type only if it has known number of
5923 // elements.
5924 if (!isa<ConstantArrayType>(AT))
5925 PType = PVDecl->getType();
5926 } else if (PType->isFunctionType())
5927 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005928 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005929 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5930 S, true /*Extended*/);
5931 else
5932 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005933 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005934 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005935 }
John McCall351762c2011-02-07 10:33:21 +00005936
5937 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005938}
5939
John McCall843dfcc2016-11-29 21:57:00 +00005940std::string
5941ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
5942 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005943 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005944 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005945 CharUnits ParmOffset;
5946 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00005947 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005948 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005949 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005950 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005951 continue;
5952
John McCall843dfcc2016-11-29 21:57:00 +00005953 assert(sz.isPositive() &&
5954 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005955 ParmOffset += sz;
5956 }
5957 S += charUnitsToString(ParmOffset);
5958 ParmOffset = CharUnits::Zero();
5959
5960 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00005961 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005962 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005963 if (const auto *AT =
5964 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005965 // Use array's original type only if it has known number of
5966 // elements.
5967 if (!isa<ConstantArrayType>(AT))
5968 PType = PVDecl->getType();
5969 } else if (PType->isFunctionType())
5970 PType = PVDecl->getType();
5971 getObjCEncodingForType(PType, S);
5972 S += charUnitsToString(ParmOffset);
5973 ParmOffset += getObjCEncodingTypeSize(PType);
5974 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005975
John McCall843dfcc2016-11-29 21:57:00 +00005976 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005977}
5978
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005979/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5980/// method parameter or return type. If Extended, include class names and
5981/// block object types.
5982void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5983 QualType T, std::string& S,
5984 bool Extended) const {
5985 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5986 getObjCEncodingForTypeQualifier(QT, S);
5987 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005988 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005989 true /*OutermostType*/,
5990 false /*EncodingProperty*/,
5991 false /*StructField*/,
5992 Extended /*EncodeBlockParameters*/,
5993 Extended /*EncodeClassNames*/);
5994}
5995
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005996/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005997/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00005998std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5999 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006000 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006001 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006002 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006003 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6004 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006005 // Compute size of all parameters.
6006 // Start with computing size of a pointer in number of bytes.
6007 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006008 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006009 // The first two arguments (self and _cmd) are pointers; account for
6010 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006011 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006012 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006013 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006014 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006015 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006016 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006017 continue;
6018
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006019 assert(sz.isPositive() &&
6020 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006021 ParmOffset += sz;
6022 }
Ken Dyck40775002010-01-11 17:06:35 +00006023 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006024 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006025 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006026
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006027 // Argument types.
6028 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006029 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006030 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006031 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006032 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006033 if (const auto *AT =
6034 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
Steve Naroffe4e55d22009-04-14 00:03:58 +00006035 // Use array's original type only if it has known number of
6036 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006037 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006038 PType = PVDecl->getType();
6039 } else if (PType->isFunctionType())
6040 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006041 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
6042 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006043 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006044 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006045 }
Douglas Gregora9d84932011-05-27 01:19:52 +00006046
John McCall843dfcc2016-11-29 21:57:00 +00006047 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006048}
6049
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006050ObjCPropertyImplDecl *
6051ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6052 const ObjCPropertyDecl *PD,
6053 const Decl *Container) const {
6054 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006055 return nullptr;
Eugene Zelenko7855e772018-04-03 00:11:50 +00006056 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006057 for (auto *PID : CID->property_impls())
6058 if (PID->getPropertyDecl() == PD)
6059 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006060 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006061 const auto *OID = cast<ObjCImplementationDecl>(Container);
Craig Topper36250ad2014-05-12 05:36:57 +00006062 for (auto *PID : OID->property_impls())
6063 if (PID->getPropertyDecl() == PD)
6064 return PID;
6065 }
6066 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006067}
6068
Daniel Dunbar4932b362008-08-28 04:38:10 +00006069/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006070/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006071/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6072/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006073/// Property attributes are stored as a comma-delimited C string. The simple
6074/// attributes readonly and bycopy are encoded as single characters. The
6075/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6076/// encoded as single characters, followed by an identifier. Property types
6077/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006078/// these attributes are defined by the following enumeration:
6079/// @code
6080/// enum PropertyAttributes {
6081/// kPropertyReadOnly = 'R', // property is read-only.
6082/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6083/// kPropertyByref = '&', // property is a reference to the value last assigned
6084/// kPropertyDynamic = 'D', // property is dynamic
6085/// kPropertyGetter = 'G', // followed by getter selector name
6086/// kPropertySetter = 'S', // followed by setter selector name
6087/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006088/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006089/// kPropertyWeak = 'W' // 'weak' property
6090/// kPropertyStrong = 'P' // property GC'able
6091/// kPropertyNonAtomic = 'N' // property non-atomic
6092/// };
6093/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006094std::string
6095ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6096 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006097 // Collect information from the property implementation decl(s).
6098 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006099 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006100
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006101 if (ObjCPropertyImplDecl *PropertyImpDecl =
6102 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6103 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6104 Dynamic = true;
6105 else
6106 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006107 }
6108
6109 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006110 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006111
6112 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006113 // GCC has some special rules regarding encoding of properties which
6114 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006115 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006116
6117 if (PD->isReadOnly()) {
6118 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006119 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6120 S += ",C";
6121 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6122 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006123 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6124 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006125 } else {
6126 switch (PD->getSetterKind()) {
6127 case ObjCPropertyDecl::Assign: break;
6128 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006129 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006130 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006131 }
6132 }
6133
6134 // It really isn't clear at all what this means, since properties
6135 // are "dynamic by default".
6136 if (Dynamic)
6137 S += ",D";
6138
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006139 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6140 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006141
Daniel Dunbar4932b362008-08-28 04:38:10 +00006142 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6143 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006144 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006145 }
6146
6147 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6148 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006149 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006150 }
6151
6152 if (SynthesizePID) {
6153 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6154 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006155 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006156 }
6157
6158 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006159 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006160}
6161
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006162/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006163/// Another legacy compatibility encoding: 32-bit longs are encoded as
6164/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006165/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006166void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006167 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006168 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006169 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006170 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006171 else
Jay Foad39c79802011-01-12 09:06:06 +00006172 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006173 PointeeTy = IntTy;
6174 }
6175 }
6176}
6177
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006178void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006179 const FieldDecl *Field,
6180 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006181 // We follow the behavior of gcc, expanding structures which are
6182 // directly pointed to, and expanding embedded structures. Note that
6183 // these rules are sufficient to prevent recursive encoding of the
6184 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00006185 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006186 true /* outermost type */, false, false,
6187 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006188}
6189
Joe Groff98ac7d22014-07-07 22:25:15 +00006190void ASTContext::getObjCEncodingForPropertyType(QualType T,
6191 std::string& S) const {
6192 // Encode result type.
6193 // GCC has some special rules regarding encoding of properties which
6194 // closely resembles encoding of ivars.
6195 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
6196 true /* outermost type */,
6197 true /* encoding property */);
6198}
6199
John McCall393a78d2012-12-20 02:45:14 +00006200static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
6201 BuiltinType::Kind kind) {
6202 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006203 case BuiltinType::Void: return 'v';
6204 case BuiltinType::Bool: return 'B';
6205 case BuiltinType::Char_U:
6206 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006207 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006208 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006209 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006210 case BuiltinType::UInt: return 'I';
6211 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006212 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006213 case BuiltinType::UInt128: return 'T';
6214 case BuiltinType::ULongLong: return 'Q';
6215 case BuiltinType::Char_S:
6216 case BuiltinType::SChar: return 'c';
6217 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006218 case BuiltinType::WChar_S:
6219 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006220 case BuiltinType::Int: return 'i';
6221 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006222 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006223 case BuiltinType::LongLong: return 'q';
6224 case BuiltinType::Int128: return 't';
6225 case BuiltinType::Float: return 'f';
6226 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006227 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006228 case BuiltinType::NullPtr: return '*'; // like char*
6229
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006230 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006231 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006232 case BuiltinType::Half:
6233 // FIXME: potentially need @encodes for these!
6234 return ' ';
6235
6236 case BuiltinType::ObjCId:
6237 case BuiltinType::ObjCClass:
6238 case BuiltinType::ObjCSel:
6239 llvm_unreachable("@encoding ObjC primitive type");
6240
6241 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006242#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6243 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006244#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006245 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006246 case BuiltinType::OCLClkEvent:
6247 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006248 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006249 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006250 case BuiltinType::Dependent:
6251#define BUILTIN_TYPE(KIND, ID)
6252#define PLACEHOLDER_TYPE(KIND, ID) \
6253 case BuiltinType::KIND:
6254#include "clang/AST/BuiltinTypes.def"
6255 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006256 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006257 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006258}
6259
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006260static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6261 EnumDecl *Enum = ET->getDecl();
6262
6263 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6264 if (!Enum->isFixed())
6265 return 'i';
6266
6267 // The encoding of a fixed enum type matches its fixed underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00006268 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006269 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006270}
6271
Jay Foad39c79802011-01-12 09:06:06 +00006272static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006273 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006274 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006275 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006276 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6277 // The GNU runtime requires more information; bitfields are encoded as b,
6278 // then the offset (in bits) of the first element, then the type of the
6279 // bitfield, then the size in bits. For example, in this structure:
6280 //
6281 // struct
6282 // {
6283 // int integer;
6284 // int flags:2;
6285 // };
6286 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6287 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6288 // information is not especially sensible, but we're stuck with it for
6289 // compatibility with GCC, although providing it breaks anything that
6290 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006291 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006292 uint64_t Offset;
6293
6294 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6295 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6296 IVD);
6297 } else {
6298 const RecordDecl *RD = FD->getParent();
6299 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6300 Offset = RL.getFieldOffset(FD->getFieldIndex());
6301 }
6302
6303 S += llvm::utostr(Offset);
6304
Eugene Zelenko7855e772018-04-03 00:11:50 +00006305 if (const auto *ET = T->getAs<EnumType>())
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006306 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006307 else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006308 const auto *BT = T->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006309 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6310 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006311 }
Richard Smithcaf33902011-10-10 18:28:20 +00006312 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006313}
6314
Daniel Dunbar07d07852009-10-18 21:17:35 +00006315// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006316void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6317 bool ExpandPointedToStructures,
6318 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006319 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006320 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006321 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006322 bool StructField,
6323 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006324 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006325 bool EncodePointerToObjCTypedef,
6326 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006327 CanQualType CT = getCanonicalType(T);
6328 switch (CT->getTypeClass()) {
6329 case Type::Builtin:
6330 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006331 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006332 return EncodeBitField(this, S, T, FD);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006333 if (const auto *BT = dyn_cast<BuiltinType>(CT))
John McCall393a78d2012-12-20 02:45:14 +00006334 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6335 else
6336 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006337 return;
Mike Stump11289f42009-09-09 15:08:12 +00006338
John McCall393a78d2012-12-20 02:45:14 +00006339 case Type::Complex: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006340 const auto *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006341 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006342 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006343 return;
6344 }
John McCall393a78d2012-12-20 02:45:14 +00006345
6346 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006347 const auto *AT = T->castAs<AtomicType>();
John McCall393a78d2012-12-20 02:45:14 +00006348 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006349 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006350 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006351 }
John McCall393a78d2012-12-20 02:45:14 +00006352
6353 // encoding for pointer or reference types.
6354 case Type::Pointer:
6355 case Type::LValueReference:
6356 case Type::RValueReference: {
6357 QualType PointeeTy;
6358 if (isa<PointerType>(CT)) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006359 const auto *PT = T->castAs<PointerType>();
John McCall393a78d2012-12-20 02:45:14 +00006360 if (PT->isObjCSelType()) {
6361 S += ':';
6362 return;
6363 }
6364 PointeeTy = PT->getPointeeType();
6365 } else {
6366 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6367 }
6368
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006369 bool isReadOnly = false;
6370 // For historical/compatibility reasons, the read-only qualifier of the
6371 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6372 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006373 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006374 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006375 if (OutermostType && T.isConstQualified()) {
6376 isReadOnly = true;
6377 S += 'r';
6378 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006379 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006380 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006381 while (P->getAs<PointerType>())
6382 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006383 if (P.isConstQualified()) {
6384 isReadOnly = true;
6385 S += 'r';
6386 }
6387 }
6388 if (isReadOnly) {
6389 // Another legacy compatibility encoding. Some ObjC qualifier and type
6390 // combinations need to be rearranged.
6391 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006392 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006393 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006394 }
Mike Stump11289f42009-09-09 15:08:12 +00006395
Anders Carlssond8499822007-10-29 05:01:08 +00006396 if (PointeeTy->isCharType()) {
6397 // char pointer types should be encoded as '*' unless it is a
6398 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006399 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006400 S += '*';
6401 return;
6402 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00006403 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006404 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6405 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6406 S += '#';
6407 return;
6408 }
6409 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6410 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6411 S += '@';
6412 return;
6413 }
6414 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006415 }
Anders Carlssond8499822007-10-29 05:01:08 +00006416 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006417 getLegacyIntegralTypeEncoding(PointeeTy);
6418
Mike Stump11289f42009-09-09 15:08:12 +00006419 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006420 nullptr, false, false, false, false, false, false,
6421 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006422 return;
6423 }
John McCall393a78d2012-12-20 02:45:14 +00006424
6425 case Type::ConstantArray:
6426 case Type::IncompleteArray:
6427 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006428 const auto *AT = cast<ArrayType>(CT);
John McCall393a78d2012-12-20 02:45:14 +00006429
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006430 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006431 // Incomplete arrays are encoded as a pointer to the array element.
6432 S += '^';
6433
Mike Stump11289f42009-09-09 15:08:12 +00006434 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006435 false, ExpandStructures, FD);
6436 } else {
6437 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006438
Eugene Zelenko7855e772018-04-03 00:11:50 +00006439 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006440 S += llvm::utostr(CAT->getSize().getZExtValue());
6441 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006442 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006443 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6444 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006445 S += '0';
6446 }
Mike Stump11289f42009-09-09 15:08:12 +00006447
6448 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006449 false, ExpandStructures, FD,
6450 false, false, false, false, false, false,
6451 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006452 S += ']';
6453 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006454 return;
6455 }
Mike Stump11289f42009-09-09 15:08:12 +00006456
John McCall393a78d2012-12-20 02:45:14 +00006457 case Type::FunctionNoProto:
6458 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006459 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006460 return;
Mike Stump11289f42009-09-09 15:08:12 +00006461
John McCall393a78d2012-12-20 02:45:14 +00006462 case Type::Record: {
6463 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006464 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006465 // Anonymous structures print as '?'
6466 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6467 S += II->getName();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006468 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006469 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006470 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00006471 printTemplateArgumentList(OS, TemplateArgs.asArray(),
6472 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006473 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006474 } else {
6475 S += '?';
6476 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006477 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006478 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006479 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006480 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006481 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006482 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006483 if (FD) {
6484 S += '"';
6485 S += Field->getNameAsString();
6486 S += '"';
6487 }
Mike Stump11289f42009-09-09 15:08:12 +00006488
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006489 // Special case bit-fields.
6490 if (Field->isBitField()) {
6491 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006492 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006493 } else {
6494 QualType qt = Field->getType();
6495 getLegacyIntegralTypeEncoding(qt);
6496 getObjCEncodingForTypeImpl(qt, S, false, true,
6497 FD, /*OutermostType*/false,
6498 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006499 /*StructField*/true,
6500 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006501 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006502 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006503 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006504 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006505 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006506 return;
6507 }
Mike Stump11289f42009-09-09 15:08:12 +00006508
John McCall393a78d2012-12-20 02:45:14 +00006509 case Type::BlockPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006510 const auto *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006511 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006512 if (EncodeBlockParameters) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006513 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006514
6515 S += '<';
6516 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006517 getObjCEncodingForTypeImpl(
6518 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6519 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006520 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6521 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006522 // Block self
6523 S += "@?";
6524 // Block parameters
Eugene Zelenko7855e772018-04-03 00:11:50 +00006525 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006526 for (const auto &I : FPT->param_types())
6527 getObjCEncodingForTypeImpl(
6528 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6529 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006530 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6531 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006532 }
6533 S += '>';
6534 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006535 return;
6536 }
Mike Stump11289f42009-09-09 15:08:12 +00006537
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006538 case Type::ObjCObject: {
6539 // hack to match legacy encoding of *id and *Class
6540 QualType Ty = getObjCObjectPointerType(CT);
6541 if (Ty->isObjCIdType()) {
6542 S += "{objc_object=}";
6543 return;
6544 }
6545 else if (Ty->isObjCClassType()) {
6546 S += "{objc_class=}";
6547 return;
6548 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006549 // TODO: Double check to make sure this intentionally falls through.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006550 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006551 }
6552
John McCall393a78d2012-12-20 02:45:14 +00006553 case Type::ObjCInterface: {
6554 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006555 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006556 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006557 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006558 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006559 if (ExpandStructures) {
6560 S += '=';
6561 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6562 DeepCollectObjCIvars(OI, true, Ivars);
6563 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006564 const FieldDecl *Field = Ivars[i];
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006565 if (Field->isBitField())
6566 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6567 else
6568 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6569 false, false, false, false, false,
6570 EncodePointerToObjCTypedef,
6571 NotEncodedT);
6572 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006573 }
6574 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006575 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006576 }
Mike Stump11289f42009-09-09 15:08:12 +00006577
John McCall393a78d2012-12-20 02:45:14 +00006578 case Type::ObjCObjectPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006579 const auto *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006580 if (OPT->isObjCIdType()) {
6581 S += '@';
6582 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006583 }
Mike Stump11289f42009-09-09 15:08:12 +00006584
Steve Narofff0c86112009-10-28 22:03:49 +00006585 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6586 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6587 // Since this is a binary compatibility issue, need to consult with runtime
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006588 // folks. Fortunately, this is a *very* obscure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006589 S += '#';
6590 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006591 }
Mike Stump11289f42009-09-09 15:08:12 +00006592
Chris Lattnere7cabb92009-07-13 00:10:46 +00006593 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006594 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006595 ExpandPointedToStructures,
6596 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006597 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006598 // Note that we do extended encoding of protocol qualifer list
6599 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006600 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006601 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006602 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006603 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006604 S += '>';
6605 }
6606 S += '"';
6607 }
6608 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006609 }
Mike Stump11289f42009-09-09 15:08:12 +00006610
Chris Lattnere7cabb92009-07-13 00:10:46 +00006611 QualType PointeeTy = OPT->getPointeeType();
6612 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006613 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6614 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006615 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006616 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006617 // {...};
6618 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006619 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006620 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006621 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6622 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6623 DeepCollectObjCIvars(OI, true, Ivars);
6624 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006625 if (Ivars[i] == FD) {
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006626 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006627 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006628 S += '}';
6629 return;
6630 }
6631 }
6632 }
Mike Stump11289f42009-09-09 15:08:12 +00006633 getObjCEncodingForTypeImpl(PointeeTy, S,
6634 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006635 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006636 false, false, false, false, false,
6637 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006638 return;
6639 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006640
6641 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006642 if (OPT->getInterfaceDecl() &&
6643 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006644 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006645 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006646 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006647 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006648 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006649 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006650 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006651 S += '"';
6652 }
6653 return;
6654 }
Mike Stump11289f42009-09-09 15:08:12 +00006655
John McCalla9e6e8d2010-05-17 23:56:34 +00006656 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006657 // FIXME: we shoul do better than that. 'M' is available.
6658 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006659 // This matches gcc's encoding, even though technically it is insufficient.
6660 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006661 case Type::Vector:
6662 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006663 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006664 if (NotEncodedT)
6665 *NotEncodedT = T;
6666 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006667
6668 // We could see an undeduced auto type here during error recovery.
6669 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006670 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00006671 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00006672 return;
6673
Xiuli Pan9c14e282016-01-09 12:53:17 +00006674 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006675#define ABSTRACT_TYPE(KIND, BASE)
6676#define TYPE(KIND, BASE)
6677#define DEPENDENT_TYPE(KIND, BASE) \
6678 case Type::KIND:
6679#define NON_CANONICAL_TYPE(KIND, BASE) \
6680 case Type::KIND:
6681#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6682 case Type::KIND:
6683#include "clang/AST/TypeNodes.def"
6684 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006685 }
John McCall393a78d2012-12-20 02:45:14 +00006686 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006687}
6688
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006689void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6690 std::string &S,
6691 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006692 bool includeVBases,
6693 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006694 assert(RDecl && "Expected non-null RecordDecl");
6695 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006696 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006697 return;
6698
Eugene Zelenko7855e772018-04-03 00:11:50 +00006699 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006700 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6701 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6702
6703 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006704 for (const auto &BI : CXXRec->bases()) {
6705 if (!BI.isVirtual()) {
6706 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006707 if (base->isEmpty())
6708 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006709 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006710 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6711 std::make_pair(offs, base));
6712 }
6713 }
6714 }
6715
6716 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006717 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006718 uint64_t offs = layout.getFieldOffset(i);
6719 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006720 std::make_pair(offs, Field));
6721 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006722 }
6723
6724 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006725 for (const auto &BI : CXXRec->vbases()) {
6726 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006727 if (base->isEmpty())
6728 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006729 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006730 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6731 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006732 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6733 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006734 }
6735 }
6736
6737 CharUnits size;
6738 if (CXXRec) {
6739 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6740 } else {
6741 size = layout.getSize();
6742 }
6743
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006744#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006745 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006746#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006747 std::multimap<uint64_t, NamedDecl *>::iterator
6748 CurLayObj = FieldOrBaseOffsets.begin();
6749
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006750 if (CXXRec && CXXRec->isDynamicClass() &&
6751 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006752 if (FD) {
6753 S += "\"_vptr$";
6754 std::string recname = CXXRec->getNameAsString();
6755 if (recname.empty()) recname = "?";
6756 S += recname;
6757 S += '"';
6758 }
6759 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006760#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006761 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006762#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006763 }
6764
6765 if (!RDecl->hasFlexibleArrayMember()) {
6766 // Mark the end of the structure.
6767 uint64_t offs = toBits(size);
6768 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006769 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006770 }
6771
6772 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006773#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006774 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006775 if (CurOffs < CurLayObj->first) {
6776 uint64_t padding = CurLayObj->first - CurOffs;
6777 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6778 // packing/alignment of members is different that normal, in which case
6779 // the encoding will be out-of-sync with the real layout.
6780 // If the runtime switches to just consider the size of types without
6781 // taking into account alignment, we could make padding explicit in the
6782 // encoding (e.g. using arrays of chars). The encoding strings would be
6783 // longer then though.
6784 CurOffs += padding;
6785 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006786#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006787
6788 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006789 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006790 break; // reached end of structure.
6791
Eugene Zelenko7855e772018-04-03 00:11:50 +00006792 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006793 // We expand the bases without their virtual bases since those are going
6794 // in the initial structure. Note that this differs from gcc which
6795 // expands virtual bases each time one is encountered in the hierarchy,
6796 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006797 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6798 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006799 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006800#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006801 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006802#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006803 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006804 const auto *field = cast<FieldDecl>(dcl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006805 if (FD) {
6806 S += '"';
6807 S += field->getNameAsString();
6808 S += '"';
6809 }
6810
6811 if (field->isBitField()) {
6812 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006813#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006814 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006815#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006816 } else {
6817 QualType qt = field->getType();
6818 getLegacyIntegralTypeEncoding(qt);
6819 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6820 /*OutermostType*/false,
6821 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006822 /*StructField*/true,
6823 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006824#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006825 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006826#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006827 }
6828 }
6829 }
6830}
6831
Mike Stump11289f42009-09-09 15:08:12 +00006832void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006833 std::string& S) const {
6834 if (QT & Decl::OBJC_TQ_In)
6835 S += 'n';
6836 if (QT & Decl::OBJC_TQ_Inout)
6837 S += 'N';
6838 if (QT & Decl::OBJC_TQ_Out)
6839 S += 'o';
6840 if (QT & Decl::OBJC_TQ_Bycopy)
6841 S += 'O';
6842 if (QT & Decl::OBJC_TQ_Byref)
6843 S += 'R';
6844 if (QT & Decl::OBJC_TQ_Oneway)
6845 S += 'V';
6846}
6847
Douglas Gregor3ea72692011-08-12 05:46:01 +00006848TypedefDecl *ASTContext::getObjCIdDecl() const {
6849 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006850 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00006851 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006852 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006853 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006854 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006855}
6856
Douglas Gregor52e02802011-08-12 06:17:30 +00006857TypedefDecl *ASTContext::getObjCSelDecl() const {
6858 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006859 QualType T = getPointerType(ObjCBuiltinSelTy);
6860 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006861 }
6862 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006863}
6864
Douglas Gregor0a586182011-08-12 05:59:41 +00006865TypedefDecl *ASTContext::getObjCClassDecl() const {
6866 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006867 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00006868 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006869 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006870 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006871 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006872}
6873
Douglas Gregord53ae832012-01-17 18:09:05 +00006874ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6875 if (!ObjCProtocolClassDecl) {
6876 ObjCProtocolClassDecl
6877 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6878 SourceLocation(),
6879 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006880 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006881 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006882 SourceLocation(), true);
6883 }
6884
6885 return ObjCProtocolClassDecl;
6886}
6887
Meador Inge5d3fb222012-06-16 03:34:49 +00006888//===----------------------------------------------------------------------===//
6889// __builtin_va_list Construction Functions
6890//===----------------------------------------------------------------------===//
6891
Charles Davisc7d5c942015-09-17 20:55:33 +00006892static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6893 StringRef Name) {
6894 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006895 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006896 return Context->buildImplicitTypedef(T, Name);
6897}
6898
6899static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6900 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6901}
6902
6903static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6904 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006905}
6906
6907static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6908 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006909 QualType T = Context->getPointerType(Context->VoidTy);
6910 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006911}
6912
Tim Northover9bb857a2013-01-31 12:13:10 +00006913static TypedefDecl *
6914CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006915 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006916 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006917 if (Context->getLangOpts().CPlusPlus) {
6918 // namespace std { struct __va_list {
6919 NamespaceDecl *NS;
6920 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6921 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006922 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006923 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006924 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006925 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006926 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006927 }
6928
6929 VaListTagDecl->startDefinition();
6930
6931 const size_t NumFields = 5;
6932 QualType FieldTypes[NumFields];
6933 const char *FieldNames[NumFields];
6934
6935 // void *__stack;
6936 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6937 FieldNames[0] = "__stack";
6938
6939 // void *__gr_top;
6940 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6941 FieldNames[1] = "__gr_top";
6942
6943 // void *__vr_top;
6944 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6945 FieldNames[2] = "__vr_top";
6946
6947 // int __gr_offs;
6948 FieldTypes[3] = Context->IntTy;
6949 FieldNames[3] = "__gr_offs";
6950
6951 // int __vr_offs;
6952 FieldTypes[4] = Context->IntTy;
6953 FieldNames[4] = "__vr_offs";
6954
6955 // Create fields
6956 for (unsigned i = 0; i < NumFields; ++i) {
6957 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6958 VaListTagDecl,
6959 SourceLocation(),
6960 SourceLocation(),
6961 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006962 FieldTypes[i], /*TInfo=*/nullptr,
6963 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006964 /*Mutable=*/false,
6965 ICIS_NoInit);
6966 Field->setAccess(AS_public);
6967 VaListTagDecl->addDecl(Field);
6968 }
6969 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006970 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006971 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006972
6973 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006974 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006975}
6976
Meador Inge5d3fb222012-06-16 03:34:49 +00006977static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6978 // typedef struct __va_list_tag {
6979 RecordDecl *VaListTagDecl;
6980
Alp Toker2dea15b2013-12-17 01:22:38 +00006981 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006982 VaListTagDecl->startDefinition();
6983
6984 const size_t NumFields = 5;
6985 QualType FieldTypes[NumFields];
6986 const char *FieldNames[NumFields];
6987
6988 // unsigned char gpr;
6989 FieldTypes[0] = Context->UnsignedCharTy;
6990 FieldNames[0] = "gpr";
6991
6992 // unsigned char fpr;
6993 FieldTypes[1] = Context->UnsignedCharTy;
6994 FieldNames[1] = "fpr";
6995
6996 // unsigned short reserved;
6997 FieldTypes[2] = Context->UnsignedShortTy;
6998 FieldNames[2] = "reserved";
6999
7000 // void* overflow_arg_area;
7001 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7002 FieldNames[3] = "overflow_arg_area";
7003
7004 // void* reg_save_area;
7005 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7006 FieldNames[4] = "reg_save_area";
7007
7008 // Create fields
7009 for (unsigned i = 0; i < NumFields; ++i) {
7010 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7011 SourceLocation(),
7012 SourceLocation(),
7013 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007014 FieldTypes[i], /*TInfo=*/nullptr,
7015 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007016 /*Mutable=*/false,
7017 ICIS_NoInit);
7018 Field->setAccess(AS_public);
7019 VaListTagDecl->addDecl(Field);
7020 }
7021 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007022 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007023 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7024
7025 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007026 TypedefDecl *VaListTagTypedefDecl =
7027 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7028
Meador Inge5d3fb222012-06-16 03:34:49 +00007029 QualType VaListTagTypedefType =
7030 Context->getTypedefType(VaListTagTypedefDecl);
7031
7032 // typedef __va_list_tag __builtin_va_list[1];
7033 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7034 QualType VaListTagArrayType
7035 = Context->getConstantArrayType(VaListTagTypedefType,
7036 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007037 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007038}
7039
7040static TypedefDecl *
7041CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007042 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007043 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007044 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007045 VaListTagDecl->startDefinition();
7046
7047 const size_t NumFields = 4;
7048 QualType FieldTypes[NumFields];
7049 const char *FieldNames[NumFields];
7050
7051 // unsigned gp_offset;
7052 FieldTypes[0] = Context->UnsignedIntTy;
7053 FieldNames[0] = "gp_offset";
7054
7055 // unsigned fp_offset;
7056 FieldTypes[1] = Context->UnsignedIntTy;
7057 FieldNames[1] = "fp_offset";
7058
7059 // void* overflow_arg_area;
7060 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7061 FieldNames[2] = "overflow_arg_area";
7062
7063 // void* reg_save_area;
7064 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7065 FieldNames[3] = "reg_save_area";
7066
7067 // Create fields
7068 for (unsigned i = 0; i < NumFields; ++i) {
7069 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7070 VaListTagDecl,
7071 SourceLocation(),
7072 SourceLocation(),
7073 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007074 FieldTypes[i], /*TInfo=*/nullptr,
7075 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007076 /*Mutable=*/false,
7077 ICIS_NoInit);
7078 Field->setAccess(AS_public);
7079 VaListTagDecl->addDecl(Field);
7080 }
7081 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007082 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007083 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7084
Richard Smith9b88a4c2015-07-27 05:40:23 +00007085 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007086
Richard Smith9b88a4c2015-07-27 05:40:23 +00007087 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007088 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007089 QualType VaListTagArrayType =
7090 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007091 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007092}
7093
7094static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7095 // typedef int __builtin_va_list[4];
7096 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00007097 QualType IntArrayType =
7098 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007099 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007100}
7101
Logan Chien57086ce2012-10-10 06:56:20 +00007102static TypedefDecl *
7103CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007104 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007105 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007106 if (Context->getLangOpts().CPlusPlus) {
7107 // namespace std { struct __va_list {
7108 NamespaceDecl *NS;
7109 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7110 Context->getTranslationUnitDecl(),
7111 /*Inline*/false, SourceLocation(),
7112 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007113 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007114 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007115 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007116 }
7117
7118 VaListDecl->startDefinition();
7119
7120 // void * __ap;
7121 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7122 VaListDecl,
7123 SourceLocation(),
7124 SourceLocation(),
7125 &Context->Idents.get("__ap"),
7126 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007127 /*TInfo=*/nullptr,
7128 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007129 /*Mutable=*/false,
7130 ICIS_NoInit);
7131 Field->setAccess(AS_public);
7132 VaListDecl->addDecl(Field);
7133
7134 // };
7135 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007136 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007137
7138 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007139 QualType T = Context->getRecordType(VaListDecl);
7140 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007141}
7142
Ulrich Weigand47445072013-05-06 16:26:41 +00007143static TypedefDecl *
7144CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007145 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007146 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007147 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007148 VaListTagDecl->startDefinition();
7149
7150 const size_t NumFields = 4;
7151 QualType FieldTypes[NumFields];
7152 const char *FieldNames[NumFields];
7153
7154 // long __gpr;
7155 FieldTypes[0] = Context->LongTy;
7156 FieldNames[0] = "__gpr";
7157
7158 // long __fpr;
7159 FieldTypes[1] = Context->LongTy;
7160 FieldNames[1] = "__fpr";
7161
7162 // void *__overflow_arg_area;
7163 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7164 FieldNames[2] = "__overflow_arg_area";
7165
7166 // void *__reg_save_area;
7167 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7168 FieldNames[3] = "__reg_save_area";
7169
7170 // Create fields
7171 for (unsigned i = 0; i < NumFields; ++i) {
7172 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7173 VaListTagDecl,
7174 SourceLocation(),
7175 SourceLocation(),
7176 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007177 FieldTypes[i], /*TInfo=*/nullptr,
7178 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007179 /*Mutable=*/false,
7180 ICIS_NoInit);
7181 Field->setAccess(AS_public);
7182 VaListTagDecl->addDecl(Field);
7183 }
7184 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007185 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007186 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007187
Richard Smith9b88a4c2015-07-27 05:40:23 +00007188 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007189
7190 // typedef __va_list_tag __builtin_va_list[1];
7191 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007192 QualType VaListTagArrayType =
7193 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007194
Alp Toker56b5cc92013-12-15 10:36:26 +00007195 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007196}
7197
Meador Inge5d3fb222012-06-16 03:34:49 +00007198static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7199 TargetInfo::BuiltinVaListKind Kind) {
7200 switch (Kind) {
7201 case TargetInfo::CharPtrBuiltinVaList:
7202 return CreateCharPtrBuiltinVaListDecl(Context);
7203 case TargetInfo::VoidPtrBuiltinVaList:
7204 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007205 case TargetInfo::AArch64ABIBuiltinVaList:
7206 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007207 case TargetInfo::PowerABIBuiltinVaList:
7208 return CreatePowerABIBuiltinVaListDecl(Context);
7209 case TargetInfo::X86_64ABIBuiltinVaList:
7210 return CreateX86_64ABIBuiltinVaListDecl(Context);
7211 case TargetInfo::PNaClABIBuiltinVaList:
7212 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007213 case TargetInfo::AAPCSABIBuiltinVaList:
7214 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007215 case TargetInfo::SystemZBuiltinVaList:
7216 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007217 }
7218
7219 llvm_unreachable("Unhandled __builtin_va_list type kind");
7220}
7221
7222TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007223 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007224 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007225 assert(BuiltinVaListDecl->isImplicit());
7226 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007227
7228 return BuiltinVaListDecl;
7229}
7230
Richard Smith9b88a4c2015-07-27 05:40:23 +00007231Decl *ASTContext::getVaListTagDecl() const {
7232 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007233 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007234 if (!VaListTagDecl)
7235 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007236
Richard Smith9b88a4c2015-07-27 05:40:23 +00007237 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007238}
7239
Charles Davisc7d5c942015-09-17 20:55:33 +00007240TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7241 if (!BuiltinMSVaListDecl)
7242 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7243
7244 return BuiltinMSVaListDecl;
7245}
7246
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007247void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007248 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007249 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007250
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007251 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007252}
7253
John McCalld28ae272009-12-02 08:04:21 +00007254/// \brief Retrieve the template name that corresponds to a non-empty
7255/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007256TemplateName
7257ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7258 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007259 unsigned size = End - Begin;
7260 assert(size > 1 && "set is not overloaded!");
7261
7262 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7263 size * sizeof(FunctionTemplateDecl*));
Eugene Zelenko7855e772018-04-03 00:11:50 +00007264 auto *OT = new (memory) OverloadedTemplateStorage(size);
John McCalld28ae272009-12-02 08:04:21 +00007265
7266 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007267 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007268 NamedDecl *D = *I;
7269 assert(isa<FunctionTemplateDecl>(D) ||
7270 (isa<UsingShadowDecl>(D) &&
7271 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7272 *Storage++ = D;
7273 }
7274
7275 return TemplateName(OT);
7276}
7277
Douglas Gregordc572a32009-03-30 22:58:21 +00007278/// \brief Retrieve the template name that represents a qualified
7279/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007280TemplateName
7281ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7282 bool TemplateKeyword,
7283 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007284 assert(NNS && "Missing nested-name-specifier in qualified template name");
7285
Douglas Gregorc42075a2010-02-04 18:10:26 +00007286 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007287 llvm::FoldingSetNodeID ID;
7288 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7289
Craig Topper36250ad2014-05-12 05:36:57 +00007290 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007291 QualifiedTemplateName *QTN =
7292 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7293 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007294 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007295 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007296 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7297 }
7298
7299 return TemplateName(QTN);
7300}
7301
7302/// \brief Retrieve the template name that represents a dependent
7303/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007304TemplateName
7305ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7306 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007307 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007308 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007309
7310 llvm::FoldingSetNodeID ID;
7311 DependentTemplateName::Profile(ID, NNS, Name);
7312
Craig Topper36250ad2014-05-12 05:36:57 +00007313 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007314 DependentTemplateName *QTN =
7315 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7316
7317 if (QTN)
7318 return TemplateName(QTN);
7319
7320 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7321 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007322 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007323 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007324 } else {
7325 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007326 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007327 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007328 DependentTemplateName *CheckQTN =
7329 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7330 assert(!CheckQTN && "Dependent type name canonicalization broken");
7331 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007332 }
7333
7334 DependentTemplateNames.InsertNode(QTN, InsertPos);
7335 return TemplateName(QTN);
7336}
7337
Douglas Gregor71395fa2009-11-04 00:56:37 +00007338/// \brief Retrieve the template name that represents a dependent
7339/// template name such as \c MetaFun::template operator+.
7340TemplateName
7341ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007342 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007343 assert((!NNS || NNS->isDependent()) &&
7344 "Nested name specifier must be dependent");
7345
7346 llvm::FoldingSetNodeID ID;
7347 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007348
7349 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007350 DependentTemplateName *QTN
7351 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007352
7353 if (QTN)
7354 return TemplateName(QTN);
7355
7356 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7357 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007358 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007359 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007360 } else {
7361 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007362 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007363 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007364
Douglas Gregorc42075a2010-02-04 18:10:26 +00007365 DependentTemplateName *CheckQTN
7366 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7367 assert(!CheckQTN && "Dependent template name canonicalization broken");
7368 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007369 }
7370
7371 DependentTemplateNames.InsertNode(QTN, InsertPos);
7372 return TemplateName(QTN);
7373}
7374
Douglas Gregor5590be02011-01-15 06:45:20 +00007375TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007376ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7377 TemplateName replacement) const {
7378 llvm::FoldingSetNodeID ID;
7379 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007380
7381 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007382 SubstTemplateTemplateParmStorage *subst
7383 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7384
7385 if (!subst) {
7386 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7387 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7388 }
7389
7390 return TemplateName(subst);
7391}
7392
7393TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007394ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7395 const TemplateArgument &ArgPack) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007396 auto &Self = const_cast<ASTContext &>(*this);
Douglas Gregor5590be02011-01-15 06:45:20 +00007397 llvm::FoldingSetNodeID ID;
7398 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007399
7400 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007401 SubstTemplateTemplateParmPackStorage *Subst
7402 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7403
7404 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00007405 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007406 ArgPack.pack_size(),
7407 ArgPack.pack_begin());
7408 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7409 }
7410
7411 return TemplateName(Subst);
7412}
7413
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007414/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007415/// TargetInfo, produce the corresponding type. The unsigned @p Type
7416/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007417CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007418 switch (Type) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007419 case TargetInfo::NoInt: return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007420 case TargetInfo::SignedChar: return SignedCharTy;
7421 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007422 case TargetInfo::SignedShort: return ShortTy;
7423 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7424 case TargetInfo::SignedInt: return IntTy;
7425 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7426 case TargetInfo::SignedLong: return LongTy;
7427 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7428 case TargetInfo::SignedLongLong: return LongLongTy;
7429 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7430 }
7431
David Blaikie83d382b2011-09-23 05:06:16 +00007432 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007433}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007434
7435//===----------------------------------------------------------------------===//
7436// Type Predicates.
7437//===----------------------------------------------------------------------===//
7438
Fariborz Jahanian96207692009-02-18 21:49:28 +00007439/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7440/// garbage collection attribute.
7441///
John McCall553d45a2011-01-12 00:34:59 +00007442Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007443 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007444 return Qualifiers::GCNone;
7445
David Blaikiebbafb8a2012-03-11 07:00:24 +00007446 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00007447 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7448
7449 // Default behaviour under objective-C's gc is for ObjC pointers
7450 // (or pointers to them) be treated as though they were declared
7451 // as __strong.
7452 if (GCAttrs == Qualifiers::GCNone) {
7453 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7454 return Qualifiers::Strong;
7455 else if (Ty->isPointerType())
7456 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7457 } else {
7458 // It's not valid to set GC attributes on anything that isn't a
7459 // pointer.
7460#ifndef NDEBUG
7461 QualType CT = Ty->getCanonicalTypeInternal();
Eugene Zelenko7855e772018-04-03 00:11:50 +00007462 while (const auto *AT = dyn_cast<ArrayType>(CT))
John McCall553d45a2011-01-12 00:34:59 +00007463 CT = AT->getElementType();
7464 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7465#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007466 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007467 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007468}
7469
Chris Lattner49af6a42008-04-07 06:51:04 +00007470//===----------------------------------------------------------------------===//
7471// Type Compatibility Testing
7472//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007473
Mike Stump11289f42009-09-09 15:08:12 +00007474/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007475/// compatible.
7476static bool areCompatVectorTypes(const VectorType *LHS,
7477 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007478 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007479 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007480 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007481}
7482
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007483bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7484 QualType SecondVec) {
7485 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7486 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7487
7488 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7489 return true;
7490
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007491 // Treat Neon vector types and most AltiVec vector types as if they are the
7492 // equivalent GCC vector types.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007493 const auto *First = FirstVec->getAs<VectorType>();
7494 const auto *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007495 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007496 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007497 First->getVectorKind() != VectorType::AltiVecPixel &&
7498 First->getVectorKind() != VectorType::AltiVecBool &&
7499 Second->getVectorKind() != VectorType::AltiVecPixel &&
7500 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007501 return true;
7502
7503 return false;
7504}
7505
Steve Naroff8e6aee52009-07-23 01:01:38 +00007506//===----------------------------------------------------------------------===//
7507// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7508//===----------------------------------------------------------------------===//
7509
7510/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7511/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007512bool
7513ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7514 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007515 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007516 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007517 for (auto *PI : rProto->protocols())
7518 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007519 return true;
7520 return false;
7521}
7522
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007523/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7524/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007525bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7526 QualType rhs) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007527 const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7528 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007529 assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007530
Aaron Ballman83731462014-03-17 16:14:00 +00007531 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007532 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007533 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007534 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7535 match = true;
7536 break;
7537 }
7538 }
7539 if (!match)
7540 return false;
7541 }
7542 return true;
7543}
7544
Steve Naroff8e6aee52009-07-23 01:01:38 +00007545/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7546/// ObjCQualifiedIDType.
7547bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7548 bool compare) {
7549 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007550 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007551 lhs->isObjCIdType() || lhs->isObjCClassType())
7552 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007553 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007554 rhs->isObjCIdType() || rhs->isObjCClassType())
7555 return true;
7556
7557 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007558 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007559
Steve Naroff8e6aee52009-07-23 01:01:38 +00007560 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007561
Steve Naroff8e6aee52009-07-23 01:01:38 +00007562 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007563 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007564 // make sure we check the class hierarchy.
7565 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007566 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007567 // when comparing an id<P> on lhs with a static type on rhs,
7568 // see if static class implements all of id's protocols, directly or
7569 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007570 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007571 return false;
7572 }
7573 }
7574 // If there are no qualifiers and no interface, we have an 'id'.
7575 return true;
7576 }
Mike Stump11289f42009-09-09 15:08:12 +00007577 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007578 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007579 bool match = false;
7580
7581 // when comparing an id<P> on lhs with a static type on rhs,
7582 // see if static class implements all of id's protocols, directly or
7583 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007584 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007585 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7586 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7587 match = true;
7588 break;
7589 }
7590 }
Mike Stump11289f42009-09-09 15:08:12 +00007591 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007592 // make sure we check the class hierarchy.
7593 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007594 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007595 // when comparing an id<P> on lhs with a static type on rhs,
7596 // see if static class implements all of id's protocols, directly or
7597 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007598 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007599 match = true;
7600 break;
7601 }
7602 }
7603 }
7604 if (!match)
7605 return false;
7606 }
Mike Stump11289f42009-09-09 15:08:12 +00007607
Steve Naroff8e6aee52009-07-23 01:01:38 +00007608 return true;
7609 }
Mike Stump11289f42009-09-09 15:08:12 +00007610
Steve Naroff8e6aee52009-07-23 01:01:38 +00007611 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7612 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7613
Mike Stump11289f42009-09-09 15:08:12 +00007614 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007615 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007616 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007617 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007618 bool match = false;
7619
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007620 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007621 // see if static class implements all of id's protocols, directly or
7622 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007623 // First, lhs protocols in the qualifier list must be found, direct
7624 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007625 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007626 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7627 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7628 match = true;
7629 break;
7630 }
7631 }
7632 if (!match)
7633 return false;
7634 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007635
7636 // Static class's protocols, or its super class or category protocols
7637 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7638 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7639 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7640 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7641 // This is rather dubious but matches gcc's behavior. If lhs has
7642 // no type qualifier and its class has no static protocol(s)
7643 // assume that it is mismatch.
7644 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7645 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007646 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007647 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007648 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007649 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7650 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7651 match = true;
7652 break;
7653 }
7654 }
7655 if (!match)
7656 return false;
7657 }
7658 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007659 return true;
7660 }
7661 return false;
7662}
7663
Eli Friedman47f77112008-08-22 00:56:42 +00007664/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007665/// compatible for assignment from RHS to LHS. This handles validation of any
7666/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007667bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7668 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007669 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7670 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7671
Steve Naroff1329fa02009-07-15 18:40:39 +00007672 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007673 if (LHS->isObjCUnqualifiedIdOrClass() ||
7674 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007675 return true;
7676
Douglas Gregorab209d82015-07-07 03:58:42 +00007677 // Function object that propagates a successful result or handles
7678 // __kindof types.
7679 auto finish = [&](bool succeeded) -> bool {
7680 if (succeeded)
7681 return true;
7682
7683 if (!RHS->isKindOfType())
7684 return false;
7685
7686 // Strip off __kindof and protocol qualifiers, then check whether
7687 // we can assign the other way.
7688 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7689 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7690 };
7691
7692 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7693 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7694 QualType(RHSOPT,0),
7695 false));
7696 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007697
Douglas Gregorab209d82015-07-07 03:58:42 +00007698 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7699 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7700 QualType(RHSOPT,0)));
7701 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007702
John McCall8b07ec22010-05-15 11:32:37 +00007703 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007704 if (LHS->getInterface() && RHS->getInterface()) {
7705 return finish(canAssignObjCInterfaces(LHS, RHS));
7706 }
Mike Stump11289f42009-09-09 15:08:12 +00007707
Steve Naroff8e6aee52009-07-23 01:01:38 +00007708 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007709}
7710
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007711/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00007712/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007713/// arguments in block literals. When passed as arguments, passing 'A*' where
7714/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7715/// not OK. For the return type, the opposite is not OK.
7716bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7717 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007718 const ObjCObjectPointerType *RHSOPT,
7719 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007720
7721 // Function object that propagates a successful result or handles
7722 // __kindof types.
7723 auto finish = [&](bool succeeded) -> bool {
7724 if (succeeded)
7725 return true;
7726
7727 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7728 if (!Expected->isKindOfType())
7729 return false;
7730
7731 // Strip off __kindof and protocol qualifiers, then check whether
7732 // we can assign the other way.
7733 return canAssignObjCInterfacesInBlockPointer(
7734 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7735 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7736 BlockReturnType);
7737 };
7738
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007739 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007740 return true;
7741
7742 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007743 return finish(RHSOPT->isObjCBuiltinType() ||
7744 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007745 }
7746
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007747 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007748 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7749 QualType(RHSOPT,0),
7750 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007751
7752 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7753 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7754 if (LHS && RHS) { // We have 2 user-defined types.
7755 if (LHS != RHS) {
7756 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007757 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007758 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007759 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007760 }
7761 else
7762 return true;
7763 }
7764 return false;
7765}
7766
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007767/// Comparison routine for Objective-C protocols to be used with
7768/// llvm::array_pod_sort.
7769static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7770 ObjCProtocolDecl * const *rhs) {
7771 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007772}
7773
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007774/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007775/// of protocols inherited from two distinct objective-c pointer objects with
7776/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007777/// It is used to build composite qualifier list of the composite type of
7778/// the conditional expression involving two objective-c pointer objects.
7779static
7780void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007781 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007782 const ObjCObjectPointerType *LHSOPT,
7783 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007784 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007785
John McCall8b07ec22010-05-15 11:32:37 +00007786 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7787 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7788 assert(LHS->getInterface() && "LHS must have an interface base");
7789 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007790
7791 // Add all of the protocols for the LHS.
7792 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7793
7794 // Start with the protocol qualifiers.
7795 for (auto proto : LHS->quals()) {
7796 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007797 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007798
7799 // Also add the protocols associated with the LHS interface.
7800 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7801
7802 // Add all of the protocls for the RHS.
7803 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7804
7805 // Start with the protocol qualifiers.
7806 for (auto proto : RHS->quals()) {
7807 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007808 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007809
7810 // Also add the protocols associated with the RHS interface.
7811 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7812
7813 // Compute the intersection of the collected protocol sets.
7814 for (auto proto : LHSProtocolSet) {
7815 if (RHSProtocolSet.count(proto))
7816 IntersectionSet.push_back(proto);
7817 }
7818
7819 // Compute the set of protocols that is implied by either the common type or
7820 // the protocols within the intersection.
7821 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7822 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7823
7824 // Remove any implied protocols from the list of inherited protocols.
7825 if (!ImpliedProtocols.empty()) {
7826 IntersectionSet.erase(
7827 std::remove_if(IntersectionSet.begin(),
7828 IntersectionSet.end(),
7829 [&](ObjCProtocolDecl *proto) -> bool {
7830 return ImpliedProtocols.count(proto) > 0;
7831 }),
7832 IntersectionSet.end());
7833 }
7834
7835 // Sort the remaining protocols by name.
7836 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7837 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007838}
7839
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007840/// Determine whether the first type is a subtype of the second.
7841static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7842 QualType rhs) {
7843 // Common case: two object pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007844 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7845 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007846 if (lhsOPT && rhsOPT)
7847 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7848
7849 // Two block pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007850 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
7851 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007852 if (lhsBlock && rhsBlock)
7853 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7854
7855 // If either is an unqualified 'id' and the other is a block, it's
7856 // acceptable.
7857 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7858 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7859 return true;
7860
7861 return false;
7862}
7863
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007864// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007865static bool sameObjCTypeArgs(ASTContext &ctx,
7866 const ObjCInterfaceDecl *iface,
7867 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007868 ArrayRef<QualType> rhsArgs,
7869 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007870 if (lhsArgs.size() != rhsArgs.size())
7871 return false;
7872
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007873 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007874 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007875 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7876 continue;
7877
7878 switch (typeParams->begin()[i]->getVariance()) {
7879 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007880 if (!stripKindOf ||
7881 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7882 rhsArgs[i].stripObjCKindOfType(ctx))) {
7883 return false;
7884 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007885 break;
7886
7887 case ObjCTypeParamVariance::Covariant:
7888 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7889 return false;
7890 break;
7891
7892 case ObjCTypeParamVariance::Contravariant:
7893 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7894 return false;
7895 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007896 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007897 }
7898
7899 return true;
7900}
7901
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007902QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007903 const ObjCObjectPointerType *Lptr,
7904 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007905 const ObjCObjectType *LHS = Lptr->getObjectType();
7906 const ObjCObjectType *RHS = Rptr->getObjectType();
7907 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7908 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007909
7910 if (!LDecl || !RDecl)
Eugene Zelenko7855e772018-04-03 00:11:50 +00007911 return {};
Douglas Gregore83b9562015-07-07 03:57:53 +00007912
Manman Renc46f7d12016-05-06 19:35:02 +00007913 // When either LHS or RHS is a kindof type, we should return a kindof type.
7914 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7915 // kindof(A).
7916 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7917
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007918 // Follow the left-hand side up the class hierarchy until we either hit a
7919 // root or find the RHS. Record the ancestors in case we don't find it.
7920 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7921 LHSAncestors;
7922 while (true) {
7923 // Record this ancestor. We'll need this if the common type isn't in the
7924 // path from the LHS to the root.
7925 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007926
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007927 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7928 // Get the type arguments.
7929 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7930 bool anyChanges = false;
7931 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7932 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007933 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7934 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007935 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00007936 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007937 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7938 // If only one has type arguments, the result will not have type
7939 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007940 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007941 anyChanges = true;
7942 }
7943
7944 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007945 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007946 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7947 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007948 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007949 anyChanges = true;
7950
7951 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007952 // If we need to return a kindof type but LHS is not a kindof type, we
7953 // build a new result type.
7954 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007955 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007956 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007957 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007958 return getObjCObjectPointerType(Result);
7959 }
7960
7961 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007962 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007963
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007964 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007965 QualType LHSSuperType = LHS->getSuperClassType();
7966 if (LHSSuperType.isNull())
7967 break;
7968
7969 LHS = LHSSuperType->castAs<ObjCObjectType>();
7970 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007971
7972 // We didn't find anything by following the LHS to its root; now check
7973 // the RHS against the cached set of ancestors.
7974 while (true) {
7975 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7976 if (KnownLHS != LHSAncestors.end()) {
7977 LHS = KnownLHS->second;
7978
7979 // Get the type arguments.
7980 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7981 bool anyChanges = false;
7982 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7983 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007984 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7985 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007986 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00007987 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007988 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7989 // If only one has type arguments, the result will not have type
7990 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007991 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007992 anyChanges = true;
7993 }
7994
7995 // Compute the intersection of protocols.
7996 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7997 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7998 Protocols);
7999 if (!Protocols.empty())
8000 anyChanges = true;
8001
Manman Renc46f7d12016-05-06 19:35:02 +00008002 // If we need to return a kindof type but RHS is not a kindof type, we
8003 // build a new result type.
8004 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008005 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008006 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008007 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008008 return getObjCObjectPointerType(Result);
8009 }
8010
8011 return getObjCObjectPointerType(QualType(RHS, 0));
8012 }
8013
8014 // Find the superclass of the RHS.
8015 QualType RHSSuperType = RHS->getSuperClassType();
8016 if (RHSSuperType.isNull())
8017 break;
8018
8019 RHS = RHSSuperType->castAs<ObjCObjectType>();
8020 }
8021
Eugene Zelenko7855e772018-04-03 00:11:50 +00008022 return {};
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008023}
8024
John McCall8b07ec22010-05-15 11:32:37 +00008025bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8026 const ObjCObjectType *RHS) {
8027 assert(LHS->getInterface() && "LHS is not an interface type");
8028 assert(RHS->getInterface() && "RHS is not an interface type");
8029
Chris Lattner49af6a42008-04-07 06:51:04 +00008030 // Verify that the base decls are compatible: the RHS must be a subclass of
8031 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008032 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8033 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8034 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008035 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008036
Douglas Gregore83b9562015-07-07 03:57:53 +00008037 // If the LHS has protocol qualifiers, determine whether all of them are
8038 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8039 // LHS).
8040 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008041 // OK if conversion of LHS to SuperClass results in narrowing of types
8042 // ; i.e., SuperClass may implement at least one of the protocols
8043 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8044 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8045 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8046 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8047 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8048 // qualifiers.
8049 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008050 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008051 // If there is no protocols associated with RHS, it is not a match.
8052 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008053 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008054
8055 for (const auto *LHSProto : LHS->quals()) {
8056 bool SuperImplementsProtocol = false;
8057 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8058 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8059 SuperImplementsProtocol = true;
8060 break;
8061 }
8062 if (!SuperImplementsProtocol)
8063 return false;
8064 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008065 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008066
8067 // If the LHS is specialized, we may need to check type arguments.
8068 if (LHS->isSpecialized()) {
8069 // Follow the superclass chain until we've matched the LHS class in the
8070 // hierarchy. This substitutes type arguments through.
8071 const ObjCObjectType *RHSSuper = RHS;
8072 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8073 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8074
8075 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008076 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008077 !sameObjCTypeArgs(*this, LHS->getInterface(),
8078 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008079 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008080 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008081 }
8082 }
8083
8084 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008085}
8086
Steve Naroffb7605152009-02-12 17:52:19 +00008087bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8088 // get the "pointed to" types
Eugene Zelenko7855e772018-04-03 00:11:50 +00008089 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8090 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008091
Steve Naroff7cae42b2009-07-10 23:34:53 +00008092 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008093 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008094
8095 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8096 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008097}
8098
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008099bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8100 return canAssignObjCInterfaces(
8101 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8102 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8103}
8104
Mike Stump11289f42009-09-09 15:08:12 +00008105/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008106/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008107/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008108/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008109bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8110 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008111 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008112 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008113
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008114 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008115}
8116
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008117bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008118 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008119}
8120
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008121bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8122 return !mergeTypes(LHS, RHS, true).isNull();
8123}
8124
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008125/// mergeTransparentUnionType - if T is a transparent union type and a member
8126/// of T is compatible with SubType, return the merged type, else return
8127/// QualType()
8128QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8129 bool OfBlockPointer,
8130 bool Unqualified) {
8131 if (const RecordType *UT = T->getAsUnionType()) {
8132 RecordDecl *UD = UT->getDecl();
8133 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008134 for (const auto *I : UD->fields()) {
8135 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008136 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8137 if (!MT.isNull())
8138 return MT;
8139 }
8140 }
8141 }
8142
Eugene Zelenko7855e772018-04-03 00:11:50 +00008143 return {};
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008144}
8145
Alp Toker9cacbab2014-01-20 20:26:09 +00008146/// mergeFunctionParameterTypes - merge two types which appear as function
8147/// parameter types
8148QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8149 bool OfBlockPointer,
8150 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008151 // GNU extension: two types are compatible if they appear as a function
8152 // argument, one of the types is a transparent union type and the other
8153 // type is compatible with a union member
8154 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8155 Unqualified);
8156 if (!lmerge.isNull())
8157 return lmerge;
8158
8159 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8160 Unqualified);
8161 if (!rmerge.isNull())
8162 return rmerge;
8163
8164 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8165}
8166
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008167QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008168 bool OfBlockPointer,
8169 bool Unqualified) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008170 const auto *lbase = lhs->getAs<FunctionType>();
8171 const auto *rbase = rhs->getAs<FunctionType>();
8172 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8173 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008174 bool allLTypes = true;
8175 bool allRTypes = true;
8176
8177 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008178 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008179 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008180 QualType RHS = rbase->getReturnType();
8181 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008182 bool UnqualifiedResult = Unqualified;
8183 if (!UnqualifiedResult)
8184 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008185 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008186 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008187 else
Alp Toker314cc812014-01-25 16:55:45 +00008188 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008189 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008190 if (retType.isNull())
8191 return {};
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008192
8193 if (Unqualified)
8194 retType = retType.getUnqualifiedType();
8195
Alp Toker314cc812014-01-25 16:55:45 +00008196 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8197 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008198 if (Unqualified) {
8199 LRetType = LRetType.getUnqualifiedType();
8200 RRetType = RRetType.getUnqualifiedType();
8201 }
8202
8203 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008204 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008205 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008206 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008207
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008208 // FIXME: double check this
8209 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8210 // rbase->getRegParmAttr() != 0 &&
8211 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008212 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8213 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008214
Douglas Gregor8c940862010-01-18 17:14:39 +00008215 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008216 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008217 return {};
Mike Stump11289f42009-09-09 15:08:12 +00008218
John McCall8c6b56f2010-12-15 01:06:38 +00008219 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008220 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008221 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008222 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008223 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008224
John McCall31168b02011-06-15 23:02:42 +00008225 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008226 return {};
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008227 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008228 return {};
Oren Ben Simhon220671a2018-03-17 13:31:35 +00008229 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008230 return {};
John McCall31168b02011-06-15 23:02:42 +00008231
John McCall8c6b56f2010-12-15 01:06:38 +00008232 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8233 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008234
Rafael Espindola8778c282012-11-29 16:09:03 +00008235 if (lbaseInfo.getNoReturn() != NoReturn)
8236 allLTypes = false;
8237 if (rbaseInfo.getNoReturn() != NoReturn)
8238 allRTypes = false;
8239
John McCall31168b02011-06-15 23:02:42 +00008240 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008241
Eli Friedman47f77112008-08-22 00:56:42 +00008242 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008243 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8244 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008245 // Compatible functions must have the same number of parameters
8246 if (lproto->getNumParams() != rproto->getNumParams())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008247 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008248
8249 // Variadic and non-variadic functions aren't compatible
8250 if (lproto->isVariadic() != rproto->isVariadic())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008251 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008252
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008253 if (lproto->getTypeQuals() != rproto->getTypeQuals())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008254 return {};
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008255
Akira Hatanaka98a49332017-09-22 00:41:05 +00008256 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8257 bool canUseLeft, canUseRight;
8258 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8259 newParamInfos))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008260 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008261
Akira Hatanaka98a49332017-09-22 00:41:05 +00008262 if (!canUseLeft)
8263 allLTypes = false;
8264 if (!canUseRight)
8265 allRTypes = false;
8266
Alp Toker601b22c2014-01-21 23:35:24 +00008267 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008268 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008269 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8270 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8271 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8272 QualType paramType = mergeFunctionParameterTypes(
8273 lParamType, rParamType, OfBlockPointer, Unqualified);
8274 if (paramType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008275 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008276
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008277 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008278 paramType = paramType.getUnqualifiedType();
8279
8280 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008281 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008282 lParamType = lParamType.getUnqualifiedType();
8283 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008284 }
Alp Toker601b22c2014-01-21 23:35:24 +00008285
8286 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008287 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008288 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008289 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008290 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00008291
Eli Friedman47f77112008-08-22 00:56:42 +00008292 if (allLTypes) return lhs;
8293 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008294
8295 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8296 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008297 EPI.ExtParameterInfos =
8298 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008299 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008300 }
8301
8302 if (lproto) allRTypes = false;
8303 if (rproto) allLTypes = false;
8304
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008305 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008306 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008307 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008308 if (proto->isVariadic())
8309 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008310 // Check that the types are compatible with the types that
8311 // would result from default argument promotions (C99 6.7.5.3p15).
8312 // The only types actually affected are promotable integer
8313 // types and floats, which would be passed as a different
8314 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008315 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8316 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008317
Eli Friedman448ce402012-08-30 00:44:15 +00008318 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008319 // to pass enum values.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008320 if (const auto *Enum = paramTy->getAs<EnumType>()) {
Alp Toker601b22c2014-01-21 23:35:24 +00008321 paramTy = Enum->getDecl()->getIntegerType();
8322 if (paramTy.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008323 return {};
Eli Friedman448ce402012-08-30 00:44:15 +00008324 }
Alp Toker601b22c2014-01-21 23:35:24 +00008325
8326 if (paramTy->isPromotableIntegerType() ||
8327 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008328 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008329 }
8330
8331 if (allLTypes) return lhs;
8332 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008333
8334 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8335 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008336 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008337 }
8338
8339 if (allLTypes) return lhs;
8340 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008341 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008342}
8343
John McCall433c2e62013-03-21 00:10:07 +00008344/// Given that we have an enum type and a non-enum type, try to merge them.
8345static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8346 QualType other, bool isBlockReturnType) {
8347 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8348 // a signed integer type, or an unsigned integer type.
8349 // Compatibility is based on the underlying type, not the promotion
8350 // type.
8351 QualType underlyingType = ET->getDecl()->getIntegerType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00008352 if (underlyingType.isNull())
8353 return {};
John McCall433c2e62013-03-21 00:10:07 +00008354 if (Context.hasSameType(underlyingType, other))
8355 return other;
8356
8357 // In block return types, we're more permissive and accept any
8358 // integral type of the same size.
8359 if (isBlockReturnType && other->isIntegerType() &&
8360 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8361 return other;
8362
Eugene Zelenko7855e772018-04-03 00:11:50 +00008363 return {};
John McCall433c2e62013-03-21 00:10:07 +00008364}
8365
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008366QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008367 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008368 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008369 // C++ [expr]: If an expression initially has the type "reference to T", the
8370 // type is adjusted to "T" prior to any further analysis, the expression
8371 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008372 // expression is an lvalue unless the reference is an rvalue reference and
8373 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008374 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8375 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008376
8377 if (Unqualified) {
8378 LHS = LHS.getUnqualifiedType();
8379 RHS = RHS.getUnqualifiedType();
8380 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00008381
Eli Friedman47f77112008-08-22 00:56:42 +00008382 QualType LHSCan = getCanonicalType(LHS),
8383 RHSCan = getCanonicalType(RHS);
8384
8385 // If two types are identical, they are compatible.
8386 if (LHSCan == RHSCan)
8387 return LHS;
8388
John McCall8ccfcb52009-09-24 19:53:00 +00008389 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008390 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8391 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008392 if (LQuals != RQuals) {
8393 // If any of these qualifiers are different, we have a type
8394 // mismatch.
8395 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008396 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008397 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8398 LQuals.hasUnaligned() != RQuals.hasUnaligned())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008399 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008400
8401 // Exactly one GC qualifier difference is allowed: __strong is
8402 // okay if the other type has no GC qualifier but is an Objective
8403 // C object pointer (i.e. implicitly strong by default). We fix
8404 // this by pretending that the unqualified type was actually
8405 // qualified __strong.
8406 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8407 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8408 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8409
8410 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008411 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008412
8413 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8414 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8415 }
8416 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8417 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8418 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008419 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008420 }
8421
8422 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008423
Eli Friedmandcca6332009-06-01 01:22:52 +00008424 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8425 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008426
Chris Lattnerfd652912008-01-14 05:45:46 +00008427 // We want to consider the two function types to be the same for these
8428 // comparisons, just force one to the other.
8429 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8430 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008431
8432 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008433 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8434 LHSClass = Type::ConstantArray;
8435 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8436 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008437
John McCall8b07ec22010-05-15 11:32:37 +00008438 // ObjCInterfaces are just specialized ObjCObjects.
8439 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8440 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8441
Nate Begemance4d7fc2008-04-18 23:10:10 +00008442 // Canonicalize ExtVector -> Vector.
8443 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8444 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008445
Chris Lattner95554662008-04-07 05:43:21 +00008446 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008447 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008448 // Note that we only have special rules for turning block enum
8449 // returns into block int returns, not vice-versa.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008450 if (const auto *ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008451 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008452 }
John McCall9dd450b2009-09-21 23:43:11 +00008453 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008454 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008455 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008456 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008457 if (OfBlockPointer && !BlockReturnType) {
8458 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8459 return LHS;
8460 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8461 return RHS;
8462 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008463
Eugene Zelenko7855e772018-04-03 00:11:50 +00008464 return {};
Steve Naroff32e44c02007-10-15 20:41:53 +00008465 }
Eli Friedman47f77112008-08-22 00:56:42 +00008466
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008467 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008468 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008469#define TYPE(Class, Base)
8470#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008471#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008472#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8473#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8474#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008475 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008476
Richard Smith27d807c2013-04-30 13:56:41 +00008477 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008478 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008479 case Type::LValueReference:
8480 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008481 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008482 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008483
John McCall8b07ec22010-05-15 11:32:37 +00008484 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008485 case Type::IncompleteArray:
8486 case Type::VariableArray:
8487 case Type::FunctionProto:
8488 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008489 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008490
Chris Lattnerfd652912008-01-14 05:45:46 +00008491 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008492 {
8493 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008494 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8495 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008496 if (Unqualified) {
8497 LHSPointee = LHSPointee.getUnqualifiedType();
8498 RHSPointee = RHSPointee.getUnqualifiedType();
8499 }
8500 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8501 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008502 if (ResultType.isNull())
8503 return {};
Eli Friedman091a9ac2009-06-02 05:28:56 +00008504 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008505 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008506 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008507 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008508 return getPointerType(ResultType);
8509 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008510 case Type::BlockPointer:
8511 {
8512 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008513 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8514 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008515 if (Unqualified) {
8516 LHSPointee = LHSPointee.getUnqualifiedType();
8517 RHSPointee = RHSPointee.getUnqualifiedType();
8518 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008519 if (getLangOpts().OpenCL) {
8520 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8521 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8522 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8523 // 6.12.5) thus the following check is asymmetric.
8524 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008525 return {};
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008526 LHSPteeQual.removeAddressSpace();
8527 RHSPteeQual.removeAddressSpace();
8528 LHSPointee =
8529 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8530 RHSPointee =
8531 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8532 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008533 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8534 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008535 if (ResultType.isNull())
8536 return {};
Steve Naroff68e167d2008-12-10 17:49:55 +00008537 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8538 return LHS;
8539 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8540 return RHS;
8541 return getBlockPointerType(ResultType);
8542 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008543 case Type::Atomic:
8544 {
8545 // Merge two pointer types, while trying to preserve typedef info
8546 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8547 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8548 if (Unqualified) {
8549 LHSValue = LHSValue.getUnqualifiedType();
8550 RHSValue = RHSValue.getUnqualifiedType();
8551 }
8552 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8553 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008554 if (ResultType.isNull())
8555 return {};
Eli Friedman0dfb8892011-10-06 23:00:33 +00008556 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8557 return LHS;
8558 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8559 return RHS;
8560 return getAtomicType(ResultType);
8561 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008562 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008563 {
8564 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8565 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8566 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008567 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008568
8569 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8570 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008571 if (Unqualified) {
8572 LHSElem = LHSElem.getUnqualifiedType();
8573 RHSElem = RHSElem.getUnqualifiedType();
8574 }
8575
8576 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008577 if (ResultType.isNull())
8578 return {};
Chris Lattner465fa322008-10-05 17:34:18 +00008579 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8580 return LHS;
8581 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8582 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008583 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8584 ArrayType::ArraySizeModifier(), 0);
8585 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8586 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008587 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8588 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00008589 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8590 return LHS;
8591 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8592 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008593 if (LVAT) {
8594 // FIXME: This isn't correct! But tricky to implement because
8595 // the array's size has to be the size of LHS, but the type
8596 // has to be different.
8597 return LHS;
8598 }
8599 if (RVAT) {
8600 // FIXME: This isn't correct! But tricky to implement because
8601 // the array's size has to be the size of RHS, but the type
8602 // has to be different.
8603 return RHS;
8604 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008605 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8606 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008607 return getIncompleteArrayType(ResultType,
8608 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008609 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008610 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008611 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008612 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008613 case Type::Enum:
Eugene Zelenko7855e772018-04-03 00:11:50 +00008614 return {};
Chris Lattnerfd652912008-01-14 05:45:46 +00008615 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008616 // Only exactly equal builtin types are compatible, which is tested above.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008617 return {};
Daniel Dunbar804c0442009-01-28 21:22:12 +00008618 case Type::Complex:
8619 // Distinct complex types are incompatible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008620 return {};
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008621 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008622 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008623 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8624 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008625 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00008626 return {};
John McCall8b07ec22010-05-15 11:32:37 +00008627 case Type::ObjCObject: {
8628 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008629 // FIXME: This should be type compatibility, e.g. whether
8630 // "LHS x; RHS x;" at global scope is legal.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008631 const auto *LHSIface = LHS->getAs<ObjCObjectType>();
8632 const auto *RHSIface = RHS->getAs<ObjCObjectType>();
John McCall8b07ec22010-05-15 11:32:37 +00008633 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008634 return LHS;
8635
Eugene Zelenko7855e772018-04-03 00:11:50 +00008636 return {};
Cedric Venet4fc88b72009-02-21 17:14:49 +00008637 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008638 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008639 if (OfBlockPointer) {
8640 if (canAssignObjCInterfacesInBlockPointer(
8641 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008642 RHS->getAs<ObjCObjectPointerType>(),
8643 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00008644 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00008645 return {};
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008646 }
John McCall9dd450b2009-09-21 23:43:11 +00008647 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8648 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00008649 return LHS;
8650
Eugene Zelenko7855e772018-04-03 00:11:50 +00008651 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00008652 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00008653 assert(LHS != RHS &&
8654 "Equivalent pipe types should have already been handled!");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008655 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00008656 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008657
David Blaikie8a40f702012-01-17 06:56:22 +00008658 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00008659}
Ted Kremenekfc581a92007-10-31 17:10:13 +00008660
Akira Hatanaka98a49332017-09-22 00:41:05 +00008661bool ASTContext::mergeExtParameterInfo(
8662 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
8663 bool &CanUseFirst, bool &CanUseSecond,
8664 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
8665 assert(NewParamInfos.empty() && "param info list not empty");
8666 CanUseFirst = CanUseSecond = true;
8667 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
8668 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
8669
John McCall18afab72016-03-01 00:49:02 +00008670 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00008671 // we match if and only if the second type also doesn't have them.
8672 if (!FirstHasInfo && !SecondHasInfo)
8673 return true;
John McCall18afab72016-03-01 00:49:02 +00008674
Akira Hatanaka98a49332017-09-22 00:41:05 +00008675 bool NeedParamInfo = false;
8676 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
8677 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00008678
Akira Hatanaka98a49332017-09-22 00:41:05 +00008679 for (size_t I = 0; I < E; ++I) {
8680 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
8681 if (FirstHasInfo)
8682 FirstParam = FirstFnType->getExtParameterInfo(I);
8683 if (SecondHasInfo)
8684 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00008685
Akira Hatanaka98a49332017-09-22 00:41:05 +00008686 // Cannot merge unless everything except the noescape flag matches.
8687 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00008688 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008689
8690 bool FirstNoEscape = FirstParam.isNoEscape();
8691 bool SecondNoEscape = SecondParam.isNoEscape();
8692 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
8693 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
8694 if (NewParamInfos.back().getOpaqueValue())
8695 NeedParamInfo = true;
8696 if (FirstNoEscape != IsNoEscape)
8697 CanUseFirst = false;
8698 if (SecondNoEscape != IsNoEscape)
8699 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00008700 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00008701
8702 if (!NeedParamInfo)
8703 NewParamInfos.clear();
8704
Fariborz Jahanian97676972011-09-28 21:52:05 +00008705 return true;
8706}
8707
Chandler Carruth21c90602015-12-30 03:24:14 +00008708void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8709 ObjCLayouts[CD] = nullptr;
8710}
8711
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008712/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8713/// 'RHS' attributes and returns the merged version; including for function
8714/// return types.
8715QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8716 QualType LHSCan = getCanonicalType(LHS),
8717 RHSCan = getCanonicalType(RHS);
8718 // If two types are identical, they are compatible.
8719 if (LHSCan == RHSCan)
8720 return LHS;
8721 if (RHSCan->isFunctionType()) {
8722 if (!LHSCan->isFunctionType())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008723 return {};
Alp Toker314cc812014-01-25 16:55:45 +00008724 QualType OldReturnType =
8725 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008726 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008727 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008728 QualType ResReturnType =
8729 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8730 if (ResReturnType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008731 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008732 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8733 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8734 // In either case, use OldReturnType to build the new function type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008735 const auto *F = LHS->getAs<FunctionType>();
8736 if (const auto *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008737 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8738 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00008739 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00008740 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008741 return ResultType;
8742 }
8743 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008744 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008745 }
8746
8747 // If the qualifiers are different, the types can still be merged.
8748 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8749 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8750 if (LQuals != RQuals) {
8751 // If any of these qualifiers are different, we have a type mismatch.
8752 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8753 LQuals.getAddressSpace() != RQuals.getAddressSpace())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008754 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008755
8756 // Exactly one GC qualifier difference is allowed: __strong is
8757 // okay if the other type has no GC qualifier but is an Objective
8758 // C object pointer (i.e. implicitly strong by default). We fix
8759 // this by pretending that the unqualified type was actually
8760 // qualified __strong.
8761 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8762 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8763 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8764
8765 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008766 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008767
8768 if (GC_L == Qualifiers::Strong)
8769 return LHS;
8770 if (GC_R == Qualifiers::Strong)
8771 return RHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00008772 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008773 }
8774
8775 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8776 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8777 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8778 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8779 if (ResQT == LHSBaseQT)
8780 return LHS;
8781 if (ResQT == RHSBaseQT)
8782 return RHS;
8783 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008784 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008785}
8786
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008787//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008788// Integer Predicates
8789//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008790
Jay Foad39c79802011-01-12 09:06:06 +00008791unsigned ASTContext::getIntWidth(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008792 if (const auto *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008793 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008794 if (T->isBooleanType())
8795 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008796 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008797 return (unsigned)getTypeSize(T);
8798}
8799
Abramo Bagnara13640492012-09-09 10:21:24 +00008800QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008801 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008802
8803 // Turn <4 x signed int> -> <4 x unsigned int>
Eugene Zelenko7855e772018-04-03 00:11:50 +00008804 if (const auto *VTy = T->getAs<VectorType>())
Chris Lattnerec3a1562009-10-17 20:33:28 +00008805 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008806 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008807
8808 // For enums, we return the unsigned version of the base type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008809 if (const auto *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008810 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008811
Eugene Zelenko7855e772018-04-03 00:11:50 +00008812 const auto *BTy = T->getAs<BuiltinType>();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008813 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008814 switch (BTy->getKind()) {
8815 case BuiltinType::Char_S:
8816 case BuiltinType::SChar:
8817 return UnsignedCharTy;
8818 case BuiltinType::Short:
8819 return UnsignedShortTy;
8820 case BuiltinType::Int:
8821 return UnsignedIntTy;
8822 case BuiltinType::Long:
8823 return UnsignedLongTy;
8824 case BuiltinType::LongLong:
8825 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008826 case BuiltinType::Int128:
8827 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008828 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008829 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008830 }
8831}
8832
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008833ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008834
Richard Smith1fa5d642013-05-11 05:45:24 +00008835void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8836 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008837
8838//===----------------------------------------------------------------------===//
8839// Builtin Type Computation
8840//===----------------------------------------------------------------------===//
8841
8842/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008843/// pointer over the consumed characters. This returns the resultant type. If
8844/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8845/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8846/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008847///
8848/// RequiresICE is filled in on return to indicate whether the value is required
8849/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008850static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008851 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00008852 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008853 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008854 // Modifiers.
8855 int HowLong = 0;
8856 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008857 RequiresICE = false;
Chandler Carruth45bbe012017-03-24 09:11:57 +00008858
Chris Lattnerdc226c22010-10-01 22:42:38 +00008859 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00008860 bool Done = false;
8861 #ifndef NDEBUG
8862 bool IsSpecialLong = false;
8863 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00008864 while (!Done) {
8865 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008866 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008867 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008868 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008869 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008870 case 'S':
8871 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8872 assert(!Signed && "Can't use 'S' modifier multiple times!");
8873 Signed = true;
8874 break;
8875 case 'U':
8876 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008877 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008878 Unsigned = true;
8879 break;
8880 case 'L':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008881 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008882 assert(HowLong <= 2 && "Can't have LLLL modifier");
8883 ++HowLong;
8884 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008885 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008886 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
8887 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
8888 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00008889 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008890 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00008891 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008892 if (Context.getTargetInfo().getLongWidth() == 32)
8893 ++HowLong;
8894 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00008895 case 'W':
8896 // This modifier represents int64 type.
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008897 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00008898 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00008899 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008900 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00008901 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00008902 switch (Context.getTargetInfo().getInt64Type()) {
8903 default:
8904 llvm_unreachable("Unexpected integer type");
8905 case TargetInfo::SignedLong:
8906 HowLong = 1;
8907 break;
8908 case TargetInfo::SignedLongLong:
8909 HowLong = 2;
8910 break;
8911 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00008912 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008913 }
8914 }
8915
8916 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008917
Chris Lattnerecd79c62009-06-14 00:45:47 +00008918 // Read the base type.
8919 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008920 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008921 case 'v':
8922 assert(HowLong == 0 && !Signed && !Unsigned &&
8923 "Bad modifiers used with 'v'!");
8924 Type = Context.VoidTy;
8925 break;
Jack Carter24bef982013-08-15 15:16:57 +00008926 case 'h':
8927 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008928 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008929 Type = Context.HalfTy;
8930 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008931 case 'f':
8932 assert(HowLong == 0 && !Signed && !Unsigned &&
8933 "Bad modifiers used with 'f'!");
8934 Type = Context.FloatTy;
8935 break;
8936 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00008937 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00008938 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00008939 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00008940 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00008941 else if (HowLong == 2)
8942 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008943 else
8944 Type = Context.DoubleTy;
8945 break;
8946 case 's':
8947 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8948 if (Unsigned)
8949 Type = Context.UnsignedShortTy;
8950 else
8951 Type = Context.ShortTy;
8952 break;
8953 case 'i':
8954 if (HowLong == 3)
8955 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8956 else if (HowLong == 2)
8957 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8958 else if (HowLong == 1)
8959 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8960 else
8961 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8962 break;
8963 case 'c':
8964 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8965 if (Signed)
8966 Type = Context.SignedCharTy;
8967 else if (Unsigned)
8968 Type = Context.UnsignedCharTy;
8969 else
8970 Type = Context.CharTy;
8971 break;
8972 case 'b': // boolean
8973 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8974 Type = Context.BoolTy;
8975 break;
8976 case 'z': // size_t.
8977 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8978 Type = Context.getSizeType();
8979 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00008980 case 'w': // wchar_t.
8981 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
8982 Type = Context.getWideCharType();
8983 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008984 case 'F':
8985 Type = Context.getCFConstantStringType();
8986 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008987 case 'G':
8988 Type = Context.getObjCIdType();
8989 break;
8990 case 'H':
8991 Type = Context.getObjCSelType();
8992 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008993 case 'M':
8994 Type = Context.getObjCSuperType();
8995 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008996 case 'a':
8997 Type = Context.getBuiltinVaListType();
8998 assert(!Type.isNull() && "builtin va list type not initialized!");
8999 break;
9000 case 'A':
9001 // This is a "reference" to a va_list; however, what exactly
9002 // this means depends on how va_list is defined. There are two
9003 // different kinds of va_list: ones passed by value, and ones
9004 // passed by reference. An example of a by-value va_list is
9005 // x86, where va_list is a char*. An example of by-ref va_list
9006 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9007 // we want this argument to be a char*&; for x86-64, we want
9008 // it to be a __va_list_tag*.
9009 Type = Context.getBuiltinVaListType();
9010 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009011 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009012 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009013 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009014 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009015 break;
9016 case 'V': {
9017 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009018 unsigned NumElements = strtoul(Str, &End, 10);
9019 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009020 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009021
Chandler Carruth45bbe012017-03-24 09:11:57 +00009022 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
9023 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009024 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00009025
9026 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009027 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009028 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009029 break;
9030 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009031 case 'E': {
9032 char *End;
9033
9034 unsigned NumElements = strtoul(Str, &End, 10);
9035 assert(End != Str && "Missing vector size");
9036
9037 Str = End;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009038
Douglas Gregorfed66992012-06-07 18:08:25 +00009039 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009040 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009041 Type = Context.getExtVectorType(ElementType, NumElements);
9042 break;
9043 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009044 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009045 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009046 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009047 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009048 Type = Context.getComplexType(ElementType);
9049 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009050 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009051 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009052 Type = Context.getPointerDiffType();
9053 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009054 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009055 Type = Context.getFILEType();
9056 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009057 Error = ASTContext::GE_Missing_stdio;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009058 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009059 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009060 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009061 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009062 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009063 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009064 else
9065 Type = Context.getjmp_bufType();
9066
Mike Stump2adb4da2009-07-28 23:47:15 +00009067 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009068 Error = ASTContext::GE_Missing_setjmp;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009069 return {};
Mike Stump2adb4da2009-07-28 23:47:15 +00009070 }
9071 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009072 case 'K':
9073 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9074 Type = Context.getucontext_tType();
9075
9076 if (Type.isNull()) {
9077 Error = ASTContext::GE_Missing_ucontext;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009078 return {};
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009079 }
9080 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009081 case 'p':
9082 Type = Context.getProcessIDType();
9083 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009084 }
Mike Stump11289f42009-09-09 15:08:12 +00009085
Chris Lattnerdc226c22010-10-01 22:42:38 +00009086 // If there are modifiers and if we're allowed to parse them, go for it.
9087 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009088 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009089 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009090 default: Done = true; --Str; break;
9091 case '*':
9092 case '&': {
9093 // Both pointers and references can have their pointee types
9094 // qualified with an address space.
9095 char *End;
9096 unsigned AddrSpace = strtoul(Str, &End, 10);
9097 if (End != Str && AddrSpace != 0) {
Alexander Richardson6d989432017-10-15 18:48:14 +00009098 Type = Context.getAddrSpaceQualType(Type,
9099 getLangASFromTargetAS(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009100 Str = End;
9101 }
9102 if (c == '*')
9103 Type = Context.getPointerType(Type);
9104 else
9105 Type = Context.getLValueReferenceType(Type);
9106 break;
9107 }
9108 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9109 case 'C':
9110 Type = Type.withConst();
9111 break;
9112 case 'D':
9113 Type = Context.getVolatileType(Type);
9114 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009115 case 'R':
9116 Type = Type.withRestrict();
9117 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009118 }
9119 }
Chris Lattner84733392010-10-01 07:13:18 +00009120
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009121 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00009122 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009123
Chris Lattnerecd79c62009-06-14 00:45:47 +00009124 return Type;
9125}
9126
9127/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009128QualType ASTContext::GetBuiltinType(unsigned Id,
9129 GetBuiltinTypeError &Error,
9130 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009131 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00009132
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009133 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009134
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009135 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009136 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009137 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9138 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009139 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009140 return {};
Chandler Carruth45bbe012017-03-24 09:11:57 +00009141
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009142 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Chandler Carruth45bbe012017-03-24 09:11:57 +00009143
Chris Lattnerecd79c62009-06-14 00:45:47 +00009144 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009145 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009146 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009147 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009148
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009149 // If this argument is required to be an IntegerConstantExpression and the
9150 // caller cares, fill in the bitmask we return.
9151 if (RequiresICE && IntegerConstantArgs)
9152 *IntegerConstantArgs |= 1 << ArgTypes.size();
9153
Chris Lattnerecd79c62009-06-14 00:45:47 +00009154 // Do array -> pointer decay. The builtin should use the decayed type.
9155 if (Ty->isArrayType())
9156 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009157
Chris Lattnerecd79c62009-06-14 00:45:47 +00009158 ArgTypes.push_back(Ty);
9159 }
9160
David Majnemerba3e5ec2015-03-13 18:26:17 +00009161 if (Id == Builtin::BI__GetExceptionInfo)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009162 return {};
David Majnemerba3e5ec2015-03-13 18:26:17 +00009163
Chris Lattnerecd79c62009-06-14 00:45:47 +00009164 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9165 "'.' should only occur at end of builtin type list!");
9166
Reid Kleckner78af0702013-08-27 23:08:25 +00009167 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00009168 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9169
9170 bool Variadic = (TypeStr[0] == '.');
9171
Richard Smith836de6b2016-12-19 23:59:34 +00009172 // We really shouldn't be making a no-proto type here.
9173 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00009174 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00009175
John McCalldb40c7f2010-12-14 08:05:40 +00009176 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00009177 EPI.ExtInfo = EI;
9178 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00009179 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9180 EPI.ExceptionSpec.Type =
9181 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00009182
Jordan Rose5c382722013-03-08 21:51:21 +00009183 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009184}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00009185
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009186static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9187 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009188 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009189 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009190
Richard Smithe2467b72017-11-16 23:54:56 +00009191 // Non-user-provided functions get emitted as weak definitions with every
9192 // use, no matter whether they've been explicitly instantiated etc.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009193 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
Richard Smithe2467b72017-11-16 23:54:56 +00009194 if (!MD->isUserProvided())
9195 return GVA_DiscardableODR;
9196
Yaron Keren4cd211b2017-02-22 14:32:39 +00009197 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009198 switch (FD->getTemplateSpecializationKind()) {
9199 case TSK_Undeclared:
9200 case TSK_ExplicitSpecialization:
9201 External = GVA_StrongExternal;
9202 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009203
Rafael Espindola3ae00052013-05-13 00:12:11 +00009204 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009205 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009206
David Majnemerc3d07332014-05-15 06:25:57 +00009207 // C++11 [temp.explicit]p10:
9208 // [ Note: The intent is that an inline function that is the subject of
9209 // an explicit instantiation declaration will still be implicitly
9210 // instantiated when used so that the body can be considered for
9211 // inlining, but that no out-of-line copy of the inline function would be
9212 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00009213 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00009214 return GVA_AvailableExternally;
9215
Rafael Espindola3ae00052013-05-13 00:12:11 +00009216 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009217 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009218 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009219 }
9220
9221 if (!FD->isInlined())
9222 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00009223
David Majnemer3f021502015-10-08 04:53:31 +00009224 if ((!Context.getLangOpts().CPlusPlus &&
9225 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009226 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00009227 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009228 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9229
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009230 // GNU or C99 inline semantics. Determine whether this symbol should be
9231 // externally visible.
9232 if (FD->isInlineDefinitionExternallyVisible())
9233 return External;
9234
9235 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00009236 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009237 }
9238
David Majnemer54e3ba52014-04-02 23:17:29 +00009239 // Functions specified with extern and inline in -fms-compatibility mode
9240 // forcibly get emitted. While the body of the function cannot be later
9241 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00009242 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00009243 return GVA_StrongODR;
9244
David Majnemer27d69db2014-04-28 22:17:59 +00009245 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009246}
9247
Artem Belevichca2b9512016-05-02 20:30:03 +00009248static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00009249 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009250 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9251 // dllexport/dllimport on inline functions.
9252 if (D->hasAttr<DLLImportAttr>()) {
9253 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9254 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00009255 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009256 if (L == GVA_DiscardableODR)
9257 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00009258 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9259 D->hasAttr<CUDAGlobalAttr>()) {
9260 // Device-side functions with __global__ attribute must always be
9261 // visible externally so they can be launched from host.
9262 if (L == GVA_DiscardableODR || L == GVA_Internal)
9263 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009264 }
9265 return L;
9266}
9267
Richard Smitha4653622017-09-06 20:01:14 +00009268/// Adjust the GVALinkage for a declaration based on what an external AST source
9269/// knows about whether there can be other definitions of this declaration.
9270static GVALinkage
9271adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9272 GVALinkage L) {
9273 ExternalASTSource *Source = Ctx.getExternalSource();
9274 if (!Source)
9275 return L;
9276
9277 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00009278 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00009279 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009280 if (L == GVA_DiscardableODR)
9281 return GVA_StrongODR;
9282 break;
Richard Smitha4653622017-09-06 20:01:14 +00009283
David Blaikie9ffe5a32017-01-30 05:00:26 +00009284 case ExternalASTSource::EK_Always:
9285 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00009286
David Blaikie9ffe5a32017-01-30 05:00:26 +00009287 case ExternalASTSource::EK_ReplyHazy:
9288 break;
9289 }
9290 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009291}
9292
Richard Smitha4653622017-09-06 20:01:14 +00009293GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9294 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9295 adjustGVALinkageForAttributes(*this, FD,
9296 basicGVALinkageForFunction(*this, FD)));
9297}
9298
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009299static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9300 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009301 if (!VD->isExternallyVisible())
9302 return GVA_Internal;
9303
David Majnemer27d69db2014-04-28 22:17:59 +00009304 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00009305 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9306 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9307 LexicalContext = LexicalContext->getLexicalParent();
9308
David Blaikieeb210012017-01-27 23:11:10 +00009309 // ObjC Blocks can create local variables that don't have a FunctionDecl
9310 // LexicalContext.
9311 if (!LexicalContext)
9312 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00009313
David Blaikieeb210012017-01-27 23:11:10 +00009314 // Otherwise, let the static local variable inherit its linkage from the
9315 // nearest enclosing function.
9316 auto StaticLocalLinkage =
9317 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9318
9319 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9320 // be emitted in any object with references to the symbol for the object it
9321 // contains, whether inline or out-of-line."
9322 // Similar behavior is observed with MSVC. An alternative ABI could use
9323 // StrongODR/AvailableExternally to match the function, but none are
9324 // known/supported currently.
9325 if (StaticLocalLinkage == GVA_StrongODR ||
9326 StaticLocalLinkage == GVA_AvailableExternally)
9327 return GVA_DiscardableODR;
9328 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009329 }
9330
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009331 // MSVC treats in-class initialized static data members as definitions.
9332 // By giving them non-strong linkage, out-of-line definitions won't
9333 // cause link errors.
9334 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9335 return GVA_DiscardableODR;
9336
Richard Smithd9b90092016-07-02 01:32:16 +00009337 // Most non-template variables have strong linkage; inline variables are
9338 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9339 GVALinkage StrongLinkage;
9340 switch (Context.getInlineVariableDefinitionKind(VD)) {
9341 case ASTContext::InlineVariableDefinitionKind::None:
9342 StrongLinkage = GVA_StrongExternal;
9343 break;
9344 case ASTContext::InlineVariableDefinitionKind::Weak:
9345 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009346 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009347 break;
9348 case ASTContext::InlineVariableDefinitionKind::Strong:
9349 StrongLinkage = GVA_StrongODR;
9350 break;
9351 }
Richard Smith62f19e72016-06-25 00:15:56 +00009352
Richard Smith8809a0c2013-09-27 20:14:12 +00009353 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009354 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009355 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009356
David Majnemer6d1780c2015-07-17 23:36:49 +00009357 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00009358 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9359 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00009360 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00009361 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009362
Rafael Espindola3ae00052013-05-13 00:12:11 +00009363 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009364 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009365
David Majnemer27d69db2014-04-28 22:17:59 +00009366 case TSK_ExplicitInstantiationDeclaration:
9367 return GVA_AvailableExternally;
9368
Rafael Espindola3ae00052013-05-13 00:12:11 +00009369 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009370 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009371 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009372
9373 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009374}
9375
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009376GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009377 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9378 adjustGVALinkageForAttributes(*this, VD,
9379 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009380}
9381
David Blaikiee6b7c282017-04-11 20:46:34 +00009382bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009383 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009384 if (!VD->isFileVarDecl())
9385 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009386 // Global named register variables (GNU extension) are never emitted.
9387 if (VD->getStorageClass() == SC_Register)
9388 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009389 if (VD->getDescribedVarTemplate() ||
9390 isa<VarTemplatePartialSpecializationDecl>(VD))
9391 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009392 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Smith5205a8c2013-04-01 20:22:16 +00009393 // We never need to emit an uninstantiated function template.
9394 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9395 return false;
Nico Weber66220292016-03-02 17:28:48 +00009396 } else if (isa<PragmaCommentDecl>(D))
9397 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00009398 else if (isa<OMPThreadPrivateDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00009399 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009400 else if (isa<PragmaDetectMismatchDecl>(D))
9401 return true;
Nico Weber66220292016-03-02 17:28:48 +00009402 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009403 return !D->getDeclContext()->isDependentContext();
9404 else if (isa<OMPDeclareReductionDecl>(D))
9405 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009406 else if (isa<ImportDecl>(D))
9407 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009408 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009409 return false;
9410
9411 // If this is a member of a class template, we do not need to emit it.
9412 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009413 return false;
9414
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009415 // Weak references don't produce any output by themselves.
9416 if (D->hasAttr<WeakRefAttr>())
9417 return false;
9418
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009419 // Aliases and used decls are required.
9420 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9421 return true;
9422
Eugene Zelenko7855e772018-04-03 00:11:50 +00009423 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009424 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009425 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009426 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009427
9428 // Constructors and destructors are required.
9429 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9430 return true;
9431
John McCall6bd2a892013-01-25 22:31:03 +00009432 // The key function for a class is required. This rule only comes
9433 // into play when inline functions can be key functions, though.
9434 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009435 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
John McCall6bd2a892013-01-25 22:31:03 +00009436 const CXXRecordDecl *RD = MD->getParent();
9437 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9438 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9439 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9440 return true;
9441 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009442 }
9443 }
9444
David Blaikie9ffe5a32017-01-30 05:00:26 +00009445 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9446
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009447 // static, static inline, always_inline, and extern inline functions can
9448 // always be deferred. Normal inline functions can be deferred in C99/C++.
9449 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009450 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009451 }
Douglas Gregor87d81242011-09-10 00:22:34 +00009452
Eugene Zelenko7855e772018-04-03 00:11:50 +00009453 const auto *VD = cast<VarDecl>(D);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009454 assert(VD->isFileVarDecl() && "Expected file scoped var");
9455
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009456 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9457 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009458 return false;
9459
Richard Smitha0e5e542012-11-12 21:38:00 +00009460 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +00009461 auto Linkage = GetGVALinkageForVariable(VD);
9462 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +00009463 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009464
Richard Smitha4653622017-09-06 20:01:14 +00009465 // We never need to emit a variable that is available in another TU.
9466 if (Linkage == GVA_AvailableExternally)
9467 return false;
9468
Richard Smitha0e5e542012-11-12 21:38:00 +00009469 // Variables that have destruction with side-effects are required.
9470 if (VD->getType().isDestructedType())
9471 return true;
9472
9473 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009474 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009475 // We can get a value-dependent initializer during error recovery.
9476 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009477 return true;
9478
Richard Smithda383632016-08-15 01:33:41 +00009479 // Likewise, variables with tuple-like bindings are required if their
9480 // bindings have side-effects.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009481 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
9482 for (const auto *BD : DD->bindings())
9483 if (const auto *BindingVD = BD->getHoldingVar())
Richard Smithda383632016-08-15 01:33:41 +00009484 if (DeclMustBeEmitted(BindingVD))
9485 return true;
9486
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00009487 // If the decl is marked as `declare target`, it should be emitted.
Alexey Bataev92327c52018-03-26 16:40:55 +00009488 for (const auto *Decl : D->redecls()) {
9489 if (!Decl->hasAttrs())
9490 continue;
9491 if (const auto *Attr = Decl->getAttr<OMPDeclareTargetDeclAttr>())
9492 if (Attr->getMapType() != OMPDeclareTargetDeclAttr::MT_Link)
9493 return true;
9494 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00009495
Richard Smitha0e5e542012-11-12 21:38:00 +00009496 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009497}
Charles Davis53c59df2010-08-16 03:33:14 +00009498
Erich Keane281d20b2018-01-08 21:34:17 +00009499void ASTContext::forEachMultiversionedFunctionVersion(
9500 const FunctionDecl *FD,
9501 llvm::function_ref<void(const FunctionDecl *)> Pred) const {
9502 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
9503 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
9504 FD = FD->getCanonicalDecl();
9505 for (auto *CurDecl :
9506 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
9507 FunctionDecl *CurFD = CurDecl->getAsFunction()->getCanonicalDecl();
9508 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
9509 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
9510 SeenDecls.insert(CurFD);
9511 Pred(CurFD);
9512 }
9513 }
9514}
9515
Reid Kleckner78af0702013-08-27 23:08:25 +00009516CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9517 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00009518 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00009519 if (IsCXXMethod)
9520 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00009521
Alexey Bataeva7547182016-05-18 09:06:38 +00009522 switch (LangOpts.getDefaultCallingConv()) {
9523 case LangOptions::DCC_None:
9524 break;
9525 case LangOptions::DCC_CDecl:
9526 return CC_C;
9527 case LangOptions::DCC_FastCall:
Erich Keane5759fa72017-10-24 23:12:01 +00009528 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
Alexey Bataeva7547182016-05-18 09:06:38 +00009529 return CC_X86FastCall;
9530 break;
9531 case LangOptions::DCC_StdCall:
9532 if (!IsVariadic)
9533 return CC_X86StdCall;
9534 break;
9535 case LangOptions::DCC_VectorCall:
9536 // __vectorcall cannot be applied to variadic functions.
9537 if (!IsVariadic)
9538 return CC_X86VectorCall;
9539 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00009540 case LangOptions::DCC_RegCall:
9541 // __regcall cannot be applied to variadic functions.
9542 if (!IsVariadic)
9543 return CC_X86RegCall;
9544 break;
Alexey Bataeva7547182016-05-18 09:06:38 +00009545 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00009546 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00009547}
9548
Jay Foad39c79802011-01-12 09:06:06 +00009549bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00009550 // Pass through to the C++ ABI object
9551 return ABI->isNearlyEmpty(RD);
9552}
9553
Reid Kleckner96f8f932014-02-05 17:27:08 +00009554VTableContextBase *ASTContext::getVTableContext() {
9555 if (!VTContext.get()) {
9556 if (Target->getCXXABI().isMicrosoft())
9557 VTContext.reset(new MicrosoftVTableContext(*this));
9558 else
9559 VTContext.reset(new ItaniumVTableContext(*this));
9560 }
9561 return VTContext.get();
9562}
9563
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009564MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00009565 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009566 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009567 case TargetCXXABI::GenericItanium:
9568 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009569 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009570 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009571 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009572 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009573 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009574 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009575 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009576 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009577 }
David Blaikie83d382b2011-09-23 05:06:16 +00009578 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009579}
9580
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009581CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009582
9583size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00009584 return ASTRecordLayouts.getMemorySize() +
9585 llvm::capacity_in_bytes(ObjCLayouts) +
9586 llvm::capacity_in_bytes(KeyFunctions) +
9587 llvm::capacity_in_bytes(ObjCImpls) +
9588 llvm::capacity_in_bytes(BlockVarCopyInits) +
9589 llvm::capacity_in_bytes(DeclAttrs) +
9590 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9591 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9592 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9593 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9594 llvm::capacity_in_bytes(OverriddenMethods) +
9595 llvm::capacity_in_bytes(Types) +
9596 llvm::capacity_in_bytes(VariableArrayTypes) +
9597 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009598}
Ted Kremenek540017e2011-10-06 05:00:56 +00009599
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009600/// getIntTypeForBitwidth -
9601/// sets integer QualTy according to specified details:
9602/// bitwidth, signed/unsigned.
9603/// Returns empty type if there is no appropriate target types.
9604QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9605 unsigned Signed) const {
9606 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9607 CanQualType QualTy = getFromTargetType(Ty);
9608 if (!QualTy && DestWidth == 128)
9609 return Signed ? Int128Ty : UnsignedInt128Ty;
9610 return QualTy;
9611}
9612
9613/// getRealTypeForBitwidth -
9614/// sets floating point QualTy according to specified bitwidth.
9615/// Returns empty type if there is no appropriate target types.
9616QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9617 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9618 switch (Ty) {
9619 case TargetInfo::Float:
9620 return FloatTy;
9621 case TargetInfo::Double:
9622 return DoubleTy;
9623 case TargetInfo::LongDouble:
9624 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00009625 case TargetInfo::Float128:
9626 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009627 case TargetInfo::NoFloat:
Eugene Zelenko7855e772018-04-03 00:11:50 +00009628 return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009629 }
9630
9631 llvm_unreachable("Unhandled TargetInfo::RealType value");
9632}
9633
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009634void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9635 if (Number > 1)
9636 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00009637}
9638
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009639unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009640 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009641 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00009642}
9643
David Majnemer2206bf52014-03-05 08:57:59 +00009644void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9645 if (Number > 1)
9646 StaticLocalNumbers[VD] = Number;
9647}
9648
9649unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009650 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00009651 return I != StaticLocalNumbers.end() ? I->second : 1;
9652}
9653
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009654MangleNumberingContext &
9655ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009656 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +00009657 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +00009658 if (!MCtx)
9659 MCtx = createMangleNumberingContext();
9660 return *MCtx;
9661}
9662
Justin Lebar20ebffc2016-10-10 16:26:19 +00009663std::unique_ptr<MangleNumberingContext>
9664ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009665 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00009666}
9667
David Majnemere7a818f2015-03-06 18:53:55 +00009668const CXXConstructorDecl *
9669ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9670 return ABI->getCopyConstructorForExceptionObject(
9671 cast<CXXRecordDecl>(RD->getFirstDecl()));
9672}
9673
9674void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9675 CXXConstructorDecl *CD) {
9676 return ABI->addCopyConstructorForExceptionObject(
9677 cast<CXXRecordDecl>(RD->getFirstDecl()),
9678 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9679}
9680
David Majnemer00350522015-08-31 18:48:39 +00009681void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9682 TypedefNameDecl *DD) {
9683 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9684}
9685
9686TypedefNameDecl *
9687ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9688 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9689}
9690
9691void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9692 DeclaratorDecl *DD) {
9693 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9694}
9695
9696DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9697 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9698}
9699
Ted Kremenek540017e2011-10-06 05:00:56 +00009700void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9701 ParamIndices[D] = index;
9702}
9703
9704unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9705 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9706 assert(I != ParamIndices.end() &&
9707 "ParmIndices lacks entry set by ParmVarDecl");
9708 return I->second;
9709}
Fariborz Jahanian615de762013-05-28 17:37:39 +00009710
Richard Smithe6c01442013-06-05 00:46:14 +00009711APValue *
9712ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9713 bool MayCreate) {
9714 assert(E && E->getStorageDuration() == SD_Static &&
9715 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00009716 if (MayCreate) {
9717 APValue *&MTVI = MaterializedTemporaryValues[E];
9718 if (!MTVI)
9719 MTVI = new (*this) APValue;
9720 return MTVI;
9721 }
Richard Smithe6c01442013-06-05 00:46:14 +00009722
David Majnemer2dcef9e2015-08-13 23:50:15 +00009723 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00009724}
9725
Fariborz Jahanian615de762013-05-28 17:37:39 +00009726bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9727 const llvm::Triple &T = getTargetInfo().getTriple();
9728 if (!T.isOSDarwin())
9729 return false;
9730
Bob Wilson2c82c3d2013-11-02 23:27:49 +00009731 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9732 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9733 return false;
9734
Fariborz Jahanian615de762013-05-28 17:37:39 +00009735 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9736 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9737 uint64_t Size = sizeChars.getQuantity();
9738 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9739 unsigned Align = alignChars.getQuantity();
9740 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9741 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9742}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009743
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009744static ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009745 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009746 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009747 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009748 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009749 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009750 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009751}
9752
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009753namespace {
9754
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009755/// Template specializations to abstract away from pointers and TypeLocs.
9756/// @{
9757template <typename T>
9758ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9759 return ast_type_traits::DynTypedNode::create(*Node);
9760}
9761template <>
9762ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9763 return ast_type_traits::DynTypedNode::create(Node);
9764}
9765template <>
9766ast_type_traits::DynTypedNode
9767createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9768 return ast_type_traits::DynTypedNode::create(Node);
9769}
9770/// @}
9771
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009772 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
9773 /// parents as defined by the \c RecursiveASTVisitor.
9774 ///
9775 /// Note that the relationship described here is purely in terms of AST
9776 /// traversal - there are other relationships (for example declaration context)
9777 /// in the AST that are better modeled by special matchers.
9778 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009779 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009780 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009781 public:
9782 /// \brief Builds and returns the translation unit's parent map.
9783 ///
9784 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009785 static std::pair<ASTContext::ParentMapPointers *,
9786 ASTContext::ParentMapOtherNodes *>
9787 buildMap(TranslationUnitDecl &TU) {
9788 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9789 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009790 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009791 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009792 }
9793
9794 private:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009795 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9796
9797 using VisitorBase = RecursiveASTVisitor<ParentMapASTVisitor>;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009798
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009799 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9800 ASTContext::ParentMapOtherNodes *OtherParents)
9801 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009802
9803 bool shouldVisitTemplateInstantiations() const {
9804 return true;
9805 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009806
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009807 bool shouldVisitImplicitCode() const {
9808 return true;
9809 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009810
Richard Smith85838722015-11-24 03:09:01 +00009811 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9812 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009813 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00009814 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00009815 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009816 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00009817 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009818 // FIXME: Currently we add the same parent multiple times, but only
9819 // when no memoization data is available for the type.
9820 // For example when we visit all subexpressions of template
9821 // instantiations; this is suboptimal, but benign: the only way to
9822 // visit those is with hasAncestor / hasParent, and those do not create
9823 // new matches.
9824 // The plan is to enable DynTypedNode to be storable in a map or hash
9825 // map. The main problem there is to implement hash functions /
9826 // comparison operators for all types that DynTypedNode supports that
9827 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009828 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00009829 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009830 if (const auto *D = ParentStack.back().get<Decl>())
9831 NodeOrVector = D;
9832 else if (const auto *S = ParentStack.back().get<Stmt>())
9833 NodeOrVector = S;
9834 else
9835 NodeOrVector =
9836 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009837 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009838 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9839 auto *Vector = new ASTContext::ParentVector(
9840 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Gabor Horvath10a837a2017-04-19 15:11:10 +00009841 delete NodeOrVector
9842 .template dyn_cast<ast_type_traits::DynTypedNode *>();
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00009843 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009844 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009845
9846 auto *Vector =
9847 NodeOrVector.template get<ASTContext::ParentVector *>();
9848 // Skip duplicates for types that have memoization data.
9849 // We must check that the type has memoization data before calling
9850 // std::find() because DynTypedNode::operator== can't compare all
9851 // types.
9852 bool Found = ParentStack.back().getMemoizationData() &&
9853 std::find(Vector->begin(), Vector->end(),
9854 ParentStack.back()) != Vector->end();
9855 if (!Found)
9856 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009857 }
9858 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009859 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009860 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009861 ParentStack.pop_back();
9862 return Result;
9863 }
9864
9865 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009866 return TraverseNode(DeclNode, DeclNode,
9867 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009868 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009869 }
9870
9871 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009872 return TraverseNode(StmtNode, StmtNode,
9873 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009874 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009875 }
9876
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009877 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009878 return TraverseNode(
9879 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9880 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9881 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009882 }
9883
9884 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9885 return TraverseNode(
9886 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009887 [&] {
9888 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9889 },
9890 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009891 }
9892
9893 ASTContext::ParentMapPointers *Parents;
9894 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009895 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009896 };
9897
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009898} // namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009899
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009900template <typename NodeTy, typename MapTy>
9901static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9902 const MapTy &Map) {
9903 auto I = Map.find(Node);
9904 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009905 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009906 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009907 if (const auto *V =
9908 I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009909 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009910 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009911 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009912}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009913
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009914ASTContext::DynTypedNodeList
9915ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9916 if (!PointerParents) {
9917 // We always need to run over the whole translation unit, as
9918 // hasAncestor can escape any subtree.
9919 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9920 PointerParents.reset(Maps.first);
9921 OtherParents.reset(Maps.second);
9922 }
9923 if (Node.getNodeKind().hasPointerIdentity())
9924 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9925 return getDynNodeFromMap(Node, *OtherParents);
9926}
9927
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009928bool
9929ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9930 const ObjCMethodDecl *MethodImpl) {
9931 // No point trying to match an unavailable/deprecated mothod.
9932 if (MethodDecl->hasAttr<UnavailableAttr>()
9933 || MethodDecl->hasAttr<DeprecatedAttr>())
9934 return false;
9935 if (MethodDecl->getObjCDeclQualifier() !=
9936 MethodImpl->getObjCDeclQualifier())
9937 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009938 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009939 return false;
9940
9941 if (MethodDecl->param_size() != MethodImpl->param_size())
9942 return false;
9943
9944 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9945 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9946 EF = MethodDecl->param_end();
9947 IM != EM && IF != EF; ++IM, ++IF) {
9948 const ParmVarDecl *DeclVar = (*IF);
9949 const ParmVarDecl *ImplVar = (*IM);
9950 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9951 return false;
9952 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9953 return false;
9954 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009955
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009956 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009957}
Richard Smith053f6c62014-05-16 23:01:30 +00009958
Yaxun Liu402804b2016-12-15 08:09:08 +00009959uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +00009960 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +00009961 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +00009962 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +00009963 else
9964 AS = QT->getPointeeType().getAddressSpace();
9965
9966 return getTargetInfo().getNullPointerValue(AS);
9967}
9968
Alexander Richardson6d989432017-10-15 18:48:14 +00009969unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
9970 if (isTargetAddressSpace(AS))
9971 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +00009972 else
Alexander Richardson6d989432017-10-15 18:48:14 +00009973 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +00009974}
9975
Richard Smith053f6c62014-05-16 23:01:30 +00009976// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9977// doesn't include ASTContext.h
9978template
9979clang::LazyGenerationalUpdatePtr<
9980 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9981clang::LazyGenerationalUpdatePtr<
9982 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9983 const clang::ASTContext &Ctx, Decl *Value);