1 //===- SjLjEHPass.cpp - Eliminate Invoke & Unwind instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This transformation is designed for use by code generators which use SjLj
11 // based exception handling.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "sjljehprepare"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
26 #include "llvm/Transforms/Utils/Local.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetLowering.h"
35 STATISTIC(NumInvokes, "Number of invokes replaced");
36 STATISTIC(NumUnwinds, "Number of unwinds replaced");
37 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
40 class SjLjEHPass : public FunctionPass {
42 const TargetLowering *TLI;
44 const Type *FunctionContextTy;
46 Constant *UnregisterFn;
47 Constant *BuiltinSetjmpFn;
48 Constant *FrameAddrFn;
52 Constant *ExceptionFn;
57 static char ID; // Pass identification, replacement for typeid
58 explicit SjLjEHPass(const TargetLowering *tli = NULL)
59 : FunctionPass(&ID), TLI(tli) { }
60 bool doInitialization(Module &M);
61 bool runOnFunction(Function &F);
63 virtual void getAnalysisUsage(AnalysisUsage &AU) const { }
64 const char *getPassName() const {
65 return "SJLJ Exception Handling preparation";
69 void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
70 void markInvokeCallSite(InvokeInst *II, int InvokeNo, Value *CallSite,
71 SwitchInst *CatchSwitch);
72 void splitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
73 bool insertSjLjEHSupport(Function &F);
75 } // end anonymous namespace
77 char SjLjEHPass::ID = 0;
79 // Public Interface To the SjLjEHPass pass.
80 FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
81 return new SjLjEHPass(TLI);
83 // doInitialization - Set up decalarations and types needed to process
85 bool SjLjEHPass::doInitialization(Module &M) {
86 // Build the function context structure.
87 // builtin_setjmp uses a five word jbuf
88 const Type *VoidPtrTy =
89 Type::getInt8PtrTy(M.getContext());
90 const Type *Int32Ty = Type::getInt32Ty(M.getContext());
92 StructType::get(M.getContext(),
95 ArrayType::get(Int32Ty, 4), // __data
96 VoidPtrTy, // __personality
98 ArrayType::get(VoidPtrTy, 5), // __jbuf
100 RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
101 Type::getVoidTy(M.getContext()),
102 PointerType::getUnqual(FunctionContextTy),
105 M.getOrInsertFunction("_Unwind_SjLj_Unregister",
106 Type::getVoidTy(M.getContext()),
107 PointerType::getUnqual(FunctionContextTy),
109 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
110 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
111 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
112 SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
113 ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
114 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
120 /// insertCallSiteStore - Insert a store of the call-site value to the
122 void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
124 ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
126 // Insert a store of the call-site number
127 new StoreInst(CallSiteNoC, CallSite, true, I); // volatile
130 /// markInvokeCallSite - Insert code to mark the call_site for this invoke
131 void SjLjEHPass::markInvokeCallSite(InvokeInst *II, int InvokeNo,
133 SwitchInst *CatchSwitch) {
134 ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
136 // The runtime comes back to the dispatcher with the call_site - 1 in
137 // the context. Odd, but there it is.
138 ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
141 // If the unwind edge has phi nodes, split the edge.
142 if (isa<PHINode>(II->getUnwindDest()->begin())) {
143 SplitCriticalEdge(II, 1, this);
145 // If there are any phi nodes left, they must have a single predecessor.
146 while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
147 PN->replaceAllUsesWith(PN->getIncomingValue(0));
148 PN->eraseFromParent();
152 // Insert the store of the call site value
153 insertCallSiteStore(II, InvokeNo, CallSite);
155 // Record the call site value for the back end so it stays associated with
157 CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
159 // Add a switch case to our unwind block.
160 CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
161 // We still want this to look like an invoke so we emit the LSDA properly,
162 // so we don't transform the invoke into a call here.
165 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
166 /// we reach blocks we've already seen.
167 static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
168 if (!LiveBBs.insert(BB).second) return; // already been here.
170 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
171 MarkBlocksLiveIn(*PI, LiveBBs);
174 /// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
175 /// we spill into a stack location, guaranteeing that there is nothing live
176 /// across the unwind edge. This process also splits all critical edges
177 /// coming out of invoke's.
179 splitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
180 // First step, split all critical edges from invoke instructions.
181 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
182 InvokeInst *II = Invokes[i];
183 SplitCriticalEdge(II, 0, this);
184 SplitCriticalEdge(II, 1, this);
185 assert(!isa<PHINode>(II->getNormalDest()) &&
186 !isa<PHINode>(II->getUnwindDest()) &&
187 "critical edge splitting left single entry phi nodes?");
190 Function *F = Invokes.back()->getParent()->getParent();
192 // To avoid having to handle incoming arguments specially, we lower each arg
193 // to a copy instruction in the entry block. This ensures that the argument
194 // value itself cannot be live across the entry block.
195 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
196 while (isa<AllocaInst>(AfterAllocaInsertPt) &&
197 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
198 ++AfterAllocaInsertPt;
199 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
201 // This is always a no-op cast because we're casting AI to AI->getType() so
202 // src and destination types are identical. BitCast is the only possibility.
203 CastInst *NC = new BitCastInst(
204 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
205 AI->replaceAllUsesWith(NC);
206 // Normally its is forbidden to replace a CastInst's operand because it
207 // could cause the opcode to reflect an illegal conversion. However, we're
208 // replacing it here with the same value it was constructed with to simply
210 NC->setOperand(0, AI);
213 // Finally, scan the code looking for instructions with bad live ranges.
214 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
215 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
216 // Ignore obvious cases we don't have to handle. In particular, most
217 // instructions either have no uses or only have a single use inside the
218 // current block. Ignore them quickly.
219 Instruction *Inst = II;
220 if (Inst->use_empty()) continue;
221 if (Inst->hasOneUse() &&
222 cast<Instruction>(Inst->use_back())->getParent() == BB &&
223 !isa<PHINode>(Inst->use_back())) continue;
225 // If this is an alloca in the entry block, it's not a real register
227 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
228 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
231 // Avoid iterator invalidation by copying users to a temporary vector.
232 SmallVector<Instruction*,16> Users;
233 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
235 Instruction *User = cast<Instruction>(*UI);
236 if (User->getParent() != BB || isa<PHINode>(User))
237 Users.push_back(User);
240 // Find all of the blocks that this value is live in.
241 std::set<BasicBlock*> LiveBBs;
242 LiveBBs.insert(Inst->getParent());
243 while (!Users.empty()) {
244 Instruction *U = Users.back();
247 if (!isa<PHINode>(U)) {
248 MarkBlocksLiveIn(U->getParent(), LiveBBs);
250 // Uses for a PHI node occur in their predecessor block.
251 PHINode *PN = cast<PHINode>(U);
252 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
253 if (PN->getIncomingValue(i) == Inst)
254 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
258 // Now that we know all of the blocks that this thing is live in, see if
259 // it includes any of the unwind locations.
260 bool NeedsSpill = false;
261 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
262 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
263 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
268 // If we decided we need a spill, do it.
271 DemoteRegToStack(*Inst, true);
276 bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
277 SmallVector<ReturnInst*,16> Returns;
278 SmallVector<UnwindInst*,16> Unwinds;
279 SmallVector<InvokeInst*,16> Invokes;
281 // Look through the terminators of the basic blocks to find invokes, returns
283 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
284 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
285 // Remember all return instructions in case we insert an invoke into this
287 Returns.push_back(RI);
288 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
289 Invokes.push_back(II);
290 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
291 Unwinds.push_back(UI);
294 // If we don't have any invokes or unwinds, there's nothing to do.
295 if (Unwinds.empty() && Invokes.empty()) return false;
297 // Find the eh.selector.* and eh.exception calls. We'll use the first
298 // eh.selector to determine the right personality function to use. For
299 // SJLJ, we always use the same personality for the whole function,
300 // not on a per-selector basis.
301 // FIXME: That's a bit ugly. Better way?
302 SmallVector<CallInst*,16> EH_Selectors;
303 SmallVector<CallInst*,16> EH_Exceptions;
304 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
305 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
306 if (CallInst *CI = dyn_cast<CallInst>(I)) {
307 if (CI->getCalledFunction() == SelectorFn) {
308 if (!PersonalityFn) PersonalityFn = CI->getOperand(2);
309 EH_Selectors.push_back(CI);
310 } else if (CI->getCalledFunction() == ExceptionFn) {
311 EH_Exceptions.push_back(CI);
316 // If we don't have any eh.selector calls, we can't determine the personality
317 // function. Without a personality function, we can't process exceptions.
318 if (!PersonalityFn) return false;
320 NumInvokes += Invokes.size();
321 NumUnwinds += Unwinds.size();
323 if (!Invokes.empty()) {
324 // We have invokes, so we need to add register/unregister calls to get
325 // this function onto the global unwind stack.
327 // First thing we need to do is scan the whole function for values that are
328 // live across unwind edges. Each value that is live across an unwind edge
329 // we spill into a stack location, guaranteeing that there is nothing live
330 // across the unwind edge. This process also splits all critical edges
331 // coming out of invoke's.
332 splitLiveRangesLiveAcrossInvokes(Invokes);
334 BasicBlock *EntryBB = F.begin();
335 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
336 // that needs to be restored on all exits from the function. This is an
337 // alloca because the value needs to be added to the global context list.
338 unsigned Align = 4; // FIXME: Should be a TLI check?
339 AllocaInst *FunctionContext =
340 new AllocaInst(FunctionContextTy, 0, Align,
341 "fcn_context", F.begin()->begin());
344 const Type *Int32Ty = Type::getInt32Ty(F.getContext());
345 Value *Zero = ConstantInt::get(Int32Ty, 0);
346 // We need to also keep around a reference to the call_site field
348 Idxs[1] = ConstantInt::get(Int32Ty, 1);
349 CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
351 EntryBB->getTerminator());
353 // The exception selector comes back in context->data[1]
354 Idxs[1] = ConstantInt::get(Int32Ty, 2);
355 Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
357 EntryBB->getTerminator());
358 Idxs[1] = ConstantInt::get(Int32Ty, 1);
359 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
361 EntryBB->getTerminator());
362 // The exception value comes back in context->data[0]
364 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
366 EntryBB->getTerminator());
368 // The result of the eh.selector call will be replaced with a
369 // a reference to the selector value returned in the function
370 // context. We leave the selector itself so the EH analysis later
372 for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
373 CallInst *I = EH_Selectors[i];
374 Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
375 I->replaceAllUsesWith(SelectorVal);
377 // eh.exception calls are replaced with references to the proper
378 // location in the context. Unlike eh.selector, the eh.exception
379 // calls are removed entirely.
380 for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
381 CallInst *I = EH_Exceptions[i];
382 // Possible for there to be duplicates, so check to make sure
383 // the instruction hasn't already been removed.
384 if (!I->getParent()) continue;
385 Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
386 const Type *Ty = Type::getInt8PtrTy(F.getContext());
387 Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
389 I->replaceAllUsesWith(Val);
390 I->eraseFromParent();
393 // The entry block changes to have the eh.sjlj.setjmp, with a conditional
394 // branch to a dispatch block for non-zero returns. If we return normally,
395 // we're not handling an exception and just register the function context
398 // Create the dispatch block. The dispatch block is basically a big switch
399 // statement that goes to all of the invoke landing pads.
400 BasicBlock *DispatchBlock =
401 BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
403 // Insert a load in the Catch block, and a switch on its value. By default,
404 // we go to a block that just does an unwind (which is the correct action
405 // for a standard call).
406 BasicBlock *UnwindBlock =
407 BasicBlock::Create(F.getContext(), "unwindbb", &F);
408 Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBlock));
410 Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
412 SwitchInst *DispatchSwitch =
413 SwitchInst::Create(DispatchLoad, UnwindBlock, Invokes.size(),
415 // Split the entry block to insert the conditional branch for the setjmp.
416 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
417 "eh.sjlj.setjmp.cont");
419 // Populate the Function Context
421 // 2. Personality function address
422 // 3. jmpbuf (save FP and call eh.sjlj.setjmp)
426 Idxs[1] = ConstantInt::get(Int32Ty, 4);
427 Value *LSDAFieldPtr =
428 GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
430 EntryBB->getTerminator());
431 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
432 EntryBB->getTerminator());
433 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
435 Idxs[1] = ConstantInt::get(Int32Ty, 3);
436 Value *PersonalityFieldPtr =
437 GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
439 EntryBB->getTerminator());
440 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
441 EntryBB->getTerminator());
443 // Save the frame pointer.
444 Idxs[1] = ConstantInt::get(Int32Ty, 5);
446 = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
448 EntryBB->getTerminator());
449 Idxs[1] = ConstantInt::get(Int32Ty, 0);
451 GetElementPtrInst::Create(FieldPtr, Idxs, Idxs+2, "jbuf_fp_gep",
452 EntryBB->getTerminator());
454 Value *Val = CallInst::Create(FrameAddrFn,
455 ConstantInt::get(Int32Ty, 0),
457 EntryBB->getTerminator());
458 new StoreInst(Val, ElemPtr, true, EntryBB->getTerminator());
459 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf
461 CastInst::Create(Instruction::BitCast, FieldPtr,
462 Type::getInt8PtrTy(F.getContext()), "",
463 EntryBB->getTerminator());
464 Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
466 EntryBB->getTerminator());
467 // check the return value of the setjmp. non-zero goes to dispatcher
468 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
469 ICmpInst::ICMP_EQ, DispatchVal, Zero,
471 // Nuke the uncond branch.
472 EntryBB->getTerminator()->eraseFromParent();
474 // Put in a new condbranch in its place.
475 BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
477 // Register the function context and make sure it's known to not throw
479 CallInst::Create(RegisterFn, FunctionContext, "",
480 ContBlock->getTerminator());
481 Register->setDoesNotThrow();
483 // At this point, we are all set up, update the invoke instructions
484 // to mark their call_site values, and fill in the dispatch switch
486 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
487 markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
489 // Mark call instructions that aren't nounwind as no-action
490 // (call_site == -1). Skip the entry block, as prior to then, no function
491 // context has been created for this function and any unexpected exceptions
492 // thrown will go directly to the caller's context, which is what we want
493 // anyway, so no need to do anything here.
494 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
495 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
496 if (CallInst *CI = dyn_cast<CallInst>(I)) {
497 // Ignore calls to the EH builtins (eh.selector, eh.exception)
498 Constant *Callee = CI->getCalledFunction();
499 if (Callee != SelectorFn && Callee != ExceptionFn
500 && !CI->doesNotThrow())
501 insertCallSiteStore(CI, -1, CallSite);
505 // Replace all unwinds with a branch to the unwind handler.
506 // ??? Should this ever happen with sjlj exceptions?
507 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
508 BranchInst::Create(UnwindBlock, Unwinds[i]);
509 Unwinds[i]->eraseFromParent();
512 // Finally, for any returns from this function, if this function contains an
513 // invoke, add a call to unregister the function context.
514 for (unsigned i = 0, e = Returns.size(); i != e; ++i)
515 CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
521 bool SjLjEHPass::runOnFunction(Function &F) {
522 bool Res = insertSjLjEHSupport(F);