DwarfEHPrepare.cpp revision d8b4fb4aab4d6fedb2b14bed1b846451b17bde7c
1//===-- DwarfEHPrepare - Prepare exception handling for code generation ---===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass mulches exception handling code into a form adapted to code
11// generation. Required if using dwarf exception handling.
12//
13//===----------------------------------------------------------------------===//
14
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"
29using namespace llvm;
30
31STATISTIC(NumLandingPadsSplit,     "Number of landing pads split");
32STATISTIC(NumUnwindsLowered,       "Number of unwind instructions lowered");
33STATISTIC(NumExceptionValuesMoved, "Number of eh.exception calls moved");
34
35namespace {
36  class DwarfEHPrepare : public FunctionPass {
37    const TargetMachine *TM;
38    const TargetLowering *TLI;
39
40    // The eh.exception intrinsic.
41    Function *ExceptionValueIntrinsic;
42
43    // The eh.selector intrinsic.
44    Function *SelectorIntrinsic;
45
46    // _Unwind_Resume_or_Rethrow or _Unwind_SjLj_Resume call.
47    Constant *URoR;
48
49    // The EH language-specific catch-all type.
50    GlobalVariable *EHCatchAllValue;
51
52    // _Unwind_Resume or the target equivalent.
53    Constant *RewindFunction;
54
55    // We both use and preserve dominator info.
56    DominatorTree *DT;
57
58    // The function we are running on.
59    Function *F;
60
61    // The landing pads for this function.
62    typedef SmallPtrSet<BasicBlock*, 8> BBSet;
63    BBSet LandingPads;
64
65    bool NormalizeLandingPads();
66    bool LowerUnwinds();
67    bool MoveExceptionValueCalls();
68
69    Instruction *CreateExceptionValueCall(BasicBlock *BB);
70
71    /// CleanupSelectors - Any remaining eh.selector intrinsic calls which still
72    /// use the "llvm.eh.catch.all.value" call need to convert to using its
73    /// initializer instead.
74    bool CleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels);
75
76    bool HasCatchAllInSelector(IntrinsicInst *);
77
78    /// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
79    void FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels,
80                                 SmallPtrSet<IntrinsicInst*, 32> &CatchAllSels);
81
82    /// FindAllURoRInvokes - Find all URoR invokes in the function.
83    void FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes);
84
85    /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow" or
86    /// "_Unwind_SjLj_Resume" calls. The "unwind" part of these invokes jump to
87    /// a landing pad within the current function. This is a candidate to merge
88    /// the selector associated with the URoR invoke with the one from the
89    /// URoR's landing pad.
90    bool HandleURoRInvokes();
91
92    /// FindSelectorAndURoR - Find the eh.selector call and URoR call associated
93    /// with the eh.exception call. This recursively looks past instructions
94    /// which don't change the EH pointer value, like casts or PHI nodes.
95    bool FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
96                             SmallPtrSet<IntrinsicInst*, 8> &SelCalls,
97                             SmallPtrSet<PHINode*, 32> &SeenPHIs);
98
99  public:
100    static char ID; // Pass identification, replacement for typeid.
101    DwarfEHPrepare(const TargetMachine *tm) :
102      FunctionPass(ID), TM(tm), TLI(TM->getTargetLowering()),
103      ExceptionValueIntrinsic(0), SelectorIntrinsic(0),
104      URoR(0), EHCatchAllValue(0), RewindFunction(0) {
105        initializeDominatorTreePass(*PassRegistry::getPassRegistry());
106      }
107
108    virtual bool runOnFunction(Function &Fn);
109
110    // getAnalysisUsage - We need the dominator tree for handling URoR.
111    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
112      AU.addRequired<DominatorTree>();
113      AU.addPreserved<DominatorTree>();
114    }
115
116    const char *getPassName() const {
117      return "Exception handling preparation";
118    }
119
120  };
121} // end anonymous namespace
122
123char DwarfEHPrepare::ID = 0;
124
125FunctionPass *llvm::createDwarfEHPass(const TargetMachine *tm) {
126  return new DwarfEHPrepare(tm);
127}
128
129/// HasCatchAllInSelector - Return true if the intrinsic instruction has a
130/// catch-all.
131bool DwarfEHPrepare::HasCatchAllInSelector(IntrinsicInst *II) {
132  if (!EHCatchAllValue) return false;
133
134  unsigned ArgIdx = II->getNumArgOperands() - 1;
135  GlobalVariable *GV = dyn_cast<GlobalVariable>(II->getArgOperand(ArgIdx));
136  return GV == EHCatchAllValue;
137}
138
139/// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
140void DwarfEHPrepare::
141FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels,
142                        SmallPtrSet<IntrinsicInst*, 32> &CatchAllSels) {
143  for (Value::use_iterator
144         I = SelectorIntrinsic->use_begin(),
145         E = SelectorIntrinsic->use_end(); I != E; ++I) {
146    IntrinsicInst *II = cast<IntrinsicInst>(*I);
147
148    if (II->getParent()->getParent() != F)
149      continue;
150
151    if (!HasCatchAllInSelector(II))
152      Sels.insert(II);
153    else
154      CatchAllSels.insert(II);
155  }
156}
157
158/// FindAllURoRInvokes - Find all URoR invokes in the function.
159void DwarfEHPrepare::
160FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes) {
161  for (Value::use_iterator
162         I = URoR->use_begin(),
163         E = URoR->use_end(); I != E; ++I) {
164    if (InvokeInst *II = dyn_cast<InvokeInst>(*I))
165      URoRInvokes.insert(II);
166  }
167}
168
169/// CleanupSelectors - Any remaining eh.selector intrinsic calls which still use
170/// the "llvm.eh.catch.all.value" call need to convert to using its
171/// initializer instead.
172bool DwarfEHPrepare::CleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels) {
173  if (!EHCatchAllValue) return false;
174
175  if (!SelectorIntrinsic) {
176    SelectorIntrinsic =
177      Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
178    if (!SelectorIntrinsic) return false;
179  }
180
181  bool Changed = false;
182  for (SmallPtrSet<IntrinsicInst*, 32>::iterator
183         I = Sels.begin(), E = Sels.end(); I != E; ++I) {
184    IntrinsicInst *Sel = *I;
185
186    // Index of the "llvm.eh.catch.all.value" variable.
187    unsigned OpIdx = Sel->getNumArgOperands() - 1;
188    GlobalVariable *GV = dyn_cast<GlobalVariable>(Sel->getArgOperand(OpIdx));
189    if (GV != EHCatchAllValue) continue;
190    Sel->setArgOperand(OpIdx, EHCatchAllValue->getInitializer());
191    Changed = true;
192  }
193
194  return Changed;
195}
196
197/// FindSelectorAndURoR - Find the eh.selector call associated with the
198/// eh.exception call. And indicate if there is a URoR "invoke" associated with
199/// the eh.exception call. This recursively looks past instructions which don't
200/// change the EH pointer value, like casts or PHI nodes.
201bool
202DwarfEHPrepare::FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
203                                    SmallPtrSet<IntrinsicInst*, 8> &SelCalls,
204                                    SmallPtrSet<PHINode*, 32> &SeenPHIs) {
205  bool Changed = false;
206
207  for (Value::use_iterator
208         I = Inst->use_begin(), E = Inst->use_end(); I != E; ++I) {
209    Instruction *II = dyn_cast<Instruction>(*I);
210    if (!II || II->getParent()->getParent() != F) continue;
211
212    if (IntrinsicInst *Sel = dyn_cast<IntrinsicInst>(II)) {
213      if (Sel->getIntrinsicID() == Intrinsic::eh_selector)
214        SelCalls.insert(Sel);
215    } else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(II)) {
216      if (Invoke->getCalledFunction() == URoR)
217        URoRInvoke = true;
218    } else if (CastInst *CI = dyn_cast<CastInst>(II)) {
219      Changed |= FindSelectorAndURoR(CI, URoRInvoke, SelCalls, SeenPHIs);
220    } else if (PHINode *PN = dyn_cast<PHINode>(II)) {
221      if (SeenPHIs.insert(PN))
222        // Don't process a PHI node more than once.
223        Changed |= FindSelectorAndURoR(PN, URoRInvoke, SelCalls, SeenPHIs);
224    }
225  }
226
227  return Changed;
228}
229
230/// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow" or
231/// "_Unwind_SjLj_Resume" calls. The "unwind" part of these invokes jump to a
232/// landing pad within the current function. This is a candidate to merge the
233/// selector associated with the URoR invoke with the one from the URoR's
234/// landing pad.
235bool DwarfEHPrepare::HandleURoRInvokes() {
236  if (!EHCatchAllValue) {
237    EHCatchAllValue =
238      F->getParent()->getNamedGlobal("llvm.eh.catch.all.value");
239    if (!EHCatchAllValue) return false;
240  }
241
242  if (!SelectorIntrinsic) {
243    SelectorIntrinsic =
244      Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
245    if (!SelectorIntrinsic) return false;
246  }
247
248  SmallPtrSet<IntrinsicInst*, 32> Sels;
249  SmallPtrSet<IntrinsicInst*, 32> CatchAllSels;
250  FindAllCleanupSelectors(Sels, CatchAllSels);
251
252  if (!URoR) {
253    URoR = F->getParent()->getFunction("_Unwind_Resume_or_Rethrow");
254    if (!URoR) {
255      URoR = F->getParent()->getFunction("_Unwind_SjLj_Resume");
256      if (!URoR) return CleanupSelectors(CatchAllSels);
257    }
258  }
259
260  SmallPtrSet<InvokeInst*, 32> URoRInvokes;
261  FindAllURoRInvokes(URoRInvokes);
262
263  SmallPtrSet<IntrinsicInst*, 32> SelsToConvert;
264
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);
273        break;
274      }
275    }
276  }
277
278  bool Changed = false;
279
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);
288    }
289
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;
295
296      bool URoRInvoke = false;
297      SmallPtrSet<IntrinsicInst*, 8> SelCalls;
298      SmallPtrSet<PHINode*, 32> SeenPHIs;
299      Changed |= FindSelectorAndURoR(EHPtr, URoRInvoke, SelCalls, SeenPHIs);
300
301      if (URoRInvoke) {
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);
309      }
310    }
311  }
312
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.
316    Changed = true;
317
318    for (SmallPtrSet<IntrinsicInst*, 8>::iterator
319           SI = SelsToConvert.begin(), SE = SelsToConvert.end();
320         SI != SE; ++SI) {
321      IntrinsicInst *II = *SI;
322
323      // Use the exception object pointer and the personality function
324      // from the original selector.
325      CallSite CS(II);
326      IntrinsicInst::op_iterator I = CS.arg_begin();
327      IntrinsicInst::op_iterator E = CS.arg_end();
328      IntrinsicInst::op_iterator B = prior(E);
329
330      // Exclude last argument if it is an integer.
331      if (isa<ConstantInt>(B)) E = B;
332
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);
337
338      Args.push_back(EHCatchAllValue->getInitializer()); // Catch-all indicator.
339
340      CallInst *NewSelector =
341        CallInst::Create(SelectorIntrinsic, Args.begin(), Args.end(),
342                         "eh.sel.catch.all", II);
343
344      NewSelector->setTailCall(II->isTailCall());
345      NewSelector->setAttributes(II->getAttributes());
346      NewSelector->setCallingConv(II->getCallingConv());
347
348      II->replaceAllUsesWith(NewSelector);
349      II->eraseFromParent();
350    }
351  }
352
353  Changed |= CleanupSelectors(CatchAllSels);
354  return Changed;
355}
356
357/// NormalizeLandingPads - Normalize and discover landing pads, noting them
358/// in the LandingPads set.  A landing pad is normal if the only CFG edges
359/// that end at it are unwind edges from invoke instructions. If we inlined
360/// through an invoke we could have a normal branch from the previous
361/// unwind block through to the landing pad for the original invoke.
362/// Abnormal landing pads are fixed up by redirecting all unwind edges to
363/// a new basic block which falls through to the original.
364bool DwarfEHPrepare::NormalizeLandingPads() {
365  bool Changed = false;
366
367  const MCAsmInfo *MAI = TM->getMCAsmInfo();
368  bool usingSjLjEH = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
369
370  for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
371    TerminatorInst *TI = I->getTerminator();
372    if (!isa<InvokeInst>(TI))
373      continue;
374    BasicBlock *LPad = TI->getSuccessor(1);
375    // Skip landing pads that have already been normalized.
376    if (LandingPads.count(LPad))
377      continue;
378
379    // Check that only invoke unwind edges end at the landing pad.
380    bool OnlyUnwoundTo = true;
381    bool SwitchOK = usingSjLjEH;
382    for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad);
383         PI != PE; ++PI) {
384      TerminatorInst *PT = (*PI)->getTerminator();
385      // The SjLj dispatch block uses a switch instruction. This is effectively
386      // an unwind edge, so we can disregard it here. There will only ever
387      // be one dispatch, however, so if there are multiple switches, one
388      // of them truly is a normal edge, not an unwind edge.
389      if (SwitchOK && isa<SwitchInst>(PT)) {
390        SwitchOK = false;
391        continue;
392      }
393      if (!isa<InvokeInst>(PT) || LPad == PT->getSuccessor(0)) {
394        OnlyUnwoundTo = false;
395        break;
396      }
397    }
398
399    if (OnlyUnwoundTo) {
400      // Only unwind edges lead to the landing pad.  Remember the landing pad.
401      LandingPads.insert(LPad);
402      continue;
403    }
404
405    // At least one normal edge ends at the landing pad.  Redirect the unwind
406    // edges to a new basic block which falls through into this one.
407
408    // Create the new basic block.
409    BasicBlock *NewBB = BasicBlock::Create(F->getContext(),
410                                           LPad->getName() + "_unwind_edge");
411
412    // Insert it into the function right before the original landing pad.
413    LPad->getParent()->getBasicBlockList().insert(LPad, NewBB);
414
415    // Redirect unwind edges from the original landing pad to NewBB.
416    for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad); PI != PE; ) {
417      TerminatorInst *PT = (*PI++)->getTerminator();
418      if (isa<InvokeInst>(PT) && PT->getSuccessor(1) == LPad)
419        // Unwind to the new block.
420        PT->setSuccessor(1, NewBB);
421    }
422
423    // If there are any PHI nodes in LPad, we need to update them so that they
424    // merge incoming values from NewBB instead.
425    for (BasicBlock::iterator II = LPad->begin(); isa<PHINode>(II); ++II) {
426      PHINode *PN = cast<PHINode>(II);
427      pred_iterator PB = pred_begin(NewBB), PE = pred_end(NewBB);
428
429      // Check to see if all of the values coming in via unwind edges are the
430      // same.  If so, we don't need to create a new PHI node.
431      Value *InVal = PN->getIncomingValueForBlock(*PB);
432      for (pred_iterator PI = PB; PI != PE; ++PI) {
433        if (PI != PB && InVal != PN->getIncomingValueForBlock(*PI)) {
434          InVal = 0;
435          break;
436        }
437      }
438
439      if (InVal == 0) {
440        // Different unwind edges have different values.  Create a new PHI node
441        // in NewBB.
442        PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".unwind",
443                                         NewBB);
444        NewPN->reserveOperandSpace(PN->getNumIncomingValues());
445        // Add an entry for each unwind edge, using the value from the old PHI.
446        for (pred_iterator PI = PB; PI != PE; ++PI)
447          NewPN->addIncoming(PN->getIncomingValueForBlock(*PI), *PI);
448
449        // Now use this new PHI as the common incoming value for NewBB in PN.
450        InVal = NewPN;
451      }
452
453      // Revector exactly one entry in the PHI node to come from NewBB
454      // and delete all other entries that come from unwind edges.  If
455      // there are both normal and unwind edges from the same predecessor,
456      // this leaves an entry for the normal edge.
457      for (pred_iterator PI = PB; PI != PE; ++PI)
458        PN->removeIncomingValue(*PI);
459      PN->addIncoming(InVal, NewBB);
460    }
461
462    // Add a fallthrough from NewBB to the original landing pad.
463    BranchInst::Create(LPad, NewBB);
464
465    // Now update DominatorTree analysis information.
466    DT->splitBlock(NewBB);
467
468    // Remember the newly constructed landing pad.  The original landing pad
469    // LPad is no longer a landing pad now that all unwind edges have been
470    // revectored to NewBB.
471    LandingPads.insert(NewBB);
472    ++NumLandingPadsSplit;
473    Changed = true;
474  }
475
476  return Changed;
477}
478
479/// LowerUnwinds - Turn unwind instructions into calls to _Unwind_Resume,
480/// rethrowing any previously caught exception.  This will crash horribly
481/// at runtime if there is no such exception: using unwind to throw a new
482/// exception is currently not supported.
483bool DwarfEHPrepare::LowerUnwinds() {
484  SmallVector<TerminatorInst*, 16> UnwindInsts;
485
486  for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
487    TerminatorInst *TI = I->getTerminator();
488    if (isa<UnwindInst>(TI))
489      UnwindInsts.push_back(TI);
490  }
491
492  if (UnwindInsts.empty()) return false;
493
494  // Find the rewind function if we didn't already.
495  if (!RewindFunction) {
496    LLVMContext &Ctx = UnwindInsts[0]->getContext();
497    std::vector<const Type*>
498      Params(1, Type::getInt8PtrTy(Ctx));
499    FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
500                                          Params, false);
501    const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
502    RewindFunction = F->getParent()->getOrInsertFunction(RewindName, FTy);
503  }
504
505  bool Changed = false;
506
507  for (SmallVectorImpl<TerminatorInst*>::iterator
508         I = UnwindInsts.begin(), E = UnwindInsts.end(); I != E; ++I) {
509    TerminatorInst *TI = *I;
510
511    // Replace the unwind instruction with a call to _Unwind_Resume (or the
512    // appropriate target equivalent) followed by an UnreachableInst.
513
514    // Create the call...
515    CallInst *CI = CallInst::Create(RewindFunction,
516                                    CreateExceptionValueCall(TI->getParent()),
517                                    "", TI);
518    CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
519    // ...followed by an UnreachableInst.
520    new UnreachableInst(TI->getContext(), TI);
521
522    // Nuke the unwind instruction.
523    TI->eraseFromParent();
524    ++NumUnwindsLowered;
525    Changed = true;
526  }
527
528  return Changed;
529}
530
531/// MoveExceptionValueCalls - Ensure that eh.exception is only ever called from
532/// landing pads by replacing calls outside of landing pads with direct use of
533/// a register holding the appropriate value; this requires adding calls inside
534/// all landing pads to initialize the register.  Also, move eh.exception calls
535/// inside landing pads to the start of the landing pad (optional, but may make
536/// things simpler for later passes).
537bool DwarfEHPrepare::MoveExceptionValueCalls() {
538  // If the eh.exception intrinsic is not declared in the module then there is
539  // nothing to do.  Speed up compilation by checking for this common case.
540  if (!ExceptionValueIntrinsic &&
541      !F->getParent()->getFunction(Intrinsic::getName(Intrinsic::eh_exception)))
542    return false;
543
544  bool Changed = false;
545
546  // Move calls to eh.exception that are inside a landing pad to the start of
547  // the landing pad.
548  for (BBSet::const_iterator LI = LandingPads.begin(), LE = LandingPads.end();
549       LI != LE; ++LI) {
550    BasicBlock *LP = *LI;
551    for (BasicBlock::iterator II = LP->getFirstNonPHIOrDbg(), IE = LP->end();
552         II != IE;)
553      if (EHExceptionInst *EI = dyn_cast<EHExceptionInst>(II++)) {
554        // Found a call to eh.exception.
555        if (!EI->use_empty()) {
556          // If there is already a call to eh.exception at the start of the
557          // landing pad, then get hold of it; otherwise create such a call.
558          Value *CallAtStart = CreateExceptionValueCall(LP);
559
560          // If the call was at the start of a landing pad then leave it alone.
561          if (EI == CallAtStart)
562            continue;
563          EI->replaceAllUsesWith(CallAtStart);
564        }
565        EI->eraseFromParent();
566        ++NumExceptionValuesMoved;
567        Changed = true;
568      }
569  }
570
571  // Look for calls to eh.exception that are not in a landing pad.  If one is
572  // found, then a register that holds the exception value will be created in
573  // each landing pad, and the SSAUpdater will be used to compute the values
574  // returned by eh.exception calls outside of landing pads.
575  SSAUpdater SSA;
576
577  // Remember where we found the eh.exception call, to avoid rescanning earlier
578  // basic blocks which we already know contain no eh.exception calls.
579  bool FoundCallOutsideLandingPad = false;
580  Function::iterator BB = F->begin();
581  for (Function::iterator BE = F->end(); BB != BE; ++BB) {
582    // Skip over landing pads.
583    if (LandingPads.count(BB))
584      continue;
585
586    for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
587         II != IE; ++II)
588      if (isa<EHExceptionInst>(II)) {
589        SSA.Initialize(II->getType(), II->getName());
590        FoundCallOutsideLandingPad = true;
591        break;
592      }
593
594    if (FoundCallOutsideLandingPad)
595      break;
596  }
597
598  // If all calls to eh.exception are in landing pads then we are done.
599  if (!FoundCallOutsideLandingPad)
600    return Changed;
601
602  // Add a call to eh.exception at the start of each landing pad, and tell the
603  // SSAUpdater that this is the value produced by the landing pad.
604  for (BBSet::iterator LI = LandingPads.begin(), LE = LandingPads.end();
605       LI != LE; ++LI)
606    SSA.AddAvailableValue(*LI, CreateExceptionValueCall(*LI));
607
608  // Now turn all calls to eh.exception that are not in a landing pad into a use
609  // of the appropriate register.
610  for (Function::iterator BE = F->end(); BB != BE; ++BB) {
611    // Skip over landing pads.
612    if (LandingPads.count(BB))
613      continue;
614
615    for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
616         II != IE;)
617      if (EHExceptionInst *EI = dyn_cast<EHExceptionInst>(II++)) {
618        // Found a call to eh.exception, replace it with the value from any
619        // upstream landing pad(s).
620        EI->replaceAllUsesWith(SSA.GetValueAtEndOfBlock(BB));
621        EI->eraseFromParent();
622        ++NumExceptionValuesMoved;
623      }
624  }
625
626  return true;
627}
628
629/// CreateExceptionValueCall - Insert a call to the eh.exception intrinsic at
630/// the start of the basic block (unless there already is one, in which case
631/// the existing call is returned).
632Instruction *DwarfEHPrepare::CreateExceptionValueCall(BasicBlock *BB) {
633  Instruction *Start = BB->getFirstNonPHIOrDbg();
634  // Is this a call to eh.exception?
635  if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Start))
636    if (CI->getIntrinsicID() == Intrinsic::eh_exception)
637      // Reuse the existing call.
638      return Start;
639
640  // Find the eh.exception intrinsic if we didn't already.
641  if (!ExceptionValueIntrinsic)
642    ExceptionValueIntrinsic = Intrinsic::getDeclaration(F->getParent(),
643                                                       Intrinsic::eh_exception);
644
645  // Create the call.
646  return CallInst::Create(ExceptionValueIntrinsic, "eh.value.call", Start);
647}
648
649bool DwarfEHPrepare::runOnFunction(Function &Fn) {
650  bool Changed = false;
651
652  // Initialize internal state.
653  DT = &getAnalysis<DominatorTree>();
654  F = &Fn;
655
656  // Ensure that only unwind edges end at landing pads (a landing pad is a
657  // basic block where an invoke unwind edge ends).
658  Changed |= NormalizeLandingPads();
659
660  // Turn unwind instructions into libcalls.
661  Changed |= LowerUnwinds();
662
663  // TODO: Move eh.selector calls to landing pads and combine them.
664
665  // Move eh.exception calls to landing pads.
666  Changed |= MoveExceptionValueCalls();
667
668  Changed |= HandleURoRInvokes();
669
670  LandingPads.clear();
671
672  return Changed;
673}
674