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/Function.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/IntrinsicInst.h"
19 #include "llvm/Module.h"
20 #include "llvm/Pass.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/Support/CallSite.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Transforms/Utils/SSAUpdater.h"
31 STATISTIC(NumLandingPadsSplit, "Number of landing pads split");
32 STATISTIC(NumUnwindsLowered, "Number of unwind instructions lowered");
33 STATISTIC(NumResumesLowered, "Number of eh.resume calls lowered");
34 STATISTIC(NumExceptionValuesMoved, "Number of eh.exception calls moved");
37 class DwarfEHPrepare : public FunctionPass {
38 const TargetMachine *TM;
39 const TargetLowering *TLI;
41 // The eh.exception intrinsic.
42 Function *ExceptionValueIntrinsic;
44 // The eh.selector intrinsic.
45 Function *SelectorIntrinsic;
47 // _Unwind_Resume_or_Rethrow or _Unwind_SjLj_Resume call.
50 // The EH language-specific catch-all type.
51 GlobalVariable *EHCatchAllValue;
53 // _Unwind_Resume or the target equivalent.
54 Constant *RewindFunction;
56 // We both use and preserve dominator info.
59 // The function we are running on.
62 // The landing pads for this function.
63 typedef SmallPtrSet<BasicBlock*, 8> BBSet;
66 bool InsertUnwindResumeCalls();
68 bool NormalizeLandingPads();
69 bool LowerUnwindsAndResumes();
70 bool MoveExceptionValueCalls();
72 Instruction *CreateExceptionValueCall(BasicBlock *BB);
74 /// CleanupSelectors - Any remaining eh.selector intrinsic calls which still
75 /// use the "llvm.eh.catch.all.value" call need to convert to using its
76 /// initializer instead.
77 bool CleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels);
79 bool HasCatchAllInSelector(IntrinsicInst *);
81 /// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
82 void FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels,
83 SmallPtrSet<IntrinsicInst*, 32> &CatchAllSels);
85 /// FindAllURoRInvokes - Find all URoR invokes in the function.
86 void FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes);
88 /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow" or
89 /// "_Unwind_SjLj_Resume" calls. The "unwind" part of these invokes jump to
90 /// a landing pad within the current function. This is a candidate to merge
91 /// the selector associated with the URoR invoke with the one from the
92 /// URoR's landing pad.
93 bool HandleURoRInvokes();
95 /// FindSelectorAndURoR - Find the eh.selector call and URoR call associated
96 /// with the eh.exception call. This recursively looks past instructions
97 /// which don't change the EH pointer value, like casts or PHI nodes.
98 bool FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
99 SmallPtrSet<IntrinsicInst*, 8> &SelCalls,
100 SmallPtrSet<PHINode*, 32> &SeenPHIs);
103 static char ID; // Pass identification, replacement for typeid.
104 DwarfEHPrepare(const TargetMachine *tm) :
105 FunctionPass(ID), TM(tm), TLI(TM->getTargetLowering()),
106 ExceptionValueIntrinsic(0), SelectorIntrinsic(0),
107 URoR(0), EHCatchAllValue(0), RewindFunction(0) {
108 initializeDominatorTreePass(*PassRegistry::getPassRegistry());
111 virtual bool runOnFunction(Function &Fn);
113 // getAnalysisUsage - We need the dominator tree for handling URoR.
114 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
115 AU.addRequired<DominatorTree>();
116 AU.addPreserved<DominatorTree>();
119 const char *getPassName() const {
120 return "Exception handling preparation";
124 } // end anonymous namespace
126 char DwarfEHPrepare::ID = 0;
128 FunctionPass *llvm::createDwarfEHPass(const TargetMachine *tm) {
129 return new DwarfEHPrepare(tm);
132 /// HasCatchAllInSelector - Return true if the intrinsic instruction has a
134 bool DwarfEHPrepare::HasCatchAllInSelector(IntrinsicInst *II) {
135 if (!EHCatchAllValue) return false;
137 unsigned ArgIdx = II->getNumArgOperands() - 1;
138 GlobalVariable *GV = dyn_cast<GlobalVariable>(II->getArgOperand(ArgIdx));
139 return GV == EHCatchAllValue;
142 /// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
143 void DwarfEHPrepare::
144 FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels,
145 SmallPtrSet<IntrinsicInst*, 32> &CatchAllSels) {
146 for (Value::use_iterator
147 I = SelectorIntrinsic->use_begin(),
148 E = SelectorIntrinsic->use_end(); I != E; ++I) {
149 IntrinsicInst *II = cast<IntrinsicInst>(*I);
151 if (II->getParent()->getParent() != F)
154 if (!HasCatchAllInSelector(II))
157 CatchAllSels.insert(II);
161 /// FindAllURoRInvokes - Find all URoR invokes in the function.
162 void DwarfEHPrepare::
163 FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes) {
164 for (Value::use_iterator
165 I = URoR->use_begin(),
166 E = URoR->use_end(); I != E; ++I) {
167 if (InvokeInst *II = dyn_cast<InvokeInst>(*I))
168 URoRInvokes.insert(II);
172 /// CleanupSelectors - Any remaining eh.selector intrinsic calls which still use
173 /// the "llvm.eh.catch.all.value" call need to convert to using its
174 /// initializer instead.
175 bool DwarfEHPrepare::CleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels) {
176 if (!EHCatchAllValue) return false;
178 if (!SelectorIntrinsic) {
180 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
181 if (!SelectorIntrinsic) return false;
184 bool Changed = false;
185 for (SmallPtrSet<IntrinsicInst*, 32>::iterator
186 I = Sels.begin(), E = Sels.end(); I != E; ++I) {
187 IntrinsicInst *Sel = *I;
189 // Index of the "llvm.eh.catch.all.value" variable.
190 unsigned OpIdx = Sel->getNumArgOperands() - 1;
191 GlobalVariable *GV = dyn_cast<GlobalVariable>(Sel->getArgOperand(OpIdx));
192 if (GV != EHCatchAllValue) continue;
193 Sel->setArgOperand(OpIdx, EHCatchAllValue->getInitializer());
200 /// FindSelectorAndURoR - Find the eh.selector call associated with the
201 /// eh.exception call. And indicate if there is a URoR "invoke" associated with
202 /// the eh.exception call. This recursively looks past instructions which don't
203 /// change the EH pointer value, like casts or PHI nodes.
205 DwarfEHPrepare::FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
206 SmallPtrSet<IntrinsicInst*, 8> &SelCalls,
207 SmallPtrSet<PHINode*, 32> &SeenPHIs) {
208 bool Changed = false;
210 for (Value::use_iterator
211 I = Inst->use_begin(), E = Inst->use_end(); I != E; ++I) {
212 Instruction *II = dyn_cast<Instruction>(*I);
213 if (!II || II->getParent()->getParent() != F) continue;
215 if (IntrinsicInst *Sel = dyn_cast<IntrinsicInst>(II)) {
216 if (Sel->getIntrinsicID() == Intrinsic::eh_selector)
217 SelCalls.insert(Sel);
218 } else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(II)) {
219 if (Invoke->getCalledFunction() == URoR)
221 } else if (CastInst *CI = dyn_cast<CastInst>(II)) {
222 Changed |= FindSelectorAndURoR(CI, URoRInvoke, SelCalls, SeenPHIs);
223 } else if (PHINode *PN = dyn_cast<PHINode>(II)) {
224 if (SeenPHIs.insert(PN))
225 // Don't process a PHI node more than once.
226 Changed |= FindSelectorAndURoR(PN, URoRInvoke, SelCalls, SeenPHIs);
233 /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow" or
234 /// "_Unwind_SjLj_Resume" calls. The "unwind" part of these invokes jump to a
235 /// landing pad within the current function. This is a candidate to merge the
236 /// selector associated with the URoR invoke with the one from the URoR's
238 bool DwarfEHPrepare::HandleURoRInvokes() {
239 if (!EHCatchAllValue) {
241 F->getParent()->getNamedGlobal("llvm.eh.catch.all.value");
242 if (!EHCatchAllValue) return false;
245 if (!SelectorIntrinsic) {
247 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
248 if (!SelectorIntrinsic) return false;
251 SmallPtrSet<IntrinsicInst*, 32> Sels;
252 SmallPtrSet<IntrinsicInst*, 32> CatchAllSels;
253 FindAllCleanupSelectors(Sels, CatchAllSels);
256 URoR = F->getParent()->getFunction("_Unwind_Resume_or_Rethrow");
257 if (!URoR) return CleanupSelectors(CatchAllSels);
260 SmallPtrSet<InvokeInst*, 32> URoRInvokes;
261 FindAllURoRInvokes(URoRInvokes);
263 SmallPtrSet<IntrinsicInst*, 32> SelsToConvert;
265 for (SmallPtrSet<IntrinsicInst*, 32>::iterator
266 SI = Sels.begin(), SE = Sels.end(); SI != SE; ++SI) {
267 const BasicBlock *SelBB = (*SI)->getParent();
268 for (SmallPtrSet<InvokeInst*, 32>::iterator
269 UI = URoRInvokes.begin(), UE = URoRInvokes.end(); UI != UE; ++UI) {
270 const BasicBlock *URoRBB = (*UI)->getParent();
271 if (DT->dominates(SelBB, URoRBB)) {
272 SelsToConvert.insert(*SI);
278 bool Changed = false;
280 if (Sels.size() != SelsToConvert.size()) {
281 // If we haven't been able to convert all of the clean-up selectors, then
282 // loop through the slow way to see if they still need to be converted.
283 if (!ExceptionValueIntrinsic) {
284 ExceptionValueIntrinsic =
285 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_exception);
286 if (!ExceptionValueIntrinsic)
287 return CleanupSelectors(CatchAllSels);
290 for (Value::use_iterator
291 I = ExceptionValueIntrinsic->use_begin(),
292 E = ExceptionValueIntrinsic->use_end(); I != E; ++I) {
293 IntrinsicInst *EHPtr = dyn_cast<IntrinsicInst>(*I);
294 if (!EHPtr || EHPtr->getParent()->getParent() != F) continue;
296 bool URoRInvoke = false;
297 SmallPtrSet<IntrinsicInst*, 8> SelCalls;
298 SmallPtrSet<PHINode*, 32> SeenPHIs;
299 Changed |= FindSelectorAndURoR(EHPtr, URoRInvoke, SelCalls, SeenPHIs);
302 // This EH pointer is being used by an invoke of an URoR instruction and
303 // an eh.selector intrinsic call. If the eh.selector is a 'clean-up', we
304 // need to convert it to a 'catch-all'.
305 for (SmallPtrSet<IntrinsicInst*, 8>::iterator
306 SI = SelCalls.begin(), SE = SelCalls.end(); SI != SE; ++SI)
307 if (!HasCatchAllInSelector(*SI))
308 SelsToConvert.insert(*SI);
313 if (!SelsToConvert.empty()) {
314 // Convert all clean-up eh.selectors, which are associated with "invokes" of
315 // URoR calls, into catch-all eh.selectors.
318 for (SmallPtrSet<IntrinsicInst*, 8>::iterator
319 SI = SelsToConvert.begin(), SE = SelsToConvert.end();
321 IntrinsicInst *II = *SI;
323 // Use the exception object pointer and the personality function
324 // from the original selector.
326 IntrinsicInst::op_iterator I = CS.arg_begin();
327 IntrinsicInst::op_iterator E = CS.arg_end();
328 IntrinsicInst::op_iterator B = prior(E);
330 // Exclude last argument if it is an integer.
331 if (isa<ConstantInt>(B)) E = B;
333 // Add exception object pointer (front).
334 // Add personality function (next).
335 // Add in any filter IDs (rest).
336 SmallVector<Value*, 8> Args(I, E);
338 Args.push_back(EHCatchAllValue->getInitializer()); // Catch-all indicator.
340 CallInst *NewSelector =
341 CallInst::Create(SelectorIntrinsic, Args, "eh.sel.catch.all", II);
343 NewSelector->setTailCall(II->isTailCall());
344 NewSelector->setAttributes(II->getAttributes());
345 NewSelector->setCallingConv(II->getCallingConv());
347 II->replaceAllUsesWith(NewSelector);
348 II->eraseFromParent();
352 Changed |= CleanupSelectors(CatchAllSels);
356 /// NormalizeLandingPads - Normalize and discover landing pads, noting them
357 /// in the LandingPads set. A landing pad is normal if the only CFG edges
358 /// that end at it are unwind edges from invoke instructions. If we inlined
359 /// through an invoke we could have a normal branch from the previous
360 /// unwind block through to the landing pad for the original invoke.
361 /// Abnormal landing pads are fixed up by redirecting all unwind edges to
362 /// a new basic block which falls through to the original.
363 bool DwarfEHPrepare::NormalizeLandingPads() {
364 bool Changed = false;
366 const MCAsmInfo *MAI = TM->getMCAsmInfo();
367 bool usingSjLjEH = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
369 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
370 TerminatorInst *TI = I->getTerminator();
371 if (!isa<InvokeInst>(TI))
373 BasicBlock *LPad = TI->getSuccessor(1);
374 // Skip landing pads that have already been normalized.
375 if (LandingPads.count(LPad))
378 // Check that only invoke unwind edges end at the landing pad.
379 bool OnlyUnwoundTo = true;
380 bool SwitchOK = usingSjLjEH;
381 for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad);
383 TerminatorInst *PT = (*PI)->getTerminator();
384 // The SjLj dispatch block uses a switch instruction. This is effectively
385 // an unwind edge, so we can disregard it here. There will only ever
386 // be one dispatch, however, so if there are multiple switches, one
387 // of them truly is a normal edge, not an unwind edge.
388 if (SwitchOK && isa<SwitchInst>(PT)) {
392 if (!isa<InvokeInst>(PT) || LPad == PT->getSuccessor(0)) {
393 OnlyUnwoundTo = false;
399 // Only unwind edges lead to the landing pad. Remember the landing pad.
400 LandingPads.insert(LPad);
404 // At least one normal edge ends at the landing pad. Redirect the unwind
405 // edges to a new basic block which falls through into this one.
407 // Create the new basic block.
408 BasicBlock *NewBB = BasicBlock::Create(F->getContext(),
409 LPad->getName() + "_unwind_edge");
411 // Insert it into the function right before the original landing pad.
412 LPad->getParent()->getBasicBlockList().insert(LPad, NewBB);
414 // Redirect unwind edges from the original landing pad to NewBB.
415 for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad); PI != PE; ) {
416 TerminatorInst *PT = (*PI++)->getTerminator();
417 if (isa<InvokeInst>(PT) && PT->getSuccessor(1) == LPad)
418 // Unwind to the new block.
419 PT->setSuccessor(1, NewBB);
422 // If there are any PHI nodes in LPad, we need to update them so that they
423 // merge incoming values from NewBB instead.
424 for (BasicBlock::iterator II = LPad->begin(); isa<PHINode>(II); ++II) {
425 PHINode *PN = cast<PHINode>(II);
426 pred_iterator PB = pred_begin(NewBB), PE = pred_end(NewBB);
428 // Check to see if all of the values coming in via unwind edges are the
429 // same. If so, we don't need to create a new PHI node.
430 Value *InVal = PN->getIncomingValueForBlock(*PB);
431 for (pred_iterator PI = PB; PI != PE; ++PI) {
432 if (PI != PB && InVal != PN->getIncomingValueForBlock(*PI)) {
439 // Different unwind edges have different values. Create a new PHI node
441 PHINode *NewPN = PHINode::Create(PN->getType(),
442 PN->getNumIncomingValues(),
443 PN->getName()+".unwind", NewBB);
444 // Add an entry for each unwind edge, using the value from the old PHI.
445 for (pred_iterator PI = PB; PI != PE; ++PI)
446 NewPN->addIncoming(PN->getIncomingValueForBlock(*PI), *PI);
448 // Now use this new PHI as the common incoming value for NewBB in PN.
452 // Revector exactly one entry in the PHI node to come from NewBB
453 // and delete all other entries that come from unwind edges. If
454 // there are both normal and unwind edges from the same predecessor,
455 // this leaves an entry for the normal edge.
456 for (pred_iterator PI = PB; PI != PE; ++PI)
457 PN->removeIncomingValue(*PI);
458 PN->addIncoming(InVal, NewBB);
461 // Add a fallthrough from NewBB to the original landing pad.
462 BranchInst::Create(LPad, NewBB);
464 // Now update DominatorTree analysis information.
465 DT->splitBlock(NewBB);
467 // Remember the newly constructed landing pad. The original landing pad
468 // LPad is no longer a landing pad now that all unwind edges have been
469 // revectored to NewBB.
470 LandingPads.insert(NewBB);
471 ++NumLandingPadsSplit;
478 /// LowerUnwinds - Turn unwind instructions into calls to _Unwind_Resume,
479 /// rethrowing any previously caught exception. This will crash horribly
480 /// at runtime if there is no such exception: using unwind to throw a new
481 /// exception is currently not supported.
482 bool DwarfEHPrepare::LowerUnwindsAndResumes() {
483 SmallVector<Instruction*, 16> ResumeInsts;
485 for (Function::iterator fi = F->begin(), fe = F->end(); fi != fe; ++fi) {
486 for (BasicBlock::iterator bi = fi->begin(), be = fi->end(); bi != be; ++bi){
487 if (isa<UnwindInst>(bi))
488 ResumeInsts.push_back(bi);
489 else if (CallInst *call = dyn_cast<CallInst>(bi))
490 if (Function *fn = dyn_cast<Function>(call->getCalledValue()))
491 if (fn->getName() == "llvm.eh.resume")
492 ResumeInsts.push_back(bi);
496 if (ResumeInsts.empty()) return false;
498 // Find the rewind function if we didn't already.
499 if (!RewindFunction) {
500 LLVMContext &Ctx = ResumeInsts[0]->getContext();
501 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
502 Type::getInt8PtrTy(Ctx), false);
503 const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
504 RewindFunction = F->getParent()->getOrInsertFunction(RewindName, FTy);
507 bool Changed = false;
509 for (SmallVectorImpl<Instruction*>::iterator
510 I = ResumeInsts.begin(), E = ResumeInsts.end(); I != E; ++I) {
511 Instruction *RI = *I;
513 // Replace the resuming instruction with a call to _Unwind_Resume (or the
514 // appropriate target equivalent).
516 llvm::Value *ExnValue;
517 if (isa<UnwindInst>(RI))
518 ExnValue = CreateExceptionValueCall(RI->getParent());
520 ExnValue = cast<CallInst>(RI)->getArgOperand(0);
522 // Create the call...
523 CallInst *CI = CallInst::Create(RewindFunction, ExnValue, "", RI);
524 CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
526 // ...followed by an UnreachableInst, if it was an unwind.
527 // Calls to llvm.eh.resume are typically already followed by this.
528 if (isa<UnwindInst>(RI))
529 new UnreachableInst(RI->getContext(), RI);
531 if (isa<UnwindInst>(RI))
536 // Nuke the resume instruction.
537 RI->eraseFromParent();
545 /// MoveExceptionValueCalls - Ensure that eh.exception is only ever called from
546 /// landing pads by replacing calls outside of landing pads with direct use of
547 /// a register holding the appropriate value; this requires adding calls inside
548 /// all landing pads to initialize the register. Also, move eh.exception calls
549 /// inside landing pads to the start of the landing pad (optional, but may make
550 /// things simpler for later passes).
551 bool DwarfEHPrepare::MoveExceptionValueCalls() {
552 // If the eh.exception intrinsic is not declared in the module then there is
553 // nothing to do. Speed up compilation by checking for this common case.
554 if (!ExceptionValueIntrinsic &&
555 !F->getParent()->getFunction(Intrinsic::getName(Intrinsic::eh_exception)))
558 bool Changed = false;
560 // Move calls to eh.exception that are inside a landing pad to the start of
562 for (BBSet::const_iterator LI = LandingPads.begin(), LE = LandingPads.end();
564 BasicBlock *LP = *LI;
565 for (BasicBlock::iterator II = LP->getFirstNonPHIOrDbg(), IE = LP->end();
567 if (EHExceptionInst *EI = dyn_cast<EHExceptionInst>(II++)) {
568 // Found a call to eh.exception.
569 if (!EI->use_empty()) {
570 // If there is already a call to eh.exception at the start of the
571 // landing pad, then get hold of it; otherwise create such a call.
572 Value *CallAtStart = CreateExceptionValueCall(LP);
574 // If the call was at the start of a landing pad then leave it alone.
575 if (EI == CallAtStart)
577 EI->replaceAllUsesWith(CallAtStart);
579 EI->eraseFromParent();
580 ++NumExceptionValuesMoved;
585 // Look for calls to eh.exception that are not in a landing pad. If one is
586 // found, then a register that holds the exception value will be created in
587 // each landing pad, and the SSAUpdater will be used to compute the values
588 // returned by eh.exception calls outside of landing pads.
591 // Remember where we found the eh.exception call, to avoid rescanning earlier
592 // basic blocks which we already know contain no eh.exception calls.
593 bool FoundCallOutsideLandingPad = false;
594 Function::iterator BB = F->begin();
595 for (Function::iterator BE = F->end(); BB != BE; ++BB) {
596 // Skip over landing pads.
597 if (LandingPads.count(BB))
600 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
602 if (isa<EHExceptionInst>(II)) {
603 SSA.Initialize(II->getType(), II->getName());
604 FoundCallOutsideLandingPad = true;
608 if (FoundCallOutsideLandingPad)
612 // If all calls to eh.exception are in landing pads then we are done.
613 if (!FoundCallOutsideLandingPad)
616 // Add a call to eh.exception at the start of each landing pad, and tell the
617 // SSAUpdater that this is the value produced by the landing pad.
618 for (BBSet::iterator LI = LandingPads.begin(), LE = LandingPads.end();
620 SSA.AddAvailableValue(*LI, CreateExceptionValueCall(*LI));
622 // Now turn all calls to eh.exception that are not in a landing pad into a use
623 // of the appropriate register.
624 for (Function::iterator BE = F->end(); BB != BE; ++BB) {
625 // Skip over landing pads.
626 if (LandingPads.count(BB))
629 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
631 if (EHExceptionInst *EI = dyn_cast<EHExceptionInst>(II++)) {
632 // Found a call to eh.exception, replace it with the value from any
633 // upstream landing pad(s).
634 EI->replaceAllUsesWith(SSA.GetValueAtEndOfBlock(BB));
635 EI->eraseFromParent();
636 ++NumExceptionValuesMoved;
643 /// CreateExceptionValueCall - Insert a call to the eh.exception intrinsic at
644 /// the start of the basic block (unless there already is one, in which case
645 /// the existing call is returned).
646 Instruction *DwarfEHPrepare::CreateExceptionValueCall(BasicBlock *BB) {
647 Instruction *Start = BB->getFirstNonPHIOrDbg();
648 // Is this a call to eh.exception?
649 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Start))
650 if (CI->getIntrinsicID() == Intrinsic::eh_exception)
651 // Reuse the existing call.
654 // Find the eh.exception intrinsic if we didn't already.
655 if (!ExceptionValueIntrinsic)
656 ExceptionValueIntrinsic = Intrinsic::getDeclaration(F->getParent(),
657 Intrinsic::eh_exception);
660 return CallInst::Create(ExceptionValueIntrinsic, "eh.value.call", Start);
663 /// InsertUnwindResumeCalls - Convert the ResumeInsts that are still present
664 /// into calls to the appropriate _Unwind_Resume function.
665 bool DwarfEHPrepare::InsertUnwindResumeCalls() {
666 SmallVector<ResumeInst*, 16> Resumes;
667 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
668 for (BasicBlock::iterator II = I->begin(), IE = I->end(); II != IE; ++II)
669 if (ResumeInst *RI = dyn_cast<ResumeInst>(II))
670 Resumes.push_back(RI);
675 // Find the rewind function if we didn't already.
676 if (!RewindFunction) {
677 LLVMContext &Ctx = Resumes[0]->getContext();
678 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
679 Type::getInt8PtrTy(Ctx), false);
680 const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
681 RewindFunction = F->getParent()->getOrInsertFunction(RewindName, FTy);
684 // Create the basic block where the _Unwind_Resume call will live.
685 LLVMContext &Ctx = F->getContext();
686 BasicBlock *UnwindBB = BasicBlock::Create(Ctx, "unwind_resume", F);
687 PHINode *PN = PHINode::Create(Type::getInt8PtrTy(Ctx), Resumes.size(),
688 "exn.obj", UnwindBB);
690 // Extract the exception object from the ResumeInst and add it to the PHI node
691 // that feeds the _Unwind_Resume call.
692 for (SmallVectorImpl<ResumeInst*>::iterator
693 I = Resumes.begin(), E = Resumes.end(); I != E; ++I) {
695 BranchInst::Create(UnwindBB, RI->getParent());
696 ExtractValueInst *ExnObj = ExtractValueInst::Create(RI->getOperand(0),
698 PN->addIncoming(ExnObj, RI->getParent());
699 RI->eraseFromParent();
702 // Call the function.
703 CallInst *CI = CallInst::Create(RewindFunction, PN, "", UnwindBB);
704 CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
706 // We never expect _Unwind_Resume to return.
707 new UnreachableInst(Ctx, UnwindBB);
711 bool DwarfEHPrepare::runOnFunction(Function &Fn) {
712 bool Changed = false;
714 // Initialize internal state.
715 DT = &getAnalysis<DominatorTree>(); // FIXME: We won't need this with the new EH.
718 if (InsertUnwindResumeCalls()) {
719 // FIXME: The reset of this function can go once the new EH is done.
724 // Ensure that only unwind edges end at landing pads (a landing pad is a
725 // basic block where an invoke unwind edge ends).
726 Changed |= NormalizeLandingPads();
728 // Turn unwind instructions and eh.resume calls into libcalls.
729 Changed |= LowerUnwindsAndResumes();
731 // TODO: Move eh.selector calls to landing pads and combine them.
733 // Move eh.exception calls to landing pads.
734 Changed |= MoveExceptionValueCalls();
736 Changed |= HandleURoRInvokes();