1 //===-- DwarfEHPrepare - Prepare exception handling for code generation ---===//
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 pass mulches exception handling code into a form adapted to code
11 // generation. Required if using dwarf exception handling.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "dwarfehprepare"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/Dominators.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Target/TargetLowering.h"
26 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
27 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
30 STATISTIC(NumLandingPadsSplit
, "Number of landing pads split");
31 STATISTIC(NumUnwindsLowered
, "Number of unwind instructions lowered");
32 STATISTIC(NumExceptionValuesMoved
, "Number of eh.exception calls moved");
33 STATISTIC(NumStackTempsIntroduced
, "Number of stack temporaries introduced");
36 class VISIBILITY_HIDDEN DwarfEHPrepare
: public FunctionPass
{
37 const TargetLowering
*TLI
;
40 // The eh.exception intrinsic.
41 Function
*ExceptionValueIntrinsic
;
43 // _Unwind_Resume or the target equivalent.
44 Constant
*RewindFunction
;
46 // Dominator info is used when turning stack temporaries into registers.
48 DominanceFrontier
*DF
;
50 // The function we are running on.
53 // The landing pads for this function.
54 typedef SmallPtrSet
<BasicBlock
*, 8> BBSet
;
57 // Stack temporary used to hold eh.exception values.
58 AllocaInst
*ExceptionValueVar
;
60 bool NormalizeLandingPads();
62 bool MoveExceptionValueCalls();
63 bool FinishStackTemporaries();
64 bool PromoteStackTemporaries();
66 Instruction
*CreateExceptionValueCall(BasicBlock
*BB
);
67 Instruction
*CreateValueLoad(BasicBlock
*BB
);
69 /// CreateReadOfExceptionValue - Return the result of the eh.exception
70 /// intrinsic by calling the intrinsic if in a landing pad, or loading
71 /// it from the exception value variable otherwise.
72 Instruction
*CreateReadOfExceptionValue(BasicBlock
*BB
) {
73 return LandingPads
.count(BB
) ?
74 CreateExceptionValueCall(BB
) : CreateValueLoad(BB
);
78 static char ID
; // Pass identification, replacement for typeid.
79 DwarfEHPrepare(const TargetLowering
*tli
, bool fast
) :
80 FunctionPass(&ID
), TLI(tli
), CompileFast(fast
),
81 ExceptionValueIntrinsic(0), RewindFunction(0) {}
83 virtual bool runOnFunction(Function
&Fn
);
85 // getAnalysisUsage - We need dominance frontiers for memory promotion.
86 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
88 AU
.addRequired
<DominatorTree
>();
89 AU
.addPreserved
<DominatorTree
>();
91 AU
.addRequired
<DominanceFrontier
>();
92 AU
.addPreserved
<DominanceFrontier
>();
95 const char *getPassName() const {
96 return "Exception handling preparation";
100 } // end anonymous namespace
102 char DwarfEHPrepare::ID
= 0;
104 FunctionPass
*llvm::createDwarfEHPass(const TargetLowering
*tli
, bool fast
) {
105 return new DwarfEHPrepare(tli
, fast
);
108 /// NormalizeLandingPads - Normalize and discover landing pads, noting them
109 /// in the LandingPads set. A landing pad is normal if the only CFG edges
110 /// that end at it are unwind edges from invoke instructions.
111 /// Abnormal landing pads are fixed up by redirecting all unwind edges to
112 /// a new basic block which falls through to the original.
113 bool DwarfEHPrepare::NormalizeLandingPads() {
114 bool Changed
= false;
116 for (Function::iterator I
= F
->begin(), E
= F
->end(); I
!= E
; ++I
) {
117 TerminatorInst
*TI
= I
->getTerminator();
118 if (!isa
<InvokeInst
>(TI
))
120 BasicBlock
*LPad
= TI
->getSuccessor(1);
121 // Skip landing pads that have already been normalized.
122 if (LandingPads
.count(LPad
))
125 // Check that only invoke unwind edges end at the landing pad.
126 bool OnlyUnwoundTo
= true;
127 for (pred_iterator PI
= pred_begin(LPad
), PE
= pred_end(LPad
);
129 TerminatorInst
*PT
= (*PI
)->getTerminator();
130 if (!isa
<InvokeInst
>(PT
) || LPad
== PT
->getSuccessor(0)) {
131 OnlyUnwoundTo
= false;
136 // Only unwind edges lead to the landing pad. Remember the landing pad.
137 LandingPads
.insert(LPad
);
141 // At least one normal edge ends at the landing pad. Redirect the unwind
142 // edges to a new basic block which falls through into this one.
144 // Create the new basic block.
145 BasicBlock
*NewBB
= BasicBlock::Create(F
->getContext(),
146 LPad
->getName() + "_unwind_edge");
148 // Insert it into the function right before the original landing pad.
149 LPad
->getParent()->getBasicBlockList().insert(LPad
, NewBB
);
151 // Redirect unwind edges from the original landing pad to NewBB.
152 for (pred_iterator PI
= pred_begin(LPad
), PE
= pred_end(LPad
); PI
!= PE
; ) {
153 TerminatorInst
*PT
= (*PI
++)->getTerminator();
154 if (isa
<InvokeInst
>(PT
) && PT
->getSuccessor(1) == LPad
)
155 // Unwind to the new block.
156 PT
->setSuccessor(1, NewBB
);
159 // If there are any PHI nodes in LPad, we need to update them so that they
160 // merge incoming values from NewBB instead.
161 for (BasicBlock::iterator II
= LPad
->begin(); isa
<PHINode
>(II
); ++II
) {
162 PHINode
*PN
= cast
<PHINode
>(II
);
163 pred_iterator PB
= pred_begin(NewBB
), PE
= pred_end(NewBB
);
165 // Check to see if all of the values coming in via unwind edges are the
166 // same. If so, we don't need to create a new PHI node.
167 Value
*InVal
= PN
->getIncomingValueForBlock(*PB
);
168 for (pred_iterator PI
= PB
; PI
!= PE
; ++PI
) {
169 if (PI
!= PB
&& InVal
!= PN
->getIncomingValueForBlock(*PI
)) {
176 // Different unwind edges have different values. Create a new PHI node
178 PHINode
*NewPN
= PHINode::Create(PN
->getType(), PN
->getName()+".unwind",
180 // Add an entry for each unwind edge, using the value from the old PHI.
181 for (pred_iterator PI
= PB
; PI
!= PE
; ++PI
)
182 NewPN
->addIncoming(PN
->getIncomingValueForBlock(*PI
), *PI
);
184 // Now use this new PHI as the common incoming value for NewBB in PN.
188 // Revector exactly one entry in the PHI node to come from NewBB
189 // and delete all other entries that come from unwind edges. If
190 // there are both normal and unwind edges from the same predecessor,
191 // this leaves an entry for the normal edge.
192 for (pred_iterator PI
= PB
; PI
!= PE
; ++PI
)
193 PN
->removeIncomingValue(*PI
);
194 PN
->addIncoming(InVal
, NewBB
);
197 // Add a fallthrough from NewBB to the original landing pad.
198 BranchInst::Create(LPad
, NewBB
);
200 // Now update DominatorTree and DominanceFrontier analysis information.
202 DT
->splitBlock(NewBB
);
204 DF
->splitBlock(NewBB
);
206 // Remember the newly constructed landing pad. The original landing pad
207 // LPad is no longer a landing pad now that all unwind edges have been
208 // revectored to NewBB.
209 LandingPads
.insert(NewBB
);
210 ++NumLandingPadsSplit
;
217 /// LowerUnwinds - Turn unwind instructions into calls to _Unwind_Resume,
218 /// rethrowing any previously caught exception. This will crash horribly
219 /// at runtime if there is no such exception: using unwind to throw a new
220 /// exception is currently not supported.
221 bool DwarfEHPrepare::LowerUnwinds() {
222 bool Changed
= false;
224 for (Function::iterator I
= F
->begin(), E
= F
->end(); I
!= E
; ++I
) {
225 TerminatorInst
*TI
= I
->getTerminator();
226 if (!isa
<UnwindInst
>(TI
))
229 // Replace the unwind instruction with a call to _Unwind_Resume (or the
230 // appropriate target equivalent) followed by an UnreachableInst.
232 // Find the rewind function if we didn't already.
233 if (!RewindFunction
) {
234 std::vector
<const Type
*> Params(1,
235 PointerType::getUnqual(Type::getInt8Ty(TI
->getContext())));
236 FunctionType
*FTy
= FunctionType::get(Type::getVoidTy(TI
->getContext()),
238 const char *RewindName
= TLI
->getLibcallName(RTLIB::UNWIND_RESUME
);
239 RewindFunction
= F
->getParent()->getOrInsertFunction(RewindName
, FTy
);
242 // Create the call...
243 CallInst::Create(RewindFunction
, CreateReadOfExceptionValue(I
), "", TI
);
244 // ...followed by an UnreachableInst.
245 new UnreachableInst(TI
->getContext(), TI
);
247 // Nuke the unwind instruction.
248 TI
->eraseFromParent();
256 /// MoveExceptionValueCalls - Ensure that eh.exception is only ever called from
257 /// landing pads by replacing calls outside of landing pads with loads from a
258 /// stack temporary. Move eh.exception calls inside landing pads to the start
259 /// of the landing pad (optional, but may make things simpler for later passes).
260 bool DwarfEHPrepare::MoveExceptionValueCalls() {
261 // If the eh.exception intrinsic is not declared in the module then there is
262 // nothing to do. Speed up compilation by checking for this common case.
263 if (!ExceptionValueIntrinsic
&&
264 !F
->getParent()->getFunction(Intrinsic::getName(Intrinsic::eh_exception
)))
267 bool Changed
= false;
269 for (Function::iterator BB
= F
->begin(), E
= F
->end(); BB
!= E
; ++BB
) {
270 for (BasicBlock::iterator II
= BB
->begin(), E
= BB
->end(); II
!= E
;)
271 if (IntrinsicInst
*CI
= dyn_cast
<IntrinsicInst
>(II
++))
272 if (CI
->getIntrinsicID() == Intrinsic::eh_exception
) {
273 if (!CI
->use_empty()) {
274 Value
*ExceptionValue
= CreateReadOfExceptionValue(BB
);
275 if (CI
== ExceptionValue
) {
276 // The call was at the start of a landing pad - leave it alone.
277 assert(LandingPads
.count(BB
) &&
278 "Created eh.exception call outside landing pad!");
281 CI
->replaceAllUsesWith(ExceptionValue
);
283 CI
->eraseFromParent();
284 ++NumExceptionValuesMoved
;
292 /// FinishStackTemporaries - If we introduced a stack variable to hold the
293 /// exception value then initialize it in each landing pad.
294 bool DwarfEHPrepare::FinishStackTemporaries() {
295 if (!ExceptionValueVar
)
299 bool Changed
= false;
301 // Make sure that there is a store of the exception value at the start of
303 for (BBSet::iterator LI
= LandingPads
.begin(), LE
= LandingPads
.end();
305 Instruction
*ExceptionValue
= CreateReadOfExceptionValue(*LI
);
306 Instruction
*Store
= new StoreInst(ExceptionValue
, ExceptionValueVar
);
307 Store
->insertAfter(ExceptionValue
);
314 /// PromoteStackTemporaries - Turn any stack temporaries we introduced into
315 /// registers if possible.
316 bool DwarfEHPrepare::PromoteStackTemporaries() {
317 if (ExceptionValueVar
&& DT
&& DF
&& isAllocaPromotable(ExceptionValueVar
)) {
318 // Turn the exception temporary into registers and phi nodes if possible.
319 std::vector
<AllocaInst
*> Allocas(1, ExceptionValueVar
);
320 PromoteMemToReg(Allocas
, *DT
, *DF
, ExceptionValueVar
->getContext());
326 /// CreateExceptionValueCall - Insert a call to the eh.exception intrinsic at
327 /// the start of the basic block (unless there already is one, in which case
328 /// the existing call is returned).
329 Instruction
*DwarfEHPrepare::CreateExceptionValueCall(BasicBlock
*BB
) {
330 Instruction
*Start
= BB
->getFirstNonPHI();
331 // Is this a call to eh.exception?
332 if (IntrinsicInst
*CI
= dyn_cast
<IntrinsicInst
>(Start
))
333 if (CI
->getIntrinsicID() == Intrinsic::eh_exception
)
334 // Reuse the existing call.
337 // Find the eh.exception intrinsic if we didn't already.
338 if (!ExceptionValueIntrinsic
)
339 ExceptionValueIntrinsic
= Intrinsic::getDeclaration(F
->getParent(),
340 Intrinsic::eh_exception
);
343 return CallInst::Create(ExceptionValueIntrinsic
, "eh.value.call", Start
);
346 /// CreateValueLoad - Insert a load of the exception value stack variable
347 /// (creating it if necessary) at the start of the basic block (unless
348 /// there already is a load, in which case the existing load is returned).
349 Instruction
*DwarfEHPrepare::CreateValueLoad(BasicBlock
*BB
) {
350 Instruction
*Start
= BB
->getFirstNonPHI();
351 // Is this a load of the exception temporary?
352 if (ExceptionValueVar
)
353 if (LoadInst
* LI
= dyn_cast
<LoadInst
>(Start
))
354 if (LI
->getPointerOperand() == ExceptionValueVar
)
355 // Reuse the existing load.
358 // Create the temporary if we didn't already.
359 if (!ExceptionValueVar
) {
360 ExceptionValueVar
= new AllocaInst(PointerType::getUnqual(
361 Type::getInt8Ty(BB
->getContext())), "eh.value", F
->begin()->begin());
362 ++NumStackTempsIntroduced
;
366 return new LoadInst(ExceptionValueVar
, "eh.value.load", Start
);
369 bool DwarfEHPrepare::runOnFunction(Function
&Fn
) {
370 bool Changed
= false;
372 // Initialize internal state.
373 DT
= getAnalysisIfAvailable
<DominatorTree
>();
374 DF
= getAnalysisIfAvailable
<DominanceFrontier
>();
375 ExceptionValueVar
= 0;
378 // Ensure that only unwind edges end at landing pads (a landing pad is a
379 // basic block where an invoke unwind edge ends).
380 Changed
|= NormalizeLandingPads();
382 // Turn unwind instructions into libcalls.
383 Changed
|= LowerUnwinds();
385 // TODO: Move eh.selector calls to landing pads and combine them.
387 // Move eh.exception calls to landing pads.
388 Changed
|= MoveExceptionValueCalls();
390 // Initialize any stack temporaries we introduced.
391 Changed
|= FinishStackTemporaries();
393 // Turn any stack temporaries into registers if possible.
395 Changed
|= PromoteStackTemporaries();