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
|
//===- LowerEmSetjmp - Lower setjmp/longjmp for Emscripten/JS -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Lowers setjmp to a reasonably-performant approach for emscripten. The idea
// is that each block with a setjmp is broken up into the part right after
// the setjmp, and a new basic block is added which is either reached from
// the setjmp, or later from a longjmp. To handle the longjmp, all calls that
// might longjmp are checked immediately afterwards.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Target/TargetLowering.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/NaCl.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Transforms/Utils/PromoteMemToReg.h"
#include <vector>
#include <set>
#include "llvm/Support/raw_ostream.h"
#ifdef NDEBUG
#undef assert
#define assert(x) { if (!(x)) report_fatal_error(#x); }
#endif
using namespace llvm;
// Utilities for mem/reg: based on Reg2Mem and MemToReg
bool valueEscapes(const Instruction *Inst) {
const BasicBlock *BB = Inst->getParent();
for (Value::const_use_iterator UI = Inst->use_begin(),E = Inst->use_end();
UI != E; ++UI) {
const Instruction *I = cast<Instruction>(*UI);
if (I->getParent() != BB || isa<PHINode>(I))
return true;
}
return false;
}
void doRegToMem(Function &F) { // see Reg2Mem.cpp
// Insert all new allocas into entry block.
BasicBlock *BBEntry = &F.getEntryBlock();
assert(pred_begin(BBEntry) == pred_end(BBEntry) &&
"Entry block to function must not have predecessors!");
// Find first non-alloca instruction and create insertion point. This is
// safe if block is well-formed: it always have terminator, otherwise
// we'll get and assertion.
BasicBlock::iterator I = BBEntry->begin();
while (isa<AllocaInst>(I)) ++I;
CastInst *AllocaInsertionPoint =
new BitCastInst(Constant::getNullValue(Type::getInt32Ty(F.getContext())),
Type::getInt32Ty(F.getContext()),
"reg2mem alloca point", I);
// Find the escaped instructions. But don't create stack slots for
// allocas in entry block.
std::list<Instruction*> WorkList;
for (Function::iterator ibb = F.begin(), ibe = F.end();
ibb != ibe; ++ibb)
for (BasicBlock::iterator iib = ibb->begin(), iie = ibb->end();
iib != iie; ++iib) {
if (!(isa<AllocaInst>(iib) && iib->getParent() == BBEntry) &&
valueEscapes(iib)) {
WorkList.push_front(&*iib);
}
}
// Demote escaped instructions
for (std::list<Instruction*>::iterator ilb = WorkList.begin(),
ile = WorkList.end(); ilb != ile; ++ilb)
DemoteRegToStack(**ilb, false, AllocaInsertionPoint);
WorkList.clear();
// Find all phi's
for (Function::iterator ibb = F.begin(), ibe = F.end();
ibb != ibe; ++ibb)
for (BasicBlock::iterator iib = ibb->begin(), iie = ibb->end();
iib != iie; ++iib)
if (isa<PHINode>(iib))
WorkList.push_front(&*iib);
// Demote phi nodes
for (std::list<Instruction*>::iterator ilb = WorkList.begin(),
ile = WorkList.end(); ilb != ile; ++ilb)
DemotePHIToStack(cast<PHINode>(*ilb), AllocaInsertionPoint);
}
void doMemToReg(Function &F) {
std::vector<AllocaInst*> Allocas;
BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
DominatorTree DT;
DT.runOnFunction(F);
while (1) {
Allocas.clear();
// Find allocas that are safe to promote, by looking at all instructions in
// the entry node
for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
if (isAllocaPromotable(AI))
Allocas.push_back(AI);
if (Allocas.empty()) break;
PromoteMemToReg(Allocas, DT);
}
}
// LowerEmSetjmp
namespace {
class LowerEmSetjmp : public ModulePass {
Module *TheModule;
public:
static char ID; // Pass identification, replacement for typeid
explicit LowerEmSetjmp() : ModulePass(ID), TheModule(NULL) {
initializeLowerEmSetjmpPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M);
};
}
char LowerEmSetjmp::ID = 0;
INITIALIZE_PASS(LowerEmSetjmp, "loweremsetjmp",
"Lower setjmp and longjmp for js/emscripten",
false, false)
bool LowerEmSetjmp::runOnModule(Module &M) {
TheModule = &M;
Function *Setjmp = TheModule->getFunction("setjmp");
Function *Longjmp = TheModule->getFunction("longjmp");
if (!Setjmp && !Longjmp) return false;
Type *i32 = Type::getInt32Ty(M.getContext());
Type *Void = Type::getVoidTy(M.getContext());
// Add functions
Function *EmSetjmp = NULL;
if (Setjmp) {
SmallVector<Type*, 2> EmSetjmpTypes;
EmSetjmpTypes.push_back(Setjmp->getFunctionType()->getParamType(0));
EmSetjmpTypes.push_back(i32); // extra param that says which setjmp in the function it is
FunctionType *EmSetjmpFunc = FunctionType::get(i32, EmSetjmpTypes, false);
EmSetjmp = Function::Create(EmSetjmpFunc, GlobalValue::ExternalLinkage, "emscripten_setjmp", TheModule);
}
Function *EmLongjmp = Longjmp ? Function::Create(Longjmp->getFunctionType(), GlobalValue::ExternalLinkage, "emscripten_longjmp", TheModule) : NULL;
SmallVector<Type*, 1> IntArgTypes;
IntArgTypes.push_back(i32);
FunctionType *IntIntFunc = FunctionType::get(i32, IntArgTypes, false);
Function *CheckLongjmp = Function::Create(IntIntFunc, GlobalValue::ExternalLinkage, "emscripten_check_longjmp", TheModule); // gets control flow
Function *GetLongjmpResult = Function::Create(IntIntFunc, GlobalValue::ExternalLinkage, "emscripten_get_longjmp_result", TheModule); // gets int value longjmp'd
FunctionType *VoidFunc = FunctionType::get(Void, false);
Function *PrepSetjmp = Function::Create(VoidFunc, GlobalValue::ExternalLinkage, "emscripten_prep_setjmp", TheModule);
Function *PreInvoke = TheModule->getFunction("emscripten_preinvoke");
if (!PreInvoke) PreInvoke = Function::Create(VoidFunc, GlobalValue::ExternalLinkage, "emscripten_preinvoke", TheModule);
FunctionType *IntFunc = FunctionType::get(i32, false);
Function *PostInvoke = TheModule->getFunction("emscripten_postinvoke");
if (!PostInvoke) PostInvoke = Function::Create(IntFunc, GlobalValue::ExternalLinkage, "emscripten_postinvoke", TheModule);
// Process all callers of setjmp and longjmp. Start with setjmp.
typedef std::vector<PHINode*> Phis;
typedef std::map<Function*, Phis> FunctionPhisMap;
FunctionPhisMap SetjmpOutputPhis;
std::vector<Instruction*> ToErase;
if (Setjmp) {
for (Instruction::use_iterator UI = Setjmp->use_begin(), UE = Setjmp->use_end(); UI != UE; ++UI) {
if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
BasicBlock *SJBB = CI->getParent();
// The tail is everything right after the call, and will be reached once when setjmp is
// called, and later when longjmp returns to the setjmp
BasicBlock *Tail = SplitBlock(SJBB, CI->getNextNode(), this);
// Add a phi to the tail, which will be the output of setjmp, which indicates if this is the
// first call or a longjmp back. The phi directly uses the right value based on where we
// arrive from
PHINode *SetjmpOutput = PHINode::Create(i32, 2, "", Tail->getFirstNonPHI());
SetjmpOutput->addIncoming(ConstantInt::get(i32, 0), SJBB); // setjmp initial call returns 0
CI->replaceAllUsesWith(SetjmpOutput); // The proper output is now this, not the setjmp call itself
// longjmp returns to the setjmp will add themselves to this phi
Phis& P = SetjmpOutputPhis[SJBB->getParent()];
P.push_back(SetjmpOutput);
|