1 //===- LowerSetJmp.cpp - Code pertaining to lowering set/long jumps -------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the lowering of setjmp and longjmp to use the
11 // LLVM invoke and unwind instructions as necessary.
13 // Lowering of longjmp is fairly trivial. We replace the call with a
14 // call to the LLVM library function "__llvm_sjljeh_throw_longjmp()".
15 // This unwinds the stack for us calling all of the destructors for
16 // objects allocated on the stack.
18 // At a setjmp call, the basic block is split and the setjmp removed.
19 // The calls in a function that have a setjmp are converted to invoke
20 // where the except part checks to see if it's a longjmp exception and,
21 // if so, if it's handled in the function. If it is, then it gets the
22 // value returned by the longjmp and goes to where the basic block was
23 // split. Invoke instructions are handled in a similar fashion with the
24 // original except block being executed if it isn't a longjmp except
25 // that is handled by that function.
27 //===----------------------------------------------------------------------===//
29 //===----------------------------------------------------------------------===//
30 // FIXME: This pass doesn't deal with PHI statements just yet. That is,
31 // we expect this to occur before SSAification is done. This would seem
32 // to make sense, but in general, it might be a good idea to make this
33 // pass invokable via the "opt" command at will.
34 //===----------------------------------------------------------------------===//
36 #include "llvm/Constants.h"
37 #include "llvm/DerivedTypes.h"
38 #include "llvm/Instructions.h"
39 #include "llvm/Intrinsics.h"
40 #include "llvm/Module.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/CFG.h"
43 #include "llvm/Support/InstVisitor.h"
44 #include "Support/DepthFirstIterator.h"
45 #include "Support/Statistic.h"
46 #include "Support/StringExtras.h"
47 #include "Support/VectorExtras.h"
50 Statistic<> LongJmpsTransformed("lowersetjmp",
51 "Number of longjmps transformed");
52 Statistic<> SetJmpsTransformed("lowersetjmp",
53 "Number of setjmps transformed");
55 //===--------------------------------------------------------------------===//
56 // LowerSetJmp pass implementation. This is subclassed from the "Pass"
57 // class because it works on a module as a whole, not a function at a
60 class LowerSetJmp : public Pass,
61 public InstVisitor<LowerSetJmp> {
62 // LLVM library functions...
63 Function* InitSJMap; // __llvm_sjljeh_init_setjmpmap
64 Function* DestroySJMap; // __llvm_sjljeh_destroy_setjmpmap
65 Function* AddSJToMap; // __llvm_sjljeh_add_setjmp_to_map
66 Function* ThrowLongJmp; // __llvm_sjljeh_throw_longjmp
67 Function* TryCatchLJ; // __llvm_sjljeh_try_catching_longjmp_exception
68 Function* IsLJException; // __llvm_sjljeh_is_longjmp_exception
69 Function* GetLJValue; // __llvm_sjljeh_get_longjmp_value
71 typedef std::pair<SwitchInst*, CallInst*> SwitchValuePair;
73 // Keep track of those basic blocks reachable via a depth-first search of
74 // the CFG from a setjmp call. We only need to transform those "call" and
75 // "invoke" instructions that are reachable from the setjmp call site.
76 std::set<BasicBlock*> DFSBlocks;
78 // The setjmp map is going to hold information about which setjmps
79 // were called (each setjmp gets its own number) and with which
80 // buffer it was called.
81 std::map<Function*, AllocaInst*> SJMap;
83 // The rethrow basic block map holds the basic block to branch to if
84 // the exception isn't handled in the current function and needs to
86 std::map<const Function*, BasicBlock*> RethrowBBMap;
88 // The preliminary basic block map holds a basic block that grabs the
89 // exception and determines if it's handled by the current function.
90 std::map<const Function*, BasicBlock*> PrelimBBMap;
92 // The switch/value map holds a switch inst/call inst pair. The
93 // switch inst controls which handler (if any) gets called and the
94 // value is the value returned to that handler by the call to
95 // __llvm_sjljeh_get_longjmp_value.
96 std::map<const Function*, SwitchValuePair> SwitchValMap;
98 // A map of which setjmps we've seen so far in a function.
99 std::map<const Function*, unsigned> SetJmpIDMap;
101 AllocaInst* GetSetJmpMap(Function* Func);
102 BasicBlock* GetRethrowBB(Function* Func);
103 SwitchValuePair GetSJSwitch(Function* Func, BasicBlock* Rethrow);
105 void TransformLongJmpCall(CallInst* Inst);
106 void TransformSetJmpCall(CallInst* Inst);
108 bool IsTransformableFunction(const std::string& Name);
110 void visitCallInst(CallInst& CI);
111 void visitInvokeInst(InvokeInst& II);
112 void visitReturnInst(ReturnInst& RI);
113 void visitUnwindInst(UnwindInst& UI);
116 bool doInitialization(Module& M);
119 RegisterOpt<LowerSetJmp> X("lowersetjmp", "Lower Set Jump");
120 } // end anonymous namespace
122 // run - Run the transformation on the program. We grab the function
123 // prototypes for longjmp and setjmp. If they are used in the program,
124 // then we can go directly to the places they're at and transform them.
125 bool LowerSetJmp::run(Module& M)
127 bool Changed = false;
129 // These are what the functions are called.
130 Function* SetJmp = M.getNamedFunction("llvm.setjmp");
131 Function* LongJmp = M.getNamedFunction("llvm.longjmp");
133 // This program doesn't have longjmp and setjmp calls.
134 if ((!LongJmp || LongJmp->use_empty()) &&
135 (!SetJmp || SetJmp->use_empty())) return false;
137 // Initialize some values and functions we'll need to transform the
138 // setjmp/longjmp functions.
142 for (Value::use_iterator B = SetJmp->use_begin(), E = SetJmp->use_end();
144 BasicBlock* BB = cast<Instruction>(*B)->getParent();
145 for (df_ext_iterator<BasicBlock*> I = df_ext_begin(BB, DFSBlocks),
146 E = df_ext_end(BB, DFSBlocks); I != E; ++I)
150 while (!SetJmp->use_empty()) {
151 assert(isa<CallInst>(SetJmp->use_back()) &&
152 "User of setjmp intrinsic not a call?");
153 TransformSetJmpCall(cast<CallInst>(SetJmp->use_back()));
159 while (!LongJmp->use_empty()) {
160 assert(isa<CallInst>(LongJmp->use_back()) &&
161 "User of longjmp intrinsic not a call?");
162 TransformLongJmpCall(cast<CallInst>(LongJmp->use_back()));
166 // Now go through the affected functions and convert calls and invokes
168 for (std::map<Function*, AllocaInst*>::iterator
169 B = SJMap.begin(), E = SJMap.end(); B != E; ++B) {
170 Function* F = B->first;
171 for (Function::iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB)
172 for (BasicBlock::iterator IB = BB->begin(), IE = BB->end(); IB != IE; ) {
174 if (IB != BB->end() && IB->getParent() != BB)
175 break; // The next instruction got moved to a different block!
181 RethrowBBMap.clear();
183 SwitchValMap.clear();
189 // doInitialization - For the lower long/setjmp pass, this ensures that a
190 // module contains a declaration for the intrisic functions we are going
191 // to call to convert longjmp and setjmp calls.
193 // This function is always successful, unless it isn't.
194 bool LowerSetJmp::doInitialization(Module& M)
196 const Type *SBPTy = PointerType::get(Type::SByteTy);
197 const Type *SBPPTy = PointerType::get(SBPTy);
199 // N.B. See llvm/runtime/GCCLibraries/libexception/SJLJ-Exception.h for
200 // a description of the following library functions.
202 // void __llvm_sjljeh_init_setjmpmap(void**)
203 InitSJMap = M.getOrInsertFunction("__llvm_sjljeh_init_setjmpmap",
204 Type::VoidTy, SBPPTy, 0);
205 // void __llvm_sjljeh_destroy_setjmpmap(void**)
206 DestroySJMap = M.getOrInsertFunction("__llvm_sjljeh_destroy_setjmpmap",
207 Type::VoidTy, SBPPTy, 0);
209 // void __llvm_sjljeh_add_setjmp_to_map(void**, void*, unsigned)
210 AddSJToMap = M.getOrInsertFunction("__llvm_sjljeh_add_setjmp_to_map",
211 Type::VoidTy, SBPPTy, SBPTy,
214 // void __llvm_sjljeh_throw_longjmp(int*, int)
215 ThrowLongJmp = M.getOrInsertFunction("__llvm_sjljeh_throw_longjmp",
216 Type::VoidTy, SBPTy, Type::IntTy, 0);
218 // unsigned __llvm_sjljeh_try_catching_longjmp_exception(void **)
220 M.getOrInsertFunction("__llvm_sjljeh_try_catching_longjmp_exception",
221 Type::UIntTy, SBPPTy, 0);
223 // bool __llvm_sjljeh_is_longjmp_exception()
224 IsLJException = M.getOrInsertFunction("__llvm_sjljeh_is_longjmp_exception",
227 // int __llvm_sjljeh_get_longjmp_value()
228 GetLJValue = M.getOrInsertFunction("__llvm_sjljeh_get_longjmp_value",
233 // IsTransformableFunction - Return true if the function name isn't one
234 // of the ones we don't want transformed. Currently, don't transform any
235 // "llvm.{setjmp,longjmp}" functions and none of the setjmp/longjmp error
236 // handling functions (beginning with __llvm_sjljeh_...they don't throw
238 bool LowerSetJmp::IsTransformableFunction(const std::string& Name)
240 std::string SJLJEh("__llvm_sjljeh");
242 if (Name.size() > SJLJEh.size())
243 return std::string(Name.begin(), Name.begin() + SJLJEh.size()) != SJLJEh;
248 // TransformLongJmpCall - Transform a longjmp call into a call to the
249 // internal __llvm_sjljeh_throw_longjmp function. It then takes care of
250 // throwing the exception for us.
251 void LowerSetJmp::TransformLongJmpCall(CallInst* Inst)
253 const Type* SBPTy = PointerType::get(Type::SByteTy);
255 // Create the call to "__llvm_sjljeh_throw_longjmp". This takes the
256 // same parameters as "longjmp", except that the buffer is cast to a
257 // char*. It returns "void", so it doesn't need to replace any of
258 // Inst's uses and doesn't get a name.
259 CastInst* CI = new CastInst(Inst->getOperand(1), SBPTy, "LJBuf", Inst);
260 new CallInst(ThrowLongJmp, make_vector<Value*>(CI, Inst->getOperand(2), 0),
263 SwitchValuePair& SVP = SwitchValMap[Inst->getParent()->getParent()];
265 // If the function has a setjmp call in it (they are transformed first)
266 // we should branch to the basic block that determines if this longjmp
267 // is applicable here. Otherwise, issue an unwind.
269 new BranchInst(SVP.first->getParent(), Inst);
271 new UnwindInst(Inst);
273 // Remove all insts after the branch/unwind inst.
274 Inst->getParent()->getInstList().erase(Inst,
275 Inst->getParent()->getInstList().end());
277 ++LongJmpsTransformed;
280 // GetSetJmpMap - Retrieve (create and initialize, if necessary) the
281 // setjmp map. This map is going to hold information about which setjmps
282 // were called (each setjmp gets its own number) and with which buffer it
283 // was called. There can be only one!
284 AllocaInst* LowerSetJmp::GetSetJmpMap(Function* Func)
286 if (SJMap[Func]) return SJMap[Func];
288 // Insert the setjmp map initialization before the first instruction in
290 Instruction* Inst = Func->getEntryBlock().begin();
291 assert(Inst && "Couldn't find even ONE instruction in entry block!");
293 // Fill in the alloca and call to initialize the SJ map.
294 const Type *SBPTy = PointerType::get(Type::SByteTy);
295 AllocaInst* Map = new AllocaInst(SBPTy, 0, "SJMap", Inst);
296 new CallInst(InitSJMap, make_vector<Value*>(Map, 0), "", Inst);
297 return SJMap[Func] = Map;
300 // GetRethrowBB - Only one rethrow basic block is needed per function.
301 // If this is a longjmp exception but not handled in this block, this BB
302 // performs the rethrow.
303 BasicBlock* LowerSetJmp::GetRethrowBB(Function* Func)
305 if (RethrowBBMap[Func]) return RethrowBBMap[Func];
307 // The basic block we're going to jump to if we need to rethrow the
309 BasicBlock* Rethrow = new BasicBlock("RethrowExcept", Func);
310 BasicBlock::InstListType& RethrowBlkIL = Rethrow->getInstList();
312 // Fill in the "Rethrow" BB with a call to rethrow the exception. This
313 // is the last instruction in the BB since at this point the runtime
314 // should exit this function and go to the next function.
315 RethrowBlkIL.push_back(new UnwindInst());
316 return RethrowBBMap[Func] = Rethrow;
319 // GetSJSwitch - Return the switch statement that controls which handler
320 // (if any) gets called and the value returned to that handler.
321 LowerSetJmp::SwitchValuePair LowerSetJmp::GetSJSwitch(Function* Func,
324 if (SwitchValMap[Func].first) return SwitchValMap[Func];
326 BasicBlock* LongJmpPre = new BasicBlock("LongJmpBlkPre", Func);
327 BasicBlock::InstListType& LongJmpPreIL = LongJmpPre->getInstList();
329 // Keep track of the preliminary basic block for some of the other
331 PrelimBBMap[Func] = LongJmpPre;
333 // Grab the exception.
335 CallInst(IsLJException, std::vector<Value*>(), "IsLJExcept");
336 LongJmpPreIL.push_back(Cond);
338 // The "decision basic block" gets the number associated with the
339 // setjmp call returning to switch on and the value returned by
341 BasicBlock* DecisionBB = new BasicBlock("LJDecisionBB", Func);
342 BasicBlock::InstListType& DecisionBBIL = DecisionBB->getInstList();
344 LongJmpPreIL.push_back(new BranchInst(DecisionBB, Rethrow, Cond));
346 // Fill in the "decision" basic block.
347 CallInst* LJVal = new CallInst(GetLJValue, std::vector<Value*>(), "LJVal");
348 DecisionBBIL.push_back(LJVal);
349 CallInst* SJNum = new
350 CallInst(TryCatchLJ, make_vector<Value*>(GetSetJmpMap(Func), 0), "SJNum");
351 DecisionBBIL.push_back(SJNum);
353 SwitchInst* SI = new SwitchInst(SJNum, Rethrow);
354 DecisionBBIL.push_back(SI);
355 return SwitchValMap[Func] = SwitchValuePair(SI, LJVal);
358 // TransformSetJmpCall - The setjmp call is a bit trickier to transform.
359 // We're going to convert all setjmp calls to nops. Then all "call" and
360 // "invoke" instructions in the function are converted to "invoke" where
361 // the "except" branch is used when returning from a longjmp call.
362 void LowerSetJmp::TransformSetJmpCall(CallInst* Inst)
364 BasicBlock* ABlock = Inst->getParent();
365 Function* Func = ABlock->getParent();
367 // Add this setjmp to the setjmp map.
368 const Type* SBPTy = PointerType::get(Type::SByteTy);
369 CastInst* BufPtr = new CastInst(Inst->getOperand(1), SBPTy, "SBJmpBuf", Inst);
370 new CallInst(AddSJToMap,
371 make_vector<Value*>(GetSetJmpMap(Func), BufPtr,
372 ConstantUInt::get(Type::UIntTy,
373 SetJmpIDMap[Func]++), 0),
376 // Change the setjmp call into a branch statement. We'll remove the
377 // setjmp call in a little bit. No worries.
378 BasicBlock* SetJmpContBlock = ABlock->splitBasicBlock(Inst);
379 assert(SetJmpContBlock && "Couldn't split setjmp BB!!");
381 SetJmpContBlock->setName("SetJmpContBlock");
383 // Reposition the split BB in the BB list to make things tidier.
384 Func->getBasicBlockList().remove(SetJmpContBlock);
385 Func->getBasicBlockList().insert(++Function::iterator(ABlock),
388 // This PHI node will be in the new block created from the
389 // splitBasicBlock call.
390 PHINode* PHI = new PHINode(Type::IntTy, "SetJmpReturn", Inst);
392 // Coming from a call to setjmp, the return is 0.
393 PHI->addIncoming(ConstantInt::getNullValue(Type::IntTy), ABlock);
395 // Add the case for this setjmp's number...
396 SwitchValuePair SVP = GetSJSwitch(Func, GetRethrowBB(Func));
397 SVP.first->addCase(ConstantUInt::get(Type::UIntTy, SetJmpIDMap[Func] - 1),
400 // Value coming from the handling of the exception.
401 PHI->addIncoming(SVP.second, SVP.second->getParent());
403 // Replace all uses of this instruction with the PHI node created by
404 // the eradication of setjmp.
405 Inst->replaceAllUsesWith(PHI);
406 Inst->getParent()->getInstList().erase(Inst);
408 ++SetJmpsTransformed;
411 // visitCallInst - This converts all LLVM call instructions into invoke
412 // instructions. The except part of the invoke goes to the "LongJmpBlkPre"
413 // that grabs the exception and proceeds to determine if it's a longjmp
415 void LowerSetJmp::visitCallInst(CallInst& CI)
417 if (CI.getCalledFunction())
418 if (!IsTransformableFunction(CI.getCalledFunction()->getName()) ||
419 CI.getCalledFunction()->isIntrinsic()) return;
421 BasicBlock* OldBB = CI.getParent();
423 // If not reachable from a setjmp call, don't transform.
424 if (!DFSBlocks.count(OldBB)) return;
426 BasicBlock* NewBB = OldBB->splitBasicBlock(CI);
427 assert(NewBB && "Couldn't split BB of \"call\" instruction!!");
428 NewBB->setName("Call2Invoke");
430 // Reposition the split BB in the BB list to make things tidier.
431 Function* Func = OldBB->getParent();
432 Func->getBasicBlockList().remove(NewBB);
433 Func->getBasicBlockList().insert(++Function::iterator(OldBB), NewBB);
435 // Construct the new "invoke" instruction.
436 TerminatorInst* Term = OldBB->getTerminator();
437 std::vector<Value*> Params(CI.op_begin() + 1, CI.op_end());
439 InvokeInst(CI.getCalledValue(), NewBB, PrelimBBMap[Func],
440 Params, CI.getName(), Term);
442 // Replace the old call inst with the invoke inst and remove the call.
443 CI.replaceAllUsesWith(II);
444 CI.getParent()->getInstList().erase(&CI);
446 // The old terminator is useless now that we have the invoke inst.
447 Term->getParent()->getInstList().erase(Term);
450 // visitInvokeInst - Converting the "invoke" instruction is fairly
451 // straight-forward. The old exception part is replaced by a query asking
452 // if this is a longjmp exception. If it is, then it goes to the longjmp
453 // exception blocks. Otherwise, control is passed the old exception.
454 void LowerSetJmp::visitInvokeInst(InvokeInst& II)
456 if (II.getCalledFunction())
457 if (!IsTransformableFunction(II.getCalledFunction()->getName()) ||
458 II.getCalledFunction()->isIntrinsic()) return;
460 BasicBlock* BB = II.getParent();
462 // If not reachable from a setjmp call, don't transform.
463 if (!DFSBlocks.count(BB)) return;
465 BasicBlock* NormalBB = II.getNormalDest();
466 BasicBlock* ExceptBB = II.getExceptionalDest();
468 Function* Func = BB->getParent();
469 BasicBlock* NewExceptBB = new BasicBlock("InvokeExcept", Func);
470 BasicBlock::InstListType& InstList = NewExceptBB->getInstList();
472 // If this is a longjmp exception, then branch to the preliminary BB of
473 // the longjmp exception handling. Otherwise, go to the old exception.
474 CallInst* IsLJExcept = new
475 CallInst(IsLJException, std::vector<Value*>(), "IsLJExcept");
476 InstList.push_back(IsLJExcept);
478 BranchInst* BR = new BranchInst(PrelimBBMap[Func], ExceptBB, IsLJExcept);
479 InstList.push_back(BR);
481 II.setExceptionalDest(NewExceptBB);
484 // visitReturnInst - We want to destroy the setjmp map upon exit from the
486 void LowerSetJmp::visitReturnInst(ReturnInst& RI)
488 Function* Func = RI.getParent()->getParent();
489 new CallInst(DestroySJMap, make_vector<Value*>(GetSetJmpMap(Func), 0),
493 // visitUnwindInst - We want to destroy the setjmp map upon exit from the
495 void LowerSetJmp::visitUnwindInst(UnwindInst& UI)
497 Function* Func = UI.getParent()->getParent();
498 new CallInst(DestroySJMap, make_vector<Value*>(GetSetJmpMap(Func), 0),
502 Pass* createLowerSetJmpPass()
504 return new LowerSetJmp();