1 //===- LowerSetJmp.cpp - Code pertaining to lowering set/long jumps -------===//
3 // This file implements the lowering of setjmp and longjmp to use the
4 // LLVM invoke and unwind instructions as necessary.
6 // Lowering of longjmp is fairly trivial. We replace the call with a
7 // call to the LLVM library function "__llvm_sjljeh_throw_longjmp()".
8 // This unwinds the stack for us calling all of the destructors for
9 // objects allocated on the stack.
11 // At a setjmp call, the basic block is split and the setjmp removed.
12 // The calls in a function that have a setjmp are converted to invoke
13 // where the except part checks to see if it's a longjmp exception and,
14 // if so, if it's handled in the function. If it is, then it gets the
15 // value returned by the longjmp and goes to where the basic block was
16 // split. Invoke instructions are handled in a similar fashion with the
17 // original except block being executed if it isn't a longjmp except
18 // that is handled by that function.
20 //===----------------------------------------------------------------------===//
22 //===----------------------------------------------------------------------===//
23 // FIXME: This pass doesn't deal with PHI statements just yet. That is,
24 // we expect this to occur before SSAification is done. This would seem
25 // to make sense, but in general, it might be a good idea to make this
26 // pass invokable via the "opt" command at will.
27 //===----------------------------------------------------------------------===//
29 #include "llvm/Constants.h"
30 #include "llvm/DerivedTypes.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/Intrinsics.h"
33 #include "llvm/Module.h"
34 #include "llvm/Pass.h"
35 #include "llvm/Support/CFG.h"
36 #include "llvm/Support/InstVisitor.h"
37 #include "Support/DepthFirstIterator.h"
38 #include "Support/Statistic.h"
39 #include "Support/StringExtras.h"
40 #include "Support/VectorExtras.h"
43 Statistic<> LongJmpsTransformed("lowersetjmp",
44 "Number of longjmps transformed");
45 Statistic<> SetJmpsTransformed("lowersetjmp",
46 "Number of setjmps transformed");
48 //===--------------------------------------------------------------------===//
49 // LowerSetJmp pass implementation. This is subclassed from the "Pass"
50 // class because it works on a module as a whole, not a function at a
53 class LowerSetJmp : public Pass,
54 public InstVisitor<LowerSetJmp> {
55 // LLVM library functions...
56 Function* InitSJMap; // __llvm_sjljeh_init_setjmpmap
57 Function* DestroySJMap; // __llvm_sjljeh_destroy_setjmpmap
58 Function* AddSJToMap; // __llvm_sjljeh_add_setjmp_to_map
59 Function* ThrowLongJmp; // __llvm_sjljeh_throw_longjmp
60 Function* TryCatchLJ; // __llvm_sjljeh_try_catching_longjmp_exception
61 Function* IsLJException; // __llvm_sjljeh_is_longjmp_exception
62 Function* GetLJValue; // __llvm_sjljeh_get_longjmp_value
64 typedef std::pair<SwitchInst*, CallInst*> SwitchValuePair;
66 // Keep track of those basic blocks reachable via a depth-first search of
67 // the CFG from a setjmp call. We only need to transform those "call" and
68 // "invoke" instructions that are reachable from the setjmp call site.
69 std::set<BasicBlock*> DFSBlocks;
71 // The setjmp map is going to hold information about which setjmps
72 // were called (each setjmp gets its own number) and with which
73 // buffer it was called.
74 std::map<Function*, AllocaInst*> SJMap;
76 // The rethrow basic block map holds the basic block to branch to if
77 // the exception isn't handled in the current function and needs to
79 std::map<const Function*, BasicBlock*> RethrowBBMap;
81 // The preliminary basic block map holds a basic block that grabs the
82 // exception and determines if it's handled by the current function.
83 std::map<const Function*, BasicBlock*> PrelimBBMap;
85 // The switch/value map holds a switch inst/call inst pair. The
86 // switch inst controls which handler (if any) gets called and the
87 // value is the value returned to that handler by the call to
88 // __llvm_sjljeh_get_longjmp_value.
89 std::map<const Function*, SwitchValuePair> SwitchValMap;
91 // A map of which setjmps we've seen so far in a function.
92 std::map<const Function*, unsigned> SetJmpIDMap;
94 AllocaInst* GetSetJmpMap(Function* Func);
95 BasicBlock* GetRethrowBB(Function* Func);
96 SwitchValuePair GetSJSwitch(Function* Func, BasicBlock* Rethrow);
98 void TransformLongJmpCall(CallInst* Inst);
99 void TransformSetJmpCall(CallInst* Inst);
101 bool IsTransformableFunction(const std::string& Name);
103 void visitCallInst(CallInst& CI);
104 void visitInvokeInst(InvokeInst& II);
105 void visitReturnInst(ReturnInst& RI);
106 void visitUnwindInst(UnwindInst& UI);
109 bool doInitialization(Module& M);
112 RegisterOpt<LowerSetJmp> X("lowersetjmp", "Lower Set Jump");
113 } // end anonymous namespace
115 // run - Run the transformation on the program. We grab the function
116 // prototypes for longjmp and setjmp. If they are used in the program,
117 // then we can go directly to the places they're at and transform them.
118 bool LowerSetJmp::run(Module& M)
120 bool Changed = false;
122 // These are what the functions are called.
123 Function* SetJmp = M.getNamedFunction("llvm.setjmp");
124 Function* LongJmp = M.getNamedFunction("llvm.longjmp");
126 // This program doesn't have longjmp and setjmp calls.
127 if ((!LongJmp || LongJmp->use_empty()) &&
128 (!SetJmp || SetJmp->use_empty())) return false;
130 // Initialize some values and functions we'll need to transform the
131 // setjmp/longjmp functions.
135 std::set<BasicBlock*> BBSet;
137 for (Value::use_iterator B = SetJmp->use_begin(), E = SetJmp->use_end();
139 Instruction* I = cast<Instruction>(*B);
140 BasicBlock* BB = I->getParent();
141 Function* Func = BB->getParent();
142 DFSBlocks.insert(df_begin(BB), df_end(BB));
145 while (!SetJmp->use_empty()) {
146 assert(isa<CallInst>(SetJmp->use_back()) &&
147 "User of setjmp intrinsic not a call?");
148 TransformSetJmpCall(cast<CallInst>(SetJmp->use_back()));
154 while (!LongJmp->use_empty()) {
155 assert(isa<CallInst>(LongJmp->use_back()) &&
156 "User of longjmp intrinsic not a call?");
157 TransformLongJmpCall(cast<CallInst>(LongJmp->use_back()));
161 // Now go through the affected functions and convert calls and invokes
163 for (std::map<Function*, AllocaInst*>::iterator
164 B = SJMap.begin(), E = SJMap.end(); B != E; ++B) {
165 Function* F = B->first;
166 for (Function::iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB)
167 for (BasicBlock::iterator IB = BB->begin(), IE = BB->end(); IB != IE; ) {
169 if (IB != BB->end() && IB->getParent() != BB)
170 break; // The next instruction got moved to a different block!
176 RethrowBBMap.clear();
178 SwitchValMap.clear();
184 // doInitialization - For the lower long/setjmp pass, this ensures that a
185 // module contains a declaration for the intrisic functions we are going
186 // to call to convert longjmp and setjmp calls.
188 // This function is always successful, unless it isn't.
189 bool LowerSetJmp::doInitialization(Module& M)
191 const Type *SBPTy = PointerType::get(Type::SByteTy);
192 const Type *SBPPTy = PointerType::get(SBPTy);
194 // N.B. See llvm/runtime/GCCLibraries/libexception/SJLJ-Exception.h for
195 // a description of the following library functions.
197 // void __llvm_sjljeh_init_setjmpmap(void**)
198 InitSJMap = M.getOrInsertFunction("__llvm_sjljeh_init_setjmpmap",
199 Type::VoidTy, SBPPTy, 0);
200 // void __llvm_sjljeh_destroy_setjmpmap(void**)
201 DestroySJMap = M.getOrInsertFunction("__llvm_sjljeh_destroy_setjmpmap",
202 Type::VoidTy, SBPPTy, 0);
204 // void __llvm_sjljeh_add_setjmp_to_map(void**, void*, unsigned)
205 AddSJToMap = M.getOrInsertFunction("__llvm_sjljeh_add_setjmp_to_map",
206 Type::VoidTy, SBPPTy, SBPTy,
209 // void __llvm_sjljeh_throw_longjmp(int*, int)
210 ThrowLongJmp = M.getOrInsertFunction("__llvm_sjljeh_throw_longjmp",
211 Type::VoidTy, SBPTy, Type::IntTy, 0);
213 // unsigned __llvm_sjljeh_try_catching_longjmp_exception(void **)
215 M.getOrInsertFunction("__llvm_sjljeh_try_catching_longjmp_exception",
216 Type::UIntTy, SBPPTy, 0);
218 // bool __llvm_sjljeh_is_longjmp_exception()
219 IsLJException = M.getOrInsertFunction("__llvm_sjljeh_is_longjmp_exception",
222 // int __llvm_sjljeh_get_longjmp_value()
223 GetLJValue = M.getOrInsertFunction("__llvm_sjljeh_get_longjmp_value",
228 // IsTransformableFunction - Return true if the function name isn't one
229 // of the ones we don't want transformed. Currently, don't transform any
230 // "llvm.{setjmp,longjmp}" functions and none of the setjmp/longjmp error
231 // handling functions (beginning with __llvm_sjljeh_...they don't throw
233 bool LowerSetJmp::IsTransformableFunction(const std::string& Name)
235 std::string SJLJEh("__llvm_sjljeh");
237 if (Name.size() > SJLJEh.size())
238 return std::string(Name.begin(), Name.begin() + SJLJEh.size()) != SJLJEh;
243 // TransformLongJmpCall - Transform a longjmp call into a call to the
244 // internal __llvm_sjljeh_throw_longjmp function. It then takes care of
245 // throwing the exception for us.
246 void LowerSetJmp::TransformLongJmpCall(CallInst* Inst)
248 const Type* SBPTy = PointerType::get(Type::SByteTy);
250 // Create the call to "__llvm_sjljeh_throw_longjmp". This takes the
251 // same parameters as "longjmp", except that the buffer is cast to a
252 // char*. It returns "void", so it doesn't need to replace any of
253 // Inst's uses and doesn't get a name.
254 CastInst* CI = new CastInst(Inst->getOperand(1), SBPTy, "LJBuf", Inst);
255 new CallInst(ThrowLongJmp, make_vector<Value*>(CI, Inst->getOperand(2), 0),
258 SwitchValuePair& SVP = SwitchValMap[Inst->getParent()->getParent()];
260 // If the function has a setjmp call in it (they are transformed first)
261 // we should branch to the basic block that determines if this longjmp
262 // is applicable here. Otherwise, issue an unwind.
264 new BranchInst(SVP.first->getParent(), Inst);
266 new UnwindInst(Inst);
268 // Remove all insts after the branch/unwind inst.
269 Inst->getParent()->getInstList().erase(Inst,
270 Inst->getParent()->getInstList().end());
272 ++LongJmpsTransformed;
275 // GetSetJmpMap - Retrieve (create and initialize, if necessary) the
276 // setjmp map. This map is going to hold information about which setjmps
277 // were called (each setjmp gets its own number) and with which buffer it
278 // was called. There can be only one!
279 AllocaInst* LowerSetJmp::GetSetJmpMap(Function* Func)
281 if (SJMap[Func]) return SJMap[Func];
283 // Insert the setjmp map initialization before the first instruction in
285 Instruction* Inst = Func->getEntryBlock().begin();
286 assert(Inst && "Couldn't find even ONE instruction in entry block!");
288 // Fill in the alloca and call to initialize the SJ map.
289 const Type *SBPTy = PointerType::get(Type::SByteTy);
290 AllocaInst* Map = new AllocaInst(SBPTy, 0, "SJMap", Inst);
291 new CallInst(InitSJMap, make_vector<Value*>(Map, 0), "", Inst);
292 return SJMap[Func] = Map;
295 // GetRethrowBB - Only one rethrow basic block is needed per function.
296 // If this is a longjmp exception but not handled in this block, this BB
297 // performs the rethrow.
298 BasicBlock* LowerSetJmp::GetRethrowBB(Function* Func)
300 if (RethrowBBMap[Func]) return RethrowBBMap[Func];
302 // The basic block we're going to jump to if we need to rethrow the
304 BasicBlock* Rethrow = new BasicBlock("RethrowExcept", Func);
305 BasicBlock::InstListType& RethrowBlkIL = Rethrow->getInstList();
307 // Fill in the "Rethrow" BB with a call to rethrow the exception. This
308 // is the last instruction in the BB since at this point the runtime
309 // should exit this function and go to the next function.
310 RethrowBlkIL.push_back(new UnwindInst());
311 return RethrowBBMap[Func] = Rethrow;
314 // GetSJSwitch - Return the switch statement that controls which handler
315 // (if any) gets called and the value returned to that handler.
316 LowerSetJmp::SwitchValuePair LowerSetJmp::GetSJSwitch(Function* Func,
319 if (SwitchValMap[Func].first) return SwitchValMap[Func];
321 BasicBlock* LongJmpPre = new BasicBlock("LongJmpBlkPre", Func);
322 BasicBlock::InstListType& LongJmpPreIL = LongJmpPre->getInstList();
324 // Keep track of the preliminary basic block for some of the other
326 PrelimBBMap[Func] = LongJmpPre;
328 // Grab the exception.
330 CallInst(IsLJException, std::vector<Value*>(), "IsLJExcept");
331 LongJmpPreIL.push_back(Cond);
333 // The "decision basic block" gets the number associated with the
334 // setjmp call returning to switch on and the value returned by
336 BasicBlock* DecisionBB = new BasicBlock("LJDecisionBB", Func);
337 BasicBlock::InstListType& DecisionBBIL = DecisionBB->getInstList();
339 LongJmpPreIL.push_back(new BranchInst(DecisionBB, Rethrow, Cond));
341 // Fill in the "decision" basic block.
342 CallInst* LJVal = new CallInst(GetLJValue, std::vector<Value*>(), "LJVal");
343 DecisionBBIL.push_back(LJVal);
344 CallInst* SJNum = new
345 CallInst(TryCatchLJ, make_vector<Value*>(GetSetJmpMap(Func), 0), "SJNum");
346 DecisionBBIL.push_back(SJNum);
348 SwitchInst* SI = new SwitchInst(SJNum, Rethrow);
349 DecisionBBIL.push_back(SI);
350 return SwitchValMap[Func] = SwitchValuePair(SI, LJVal);
353 // TransformSetJmpCall - The setjmp call is a bit trickier to transform.
354 // We're going to convert all setjmp calls to nops. Then all "call" and
355 // "invoke" instructions in the function are converted to "invoke" where
356 // the "except" branch is used when returning from a longjmp call.
357 void LowerSetJmp::TransformSetJmpCall(CallInst* Inst)
359 BasicBlock* ABlock = Inst->getParent();
360 Function* Func = ABlock->getParent();
362 // Add this setjmp to the setjmp map.
363 const Type* SBPTy = PointerType::get(Type::SByteTy);
364 CastInst* BufPtr = new CastInst(Inst->getOperand(1), SBPTy, "SBJmpBuf", Inst);
365 new CallInst(AddSJToMap,
366 make_vector<Value*>(GetSetJmpMap(Func), BufPtr,
367 ConstantUInt::get(Type::UIntTy,
368 SetJmpIDMap[Func]++), 0),
371 // Change the setjmp call into a branch statement. We'll remove the
372 // setjmp call in a little bit. No worries.
373 BasicBlock* SetJmpContBlock = ABlock->splitBasicBlock(Inst);
374 assert(SetJmpContBlock && "Couldn't split setjmp BB!!");
376 SetJmpContBlock->setName("SetJmpContBlock");
378 // Reposition the split BB in the BB list to make things tidier.
379 Func->getBasicBlockList().remove(SetJmpContBlock);
380 Func->getBasicBlockList().insert(++Function::iterator(ABlock),
383 // This PHI node will be in the new block created from the
384 // splitBasicBlock call.
385 PHINode* PHI = new PHINode(Type::IntTy, "SetJmpReturn", Inst);
387 // Coming from a call to setjmp, the return is 0.
388 PHI->addIncoming(ConstantInt::getNullValue(Type::IntTy), ABlock);
390 // Add the case for this setjmp's number...
391 SwitchValuePair SVP = GetSJSwitch(Func, GetRethrowBB(Func));
392 SVP.first->addCase(ConstantUInt::get(Type::UIntTy, SetJmpIDMap[Func] - 1),
395 // Value coming from the handling of the exception.
396 PHI->addIncoming(SVP.second, SVP.second->getParent());
398 // Replace all uses of this instruction with the PHI node created by
399 // the eradication of setjmp.
400 Inst->replaceAllUsesWith(PHI);
401 Inst->getParent()->getInstList().erase(Inst);
403 ++SetJmpsTransformed;
406 // visitCallInst - This converts all LLVM call instructions into invoke
407 // instructions. The except part of the invoke goes to the "LongJmpBlkPre"
408 // that grabs the exception and proceeds to determine if it's a longjmp
410 void LowerSetJmp::visitCallInst(CallInst& CI)
412 if (CI.getCalledFunction())
413 if (!IsTransformableFunction(CI.getCalledFunction()->getName()) ||
414 CI.getCalledFunction()->isIntrinsic()) return;
416 BasicBlock* OldBB = CI.getParent();
417 Function* Func = OldBB->getParent();
419 // If not reachable from a setjmp call, don't transform.
420 if (!DFSBlocks.count(OldBB)) return;
422 BasicBlock* NewBB = OldBB->splitBasicBlock(CI);
423 assert(NewBB && "Couldn't split BB of \"call\" instruction!!");
424 NewBB->setName("Call2Invoke");
426 // Reposition the split BB in the BB list to make things tidier.
427 Func->getBasicBlockList().remove(NewBB);
428 Func->getBasicBlockList().insert(++Function::iterator(OldBB), NewBB);
430 // Construct the new "invoke" instruction.
431 TerminatorInst* Term = OldBB->getTerminator();
432 std::vector<Value*> Params(CI.op_begin() + 1, CI.op_end());
434 InvokeInst(CI.getCalledValue(), NewBB, PrelimBBMap[Func],
435 Params, CI.getName(), Term);
437 // Replace the old call inst with the invoke inst and remove the call.
438 CI.replaceAllUsesWith(II);
439 CI.getParent()->getInstList().erase(&CI);
441 // The old terminator is useless now that we have the invoke inst.
442 Term->getParent()->getInstList().erase(Term);
445 // visitInvokeInst - Converting the "invoke" instruction is fairly
446 // straight-forward. The old exception part is replaced by a query asking
447 // if this is a longjmp exception. If it is, then it goes to the longjmp
448 // exception blocks. Otherwise, control is passed the old exception.
449 void LowerSetJmp::visitInvokeInst(InvokeInst& II)
451 if (II.getCalledFunction())
452 if (!IsTransformableFunction(II.getCalledFunction()->getName()) ||
453 II.getCalledFunction()->isIntrinsic()) return;
455 BasicBlock* BB = II.getParent();
456 Function* Func = BB->getParent();
458 // If not reachable from a setjmp call, don't transform.
459 if (!DFSBlocks.count(BB)) return;
461 BasicBlock* NormalBB = II.getNormalDest();
462 BasicBlock* ExceptBB = II.getExceptionalDest();
464 BasicBlock* NewExceptBB = new BasicBlock("InvokeExcept", Func);
465 BasicBlock::InstListType& InstList = NewExceptBB->getInstList();
467 // If this is a longjmp exception, then branch to the preliminary BB of
468 // the longjmp exception handling. Otherwise, go to the old exception.
469 CallInst* IsLJExcept = new
470 CallInst(IsLJException, std::vector<Value*>(), "IsLJExcept");
471 InstList.push_back(IsLJExcept);
473 BranchInst* BR = new BranchInst(PrelimBBMap[Func], ExceptBB, IsLJExcept);
474 InstList.push_back(BR);
476 II.setExceptionalDest(NewExceptBB);
479 // visitReturnInst - We want to destroy the setjmp map upon exit from the
481 void LowerSetJmp::visitReturnInst(ReturnInst& RI)
483 Function* Func = RI.getParent()->getParent();
484 new CallInst(DestroySJMap, make_vector<Value*>(GetSetJmpMap(Func), 0),
488 // visitUnwindInst - We want to destroy the setjmp map upon exit from the
490 void LowerSetJmp::visitUnwindInst(UnwindInst& UI)
492 Function* Func = UI.getParent()->getParent();
493 new CallInst(DestroySJMap, make_vector<Value*>(GetSetJmpMap(Func), 0),
497 Pass* createLowerSetJmpPass()
499 return new LowerSetJmp();