-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathIRABIDetailsProvider.cpp
400 lines (357 loc) · 14.7 KB
/
IRABIDetailsProvider.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
//===--- IRABIDetailsProvider.cpp - Get ABI details for decls ---*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/IRGen/IRABIDetailsProvider.h"
#include "Callee.h"
#include "FixedTypeInfo.h"
#include "GenEnum.h"
#include "GenType.h"
#include "GenericRequirement.h"
#include "IRGen.h"
#include "IRGenModule.h"
#include "NativeConventionSchema.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Types.h"
#include "swift/SIL/SILFunctionBuilder.h"
#include "swift/SIL/SILModule.h"
#include "swift/Subsystems.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/CodeGen/SwiftCallingConv.h"
#include "llvm/IR/DerivedTypes.h"
using namespace swift;
using namespace irgen;
static Optional<Type> getPrimitiveTypeFromLLVMType(ASTContext &ctx,
const llvm::Type *type) {
if (const auto *intType = dyn_cast<llvm::IntegerType>(type)) {
switch (intType->getBitWidth()) {
case 1:
return ctx.getBoolType();
case 8:
return ctx.getUInt8Type();
case 16:
return ctx.getUInt16Type();
case 32:
return ctx.getUInt32Type();
case 64:
return ctx.getUInt64Type();
default:
return None;
}
} else if (type->isFloatTy()) {
return ctx.getFloatType();
} else if (type->isDoubleTy()) {
return ctx.getDoubleType();
} else if (type->isPointerTy()) {
return ctx.getOpaquePointerType();
}
// FIXME: Handle vector type.
return None;
}
namespace swift {
class IRABIDetailsProviderImpl {
public:
IRABIDetailsProviderImpl(ModuleDecl &mod, const IRGenOptions &opts)
: typeConverter(mod),
silMod(SILModule::createEmptyModule(&mod, typeConverter, silOpts)),
IRGen(opts, *silMod), IGM(IRGen, IRGen.createTargetMachine()) {}
llvm::Optional<IRABIDetailsProvider::SizeAndAlignment>
getTypeSizeAlignment(const NominalTypeDecl *TD) {
auto *TI = &IGM.getTypeInfoForUnlowered(TD->getDeclaredTypeInContext());
auto *fixedTI = dyn_cast<FixedTypeInfo>(TI);
if (!fixedTI)
return None;
return IRABIDetailsProvider::SizeAndAlignment{
fixedTI->getFixedSize().getValue(),
fixedTI->getFixedAlignment().getValue()};
}
IRABIDetailsProvider::FunctionABISignature
getTypeMetadataAccessFunctionSignature() {
auto &ctx = IGM.getSwiftModule()->getASTContext();
llvm::StructType *responseTy = IGM.getTypeMetadataResponseTy();
IRABIDetailsProvider::TypeRecordABIRepresentation::MemberVectorTy members;
for (auto *elementTy : responseTy->elements())
members.push_back(*getPrimitiveTypeFromLLVMType(ctx, elementTy));
auto returnTy =
IRABIDetailsProvider::TypeRecordABIRepresentation(std::move(members));
auto paramTy = IRABIDetailsProvider::TypeRecordABIRepresentation(
{*getPrimitiveTypeFromLLVMType(ctx,
IGM.getTypeMetadataRequestParamTy())});
return {returnTy, {paramTy}};
}
SmallVector<GenericRequirement, 2>
getTypeMetadataAccessFunctionGenericRequirementParameters(
NominalTypeDecl *nominal) {
GenericTypeRequirements requirements(IGM, nominal);
SmallVector<GenericRequirement, 2> result;
for (const auto &req : requirements.getRequirements())
result.push_back(req);
return result;
}
llvm::MapVector<EnumElementDecl *, IRABIDetailsProvider::EnumElementInfo>
getEnumTagMapping(const EnumDecl *ED) {
llvm::MapVector<EnumElementDecl *, IRABIDetailsProvider::EnumElementInfo>
elements;
auto &enumImplStrat = getEnumImplStrategy(
IGM, ED->DeclContext::getDeclaredTypeInContext()->getCanonicalType());
for (auto *element : ED->getAllElements()) {
auto tagIdx = enumImplStrat.getTagIndex(element);
auto *global = cast<llvm::GlobalVariable>(
IGM.getAddrOfEnumCase(element, NotForDefinition).getAddress());
elements.insert({element, {tagIdx, global->getName()}});
}
return elements;
}
llvm::Optional<LoweredFunctionSignature>
getFunctionLoweredSignature(AbstractFunctionDecl *fd) {
auto function = SILFunction::getFunction(SILDeclRef(fd), *silMod);
IGM.lowerSILFunction(function);
auto silFuncType = function->getLoweredFunctionType();
// FIXME: Async function support.
if (silFuncType->isAsync())
return None;
if (silFuncType->getLanguage() != SILFunctionLanguage::Swift)
return None;
// FIXME: Tuple parameter mapping support.
llvm::SmallVector<const ParamDecl *, 8> silParamMapping;
for (auto param : *fd->getParameters()) {
if (auto *tuple =
param->getType()->getDesugaredType()->getAs<TupleType>()) {
if (tuple->getNumElements() > 0)
return None;
}
}
auto funcPointerKind =
FunctionPointerKind(FunctionPointerKind::BasicKind::Function);
auto *abiDetails = new (signatureExpansions.Allocate())
SignatureExpansionABIDetails(Signature::getUncachedABIDetails(
IGM, silFuncType, funcPointerKind));
auto result = LoweredFunctionSignature(fd, *this, *abiDetails);
// Save metadata source types to avoid keeping the SIL func around.
for (const auto &typeSource :
abiDetails->polymorphicSignatureExpandedTypeSources) {
typeSource.visit(
[&](const GenericRequirement &reqt) {},
[&](const MetadataSource &metadataSource) {
auto index = metadataSource.getParamIndex();
auto canType =
silFuncType->getParameters()[index].getInterfaceType();
result.metadataSourceTypes.push_back(canType);
});
}
// Verify that the signature param count matches the IR param count.
size_t signatureParamCount = 0;
result.visitParameterList(
[&](const LoweredFunctionSignature::IndirectResultValue
&indirectResult) { ++signatureParamCount; },
[&](const LoweredFunctionSignature::DirectParameter ¶m) {
param.enumerateRecordMembers([&](clang::CharUnits, clang::CharUnits,
Type) { ++signatureParamCount; });
},
[&](const LoweredFunctionSignature::IndirectParameter ¶m) {
++signatureParamCount;
},
[&](const LoweredFunctionSignature::GenericRequirementParameter
&genericRequirementParam) { ++signatureParamCount; },
[&](const LoweredFunctionSignature::MetadataSourceParameter
&metadataSrcParam) { ++signatureParamCount; },
[&](const LoweredFunctionSignature::ContextParameter &) {
++signatureParamCount;
},
[&](const LoweredFunctionSignature::ErrorResultValue &) {
++signatureParamCount;
});
// Return nothing if we were unable to represent the exact signature
// parameters.
if (signatureParamCount != abiDetails->numParamIRTypesInSignature)
return None;
return result;
}
Lowering::TypeConverter typeConverter;
// Default silOptions are sufficient, as we don't need to generated SIL.
SILOptions silOpts;
std::unique_ptr<SILModule> silMod;
IRGenerator IRGen;
IRGenModule IGM;
llvm::SpecificBumpPtrAllocator<SignatureExpansionABIDetails>
signatureExpansions;
};
} // namespace swift
LoweredFunctionSignature::LoweredFunctionSignature(
const AbstractFunctionDecl *FD, IRABIDetailsProviderImpl &owner,
const irgen::SignatureExpansionABIDetails &abiDetails)
: FD(FD), owner(owner), abiDetails(abiDetails) {}
LoweredFunctionSignature::DirectResultType::DirectResultType(
IRABIDetailsProviderImpl &owner, const irgen::TypeInfo &typeDetails)
: owner(owner), typeDetails(typeDetails) {}
bool LoweredFunctionSignature::DirectResultType::enumerateRecordMembers(
llvm::function_ref<void(clang::CharUnits, clang::CharUnits, Type)> callback)
const {
auto &schema = typeDetails.nativeReturnValueSchema(owner.IGM);
assert(!schema.requiresIndirect());
bool hasError = false;
schema.enumerateComponents(
[&](clang::CharUnits offset, clang::CharUnits end, llvm::Type *type) {
auto primitiveType = getPrimitiveTypeFromLLVMType(
owner.IGM.getSwiftModule()->getASTContext(), type);
if (!primitiveType) {
hasError = true;
return;
}
callback(offset, end, *primitiveType);
});
return hasError;
}
LoweredFunctionSignature::DirectParameter::DirectParameter(
IRABIDetailsProviderImpl &owner, const irgen::TypeInfo &typeDetails,
const ParamDecl ¶mDecl)
: owner(owner), typeDetails(typeDetails), paramDecl(paramDecl) {}
LoweredFunctionSignature::IndirectParameter::IndirectParameter(
const ParamDecl ¶mDecl)
: paramDecl(paramDecl) {}
bool LoweredFunctionSignature::DirectParameter::enumerateRecordMembers(
llvm::function_ref<void(clang::CharUnits, clang::CharUnits, Type)> callback)
const {
auto &schema = typeDetails.nativeParameterValueSchema(owner.IGM);
assert(!schema.requiresIndirect());
bool hasError = false;
schema.enumerateComponents(
[&](clang::CharUnits offset, clang::CharUnits end, llvm::Type *type) {
auto primitiveType = getPrimitiveTypeFromLLVMType(
owner.IGM.getSwiftModule()->getASTContext(), type);
if (!primitiveType) {
hasError = true;
return;
}
callback(offset, end, *primitiveType);
});
return hasError;
}
LoweredFunctionSignature::GenericRequirementParameter::
GenericRequirementParameter(const GenericRequirement &requirement)
: requirement(requirement) {}
LoweredFunctionSignature::MetadataSourceParameter::MetadataSourceParameter(
const CanType &type)
: type(type) {}
llvm::Optional<LoweredFunctionSignature::DirectResultType>
LoweredFunctionSignature::getDirectResultType() const {
if (!abiDetails.directResult)
return None;
return DirectResultType(owner, abiDetails.directResult->typeInfo);
}
size_t LoweredFunctionSignature::getNumIndirectResultValues() const {
return abiDetails.indirectResults.size();
}
void LoweredFunctionSignature::visitParameterList(
llvm::function_ref<void(const IndirectResultValue &)> indirectResultVisitor,
llvm::function_ref<void(const DirectParameter &)> directParamVisitor,
llvm::function_ref<void(const IndirectParameter &)> indirectParamVisitor,
llvm::function_ref<void(const GenericRequirementParameter &)>
genericRequirementVisitor,
llvm::function_ref<void(const MetadataSourceParameter &)>
metadataSourceVisitor,
llvm::function_ref<void(const ContextParameter &)> contextParamVisitor,
llvm::function_ref<void(const ErrorResultValue &)> errorResultVisitor)
const {
// Indirect result values come before parameters.
for (const auto &r : abiDetails.indirectResults)
indirectResultVisitor(IndirectResultValue(r.hasSRet));
// Traverse ABI parameters, mapping them back to the AST parameters.
llvm::SmallVector<const ParamDecl *, 8> silParamMapping;
for (auto param : *FD->getParameters()) {
// FIXME: tuples map to more than one sil param (but they're not yet
// representable by the consumer).
if (!param->getInterfaceType()->isVoid())
silParamMapping.push_back(param);
}
size_t currentSilParam = 0;
for (const auto &abiParam : abiDetails.parameters) {
bool isIndirect = true;
if (!isIndirectFormalParameter(abiParam.convention)) {
const auto &schema =
abiParam.typeInfo.get().nativeParameterValueSchema(owner.IGM);
if (!schema.requiresIndirect()) {
// Skip ABI parameters with empty native representation, as they're not
// emitted in the LLVM IR signature.
if (schema.empty())
continue;
isIndirect = false;
}
}
const ParamDecl *paramDecl = abiParam.isSelf
? FD->getImplicitSelfDecl()
: silParamMapping[currentSilParam];
++currentSilParam;
if (!isIndirect) {
DirectParameter param(owner, abiParam.typeInfo, *paramDecl);
directParamVisitor(param);
} else {
IndirectParameter param(*paramDecl);
indirectParamVisitor(param);
}
}
// FIXME: Use one assert for indirect self too.
if (FD->getImplicitSelfDecl())
assert(currentSilParam == (silParamMapping.size() + 1) ||
currentSilParam == silParamMapping.size());
else
assert(currentSilParam == silParamMapping.size());
// Generic requirements come next.
size_t metadataSourceIndex = 0;
for (const auto &typeSource :
abiDetails.polymorphicSignatureExpandedTypeSources) {
typeSource.visit(
[&](const GenericRequirement &reqt) {
genericRequirementVisitor(GenericRequirementParameter(reqt));
},
[&](const MetadataSource &metadataSource) {
metadataSourceVisitor(MetadataSourceParameter(
metadataSourceTypes[metadataSourceIndex]));
++metadataSourceIndex;
});
}
if (abiDetails.hasTrailingSelfParam) {
assert(!abiDetails.hasContextParam);
assert(FD->hasImplicitSelfDecl());
indirectParamVisitor(IndirectParameter(*FD->getImplicitSelfDecl()));
} else if (abiDetails.hasContextParam) {
contextParamVisitor(ContextParameter());
}
if (abiDetails.hasErrorResult)
errorResultVisitor(ErrorResultValue());
}
IRABIDetailsProvider::IRABIDetailsProvider(ModuleDecl &mod,
const IRGenOptions &opts)
: impl(std::make_unique<IRABIDetailsProviderImpl>(mod, opts)) {}
IRABIDetailsProvider::~IRABIDetailsProvider() {}
llvm::Optional<IRABIDetailsProvider::SizeAndAlignment>
IRABIDetailsProvider::getTypeSizeAlignment(const NominalTypeDecl *TD) {
return impl->getTypeSizeAlignment(TD);
}
llvm::Optional<LoweredFunctionSignature>
IRABIDetailsProvider::getFunctionLoweredSignature(AbstractFunctionDecl *fd) {
return impl->getFunctionLoweredSignature(fd);
}
IRABIDetailsProvider::FunctionABISignature
IRABIDetailsProvider::getTypeMetadataAccessFunctionSignature() {
return impl->getTypeMetadataAccessFunctionSignature();
}
SmallVector<GenericRequirement, 2>
IRABIDetailsProvider::getTypeMetadataAccessFunctionGenericRequirementParameters(
NominalTypeDecl *nominal) {
return impl->getTypeMetadataAccessFunctionGenericRequirementParameters(
nominal);
}
llvm::MapVector<EnumElementDecl *, IRABIDetailsProvider::EnumElementInfo>
IRABIDetailsProvider::getEnumTagMapping(const EnumDecl *ED) {
return impl->getEnumTagMapping(ED);
}