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
|
//===- PNaClSjLjEH.cpp - Lower C++ exception handling to use setjmp()------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The PNaClSjLjEH pass is part of an implementation of C++ exception
// handling for PNaCl that uses setjmp() and longjmp() to handle C++
// exceptions. The pass lowers LLVM "invoke" instructions to use
// setjmp().
//
// For example, consider the following C++ code fragment:
//
// int catcher_func() {
// try {
// int result = external_func();
// return result + 100;
// } catch (MyException &exc) {
// return exc.value + 200;
// }
// }
//
// PNaClSjLjEH converts the IR for that function to the following
// pseudo-code:
//
// struct LandingPadResult {
// void *exception_obj; // For passing to __cxa_begin_catch()
// int matched_clause_id; // See ExceptionInfoWriter.cpp
// };
//
// struct ExceptionFrame {
// union {
// jmp_buf jmpbuf; // Context for jumping to landingpad block
// struct LandingPadResult result; // Data returned to landingpad block
// };
// struct ExceptionFrame *next; // Next frame in linked list
// int clause_list_id; // Reference to landingpad's exception info
// };
//
// // Thread-local exception state
// __thread struct ExceptionFrame *__pnacl_eh_stack;
//
// int catcher_func() {
// struct ExceptionFrame frame;
// int result;
// if (!setjmp(&frame.jmpbuf)) { // Save context
// frame.next = __pnacl_eh_stack;
// frame.clause_list_id = 123;
// __pnacl_eh_stack = &frame; // Add frame to stack
// result = external_func();
// __pnacl_eh_stack = frame.next; // Remove frame from stack
// } else {
// // Handle exception. This is a simplification. Real code would
// // call __cxa_begin_catch() to extract the thrown object.
// MyException &exc = *(MyException *) frame.result.exception_obj;
// return exc.value + 200;
// }
// return result + 100;
// }
//
// The pass makes the following changes to IR:
//
// * Convert "invoke" and "landingpad" instructions.
// * Convert "resume" instructions into __pnacl_eh_resume() calls.
// * Replace each call to llvm.eh.typeid.for() with an integer
// constant representing the exception type.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/DenseMap.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/NaCl.h"
#include "ExceptionInfoWriter.h"
using namespace llvm;
namespace {
// This is a ModulePass so that it can introduce new global variables.
class PNaClSjLjEH : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
PNaClSjLjEH() : ModulePass(ID) {
initializePNaClSjLjEHPass(*PassRegistry::getPassRegistry());
}
virtual bool runOnModule(Module &M);
};
class FuncRewriter {
Type *ExceptionFrameTy;
ExceptionInfoWriter *ExcInfoWriter;
Function *Func;
// FrameInitialized indicates whether the following variables have
// been initialized.
bool FrameInitialized;
Function *SetjmpIntrinsic; // setjmp() intrinsic function
Instruction *EHStackTlsVar; // Bitcast of thread-local __pnacl_eh_stack var
Instruction *Frame; // Frame allocated for this function
Instruction *FrameJmpBuf; // Frame's jmp_buf field
Instruction *FrameNextPtr; // Frame's next field
Instruction *FrameExcInfo; // Frame's clause_list_id field
Function *EHResumeFunc; // __pnacl_eh_resume() function
// Initialize values that are shared across all "invoke"
// instructions within the function.
void initializeFrame();
public:
FuncRewriter(Type *ExceptionFrameTy, ExceptionInfoWriter *ExcInfoWriter,
Function *Func):
ExceptionFrameTy(ExceptionFrameTy),
ExcInfoWriter(ExcInfoWriter),
Func(Func),
FrameInitialized(false),
SetjmpIntrinsic(NULL), EHStackTlsVar(NULL),
Frame(NULL), FrameJmpBuf(NULL), FrameNextPtr(NULL), FrameExcInfo(NULL),
EHResumeFunc(NULL) {}
void expandInvokeInst(InvokeInst *Invoke);
void expandResumeInst(ResumeInst *Resume);
void expandFunc();
};
}
char PNaClSjLjEH::ID = 0;
INITIALIZE_PASS(PNaClSjLjEH, "pnacl-sjlj-eh",
"Lower C++ exception handling to use setjmp()",
false, false)
static const int kPNaClJmpBufSize = 1024;
static const int kPNaClJmpBufAlign = 8;
void FuncRewriter::initializeFrame() {
if (FrameInitialized)
return;
FrameInitialized = true;
Module *M = Func->getParent();
SetjmpIntrinsic = Intrinsic::getDeclaration(M, Intrinsic::nacl_setjmp);
Value *EHStackTlsVarUncast = M->getGlobalVariable("__pnacl_eh_stack");
if (!EHStackTlsVarUncast)
report_fatal_error("__pnacl_eh_stack not defined");
EHStackTlsVar = new BitCastInst(
EHStackTlsVarUncast, ExceptionFrameTy->getPointerTo()->getPointerTo(),
"pnacl_eh_stack");
Func->getEntryBlock().getInstList().push_front(EHStackTlsVar);
// Allocate the new exception frame. This is reused across all
// invoke instructions in the function.
Type *I32 = Type::getInt32Ty(M->getContext());
Frame = new AllocaInst(ExceptionFrameTy, ConstantInt::get(I32, 1),
kPNaClJmpBufAlign, "invoke_frame");
Func->getEntryBlock().getInstList().push_front(Frame);
// Calculate addresses of fields in the exception frame.
Value *JmpBufIndexes[] = { ConstantInt::get(I32, 0),
ConstantInt::get(I32, 0),
ConstantInt::get(I32, 0) };
FrameJmpBuf = GetElementPtrInst::Create(Frame, JmpBufIndexes,
"invoke_jmp_buf");
FrameJmpBuf->insertAfter(Frame);
Value *NextPtrIndexes[] = { ConstantInt::get(I32, 0),
ConstantInt::get(I32, 1) };
FrameNextPtr = GetElementPtrInst::Create(Frame, NextPtrIndexes,
"invoke_next");
FrameNextPtr->insertAfter(Frame);
Value *ExcInfoIndexes[] = { ConstantInt::get(I32, 0),
ConstantInt::get(I32, 2) };
FrameExcInfo = GetElementPtrInst::Create(Frame, ExcInfoIndexes,
"exc_info_ptr");
FrameExcInfo->insertAfter(Frame);
}
static void updateEdge(BasicBlock *Dest,
BasicBlock *OldIncoming,
BasicBlock *NewIncoming) {
for (BasicBlock::iterator Inst = Dest->begin(); Inst != Dest->end(); ++Inst) {
PHINode *Phi = dyn_cast<PHINode>(Inst);
if (!Phi)
break;
for (unsigned I = 0, E = Phi->getNumIncomingValues(); I < E; ++I) {
if (Phi->getIncomingBlock(I) == OldIncoming)
Phi->setIncomingBlock(I, NewIncoming);
}
}
}
void FuncRewriter::expandInvokeInst(InvokeInst *Invoke) {
initializeFrame();
LandingPadInst *LP = Invoke->getLandingPadInst();
Type *I32 = Type::getInt32Ty(Func->getContext());
Value *ExcInfo = ConstantInt::get(
I32, ExcInfoWriter->getIDForLandingPadClauseList(LP));
// Create setjmp() call.
Value *SetjmpArgs[] = { FrameJmpBuf };
Value *SetjmpCall = CopyDebug(CallInst::Create(SetjmpIntrinsic, SetjmpArgs,
"invoke_sj", Invoke), Invoke);
// Check setjmp()'s result.
Value *IsZero = CopyDebug(new ICmpInst(Invoke, CmpInst::ICMP_EQ, SetjmpCall,
ConstantInt::get(I32, 0),
"invoke_sj_is_zero"), Invoke);
BasicBlock *CallBB = BasicBlock::Create(Func->getContext(), "invoke_do_call",
Func);
CallBB->moveAfter(Invoke->getParent());
// Append the new frame to the list.
Value *OldList = CopyDebug(
new LoadInst(EHStackTlsVar, "old_eh_stack", CallBB), Invoke);
CopyDebug(new StoreInst(OldList, FrameNextPtr, CallBB), Invoke);
CopyDebug(new StoreInst(ExcInfo, FrameExcInfo, CallBB), Invoke);
CopyDebug(new StoreInst(Frame, EHStackTlsVar, CallBB), Invoke);
SmallVector<Value *, 10> CallArgs;
for (unsigned I = 0, E = Invoke->getNumArgOperands(); I < E; ++I)
CallArgs.push_back(Invoke->getArgOperand(I));
CallInst *NewCall = CallInst::Create(Invoke->getCalledValue(), CallArgs, "",
CallBB);
CopyDebug(NewCall, Invoke);
NewCall->takeName(Invoke);
NewCall->setAttributes(Invoke->getAttributes());
NewCall->setCallingConv(Invoke->getCallingConv());
// Restore the old frame list. We only need to do this on the
// non-exception code path. If an exception is raised, the frame
// list state will be restored for us.
CopyDebug(new StoreInst(OldList, EHStackTlsVar, CallBB), Invoke);
CopyDebug(BranchInst::Create(CallBB, Invoke->getUnwindDest(), IsZero, Invoke),
Invoke);
CopyDebug(BranchInst::Create(Invoke->getNormalDest(), CallBB), Invoke);
updateEdge(Invoke->getNormalDest(), Invoke->getParent(), CallBB);
Invoke->replaceAllUsesWith(NewCall);
Invoke->eraseFromParent();
}
void FuncRewriter::expandResumeInst(ResumeInst *Resume) {
if (!EHResumeFunc) {
EHResumeFunc = Func->getParent()->getFunction("__pnacl_eh_resume");
if (!EHResumeFunc)
report_fatal_error("__pnacl_eh_resume() not defined");
}
// The "resume" instruction gets passed the landingpad's full result
// (struct LandingPadResult above). Extract the exception_obj field
// to pass to __pnacl_eh_resume(), which doesn't need the
// matched_clause_id field.
unsigned Indexes[] = { 0 };
Value *ExceptionPtr =
CopyDebug(ExtractValueInst::Create(Resume->getValue(), Indexes,
"resume_exc", Resume), Resume);
// Cast to the pointer type that __pnacl_eh_resume() expects.
if (EHResumeFunc->getFunctionType()->getFunctionNumParams() != 1)
report_fatal_error("Bad type for __pnacl_eh_resume()&quo
|