-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathTargetConstantFolding.cpp
152 lines (134 loc) · 5.18 KB
/
TargetConstantFolding.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
//===--- TargetConstantFolding.cpp ----------------------------------------===//
//
// 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
//
// This pass lowers loadable SILTypes. On completion, the SILType of every
// function argument is an address instead of the type itself.
// This reduces the code size.
// Consequently, this pass is required for IRGen.
// It is a mandatory IRGen preparation pass (not a diagnostic pass).
//
//===----------------------------------------------------------------------===//
///
/// This file contains a pass for target specific constant folding:
/// `TargetConstantFolding`. For details see the comments there.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "target-constant-folding"
#include "../../IRGen/IRGenModule.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/InstructionDeleter.h"
#include "llvm/Support/Debug.h"
using namespace swift;
using namespace swift::irgen;
namespace {
/// Performs constant folding for target-specific values.
///
/// Specifically, this optimization constant folds
/// ```
/// MemoryLayout<S>.size
/// MemoryLayout<S>.alignment
/// MemoryLayout<S>.stride
/// ```
/// Constant folding those expressions in the middle of the SIL pipeline
/// enables other optimizations to e.g. allow such expressions in statically
/// allocated global variables (done by the GlobalOpt pass).
class TargetConstantFolding : public SILModuleTransform {
private:
/// The entry point to the transformation.
void run() override {
SILModule *module = getModule();
auto *irgenOpts = module->getIRGenOptionsOrNull();
if (!irgenOpts)
return;
// We need an IRGenModule to get the actual sizes from type lowering.
// Creating an IRGenModule involves some effort. Therefore this is a
// module pass rather than a function pass so that this one-time setup
// only needs to be done once and not for all functions in a module.
IRGenerator irgen(*irgenOpts, *module);
auto targetMachine = irgen.createTargetMachine();
if (!targetMachine)
return;
IRGenModule IGM(irgen, std::move(targetMachine));
// Scan all instructions in the module for constant foldable instructions.
for (SILFunction &function : *module) {
bool changed = false;
for (SILBasicBlock &block : function) {
InstructionDeleter deleter;
for (SILInstruction *inst : deleter.updatingRange(&block)) {
if (constFold(inst, IGM)) {
deleter.forceDelete(inst);
changed = true;
}
}
deleter.cleanupDeadInstructions();
}
if (changed) {
invalidateAnalysis(&function, SILAnalysis::InvalidationKind::Instructions);
}
}
}
/// Constant fold a single instruction.
///
/// Returns true if `inst` was replaced and can be deleted.
bool constFold(SILInstruction *inst, IRGenModule &IGM) {
auto *bi = dyn_cast<BuiltinInst>(inst);
if (!bi)
return false;
llvm::Constant *c = nullptr;
uint64_t offset = 0;
switch (bi->getBuiltinInfo().ID) {
case BuiltinValueKind::Sizeof:
c = getTypeInfoOfBuiltin(bi, IGM).getStaticSize(IGM);
break;
case BuiltinValueKind::Alignof:
c = getTypeInfoOfBuiltin(bi, IGM).getStaticAlignmentMask(IGM);
// The constant is the alignment _mask_. We get the actual alignment by
// adding 1.
offset = 1;
break;
case BuiltinValueKind::Strideof:
c = getTypeInfoOfBuiltin(bi, IGM).getStaticStride(IGM);
break;
default:
return false;
}
auto *intConst = dyn_cast_or_null<llvm::ConstantInt>(c);
if (!intConst)
return false;
APInt value = intConst->getValue();
value += APInt(value.getBitWidth(), offset);
auto intTy = bi->getType().getAs<BuiltinIntegerType>();
if (!intTy)
return false;
// The bit widths can differ if we are compiling for a 32 bit target.
if (value.getActiveBits() > intTy->getGreatestWidth()) {
// It's unlikely that a size/stride overflows 32 bits, but let's be on
// the safe side and catch a potential overflow.
return false;
}
value = value.sextOrTrunc(intTy->getGreatestWidth());
// Replace the builtin by an integer literal.
SILBuilderWithScope builder(bi);
auto *intLit = builder.createIntegerLiteral(bi->getLoc(), bi->getType(),
value);
bi->replaceAllUsesWith(intLit);
return true;
}
const TypeInfo &getTypeInfoOfBuiltin(BuiltinInst *bi, IRGenModule &IGM) {
SubstitutionMap subs = bi->getSubstitutions();
SILType lowered = IGM.getLoweredType(subs.getReplacementTypes()[0]);
return IGM.getTypeInfo(lowered);
}
};
} // end anonymous namespace
SILTransform *swift::createTargetConstantFolding() {
return new TargetConstantFolding();
}