When performing the Horrible Hack(tm-Duncan) on the EH code to convert a
[oota-llvm.git] / lib / CodeGen / DwarfEHPrepare.cpp
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/Target/TargetLowering.h"
26 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
27 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
28 using namespace llvm;
29
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");
34
35 namespace {
36   class DwarfEHPrepare : public FunctionPass {
37     const TargetMachine *TM;
38     const TargetLowering *TLI;
39     bool CompileFast;
40
41     // The eh.exception intrinsic.
42     Function *ExceptionValueIntrinsic;
43
44     // The eh.selector intrinsic.
45     Function *SelectorIntrinsic;
46
47     // _Unwind_Resume_or_Rethrow call.
48     Constant *URoR;
49
50     // The EH language-specific catch-all type.
51     GlobalVariable *EHCatchAllValue;
52
53     // _Unwind_Resume or the target equivalent.
54     Constant *RewindFunction;
55
56     // Dominator info is used when turning stack temporaries into registers.
57     DominatorTree *DT;
58     DominanceFrontier *DF;
59
60     // The function we are running on.
61     Function *F;
62
63     // The landing pads for this function.
64     typedef SmallPtrSet<BasicBlock*, 8> BBSet;
65     BBSet LandingPads;
66
67     // Stack temporary used to hold eh.exception values.
68     AllocaInst *ExceptionValueVar;
69
70     bool NormalizeLandingPads();
71     bool LowerUnwinds();
72     bool MoveExceptionValueCalls();
73     bool FinishStackTemporaries();
74     bool PromoteStackTemporaries();
75
76     Instruction *CreateExceptionValueCall(BasicBlock *BB);
77     Instruction *CreateValueLoad(BasicBlock *BB);
78
79     /// CreateReadOfExceptionValue - Return the result of the eh.exception
80     /// intrinsic by calling the intrinsic if in a landing pad, or loading it
81     /// from the exception value variable otherwise.
82     Instruction *CreateReadOfExceptionValue(BasicBlock *BB) {
83       return LandingPads.count(BB) ?
84         CreateExceptionValueCall(BB) : CreateValueLoad(BB);
85     }
86
87     /// CleanupSelectors - Any remaining eh.selector intrinsic calls which still
88     /// use the ".llvm.eh.catch.all.value" call need to convert to using its
89     /// initializer instead.
90     bool CleanupSelectors();
91
92     bool IsACleanupSelector(IntrinsicInst *);
93
94     /// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
95     void FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels);
96
97     /// FindAllURoRInvokes - Find all URoR invokes in the function.
98     void FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes);
99
100     /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow"
101     /// calls. The "unwind" part of these invokes jump to a landing pad within
102     /// the current function. This is a candidate to merge the selector
103     /// associated with the URoR invoke with the one from the URoR's landing
104     /// pad.
105     bool HandleURoRInvokes();
106
107     /// FindSelectorAndURoR - Find the eh.selector call and URoR call associated
108     /// with the eh.exception call. This recursively looks past instructions
109     /// which don't change the EH pointer value, like casts or PHI nodes.
110     bool FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
111                              SmallPtrSet<IntrinsicInst*, 8> &SelCalls);
112       
113     /// DoMem2RegPromotion - Take an alloca call and promote it from memory to a
114     /// register.
115     bool DoMem2RegPromotion(Value *V) {
116       AllocaInst *AI = dyn_cast<AllocaInst>(V);
117       if (!AI || !isAllocaPromotable(AI)) return false;
118
119       // Turn the alloca into a register.
120       std::vector<AllocaInst*> Allocas(1, AI);
121       PromoteMemToReg(Allocas, *DT, *DF);
122       return true;
123     }
124
125     /// PromoteStoreInst - Perform Mem2Reg on a StoreInst.
126     bool PromoteStoreInst(StoreInst *SI) {
127       if (!SI || !DT || !DF) return false;
128       if (DoMem2RegPromotion(SI->getOperand(1)))
129         return true;
130       return false;
131     }
132
133     /// PromoteEHPtrStore - Promote the storing of an EH pointer into a
134     /// register. This should get rid of the store and subsequent loads.
135     bool PromoteEHPtrStore(IntrinsicInst *II) {
136       if (!DT || !DF) return false;
137
138       bool Changed = false;
139       StoreInst *SI;
140
141       while (1) {
142         SI = 0;
143         for (Value::use_iterator
144                I = II->use_begin(), E = II->use_end(); I != E; ++I) {
145           SI = dyn_cast<StoreInst>(I);
146           if (SI) break;
147         }
148
149         if (!PromoteStoreInst(SI))
150           break;
151
152         Changed = true;
153       }
154
155       return false;
156     }
157
158   public:
159     static char ID; // Pass identification, replacement for typeid.
160     DwarfEHPrepare(const TargetMachine *tm, bool fast) :
161       FunctionPass(&ID), TM(tm), TLI(TM->getTargetLowering()),
162       CompileFast(fast),
163       ExceptionValueIntrinsic(0), SelectorIntrinsic(0),
164       URoR(0), EHCatchAllValue(0), RewindFunction(0) {}
165
166     virtual bool runOnFunction(Function &Fn);
167
168     // getAnalysisUsage - We need dominance frontiers for memory promotion.
169     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
170       if (!CompileFast)
171         AU.addRequired<DominatorTree>();
172       AU.addPreserved<DominatorTree>();
173       if (!CompileFast)
174         AU.addRequired<DominanceFrontier>();
175       AU.addPreserved<DominanceFrontier>();
176     }
177
178     const char *getPassName() const {
179       return "Exception handling preparation";
180     }
181
182   };
183 } // end anonymous namespace
184
185 char DwarfEHPrepare::ID = 0;
186
187 FunctionPass *llvm::createDwarfEHPass(const TargetMachine *tm, bool fast) {
188   return new DwarfEHPrepare(tm, fast);
189 }
190
191 /// IsACleanupSelector - Return true if the intrinsic instruction is a clean-up
192 /// selector instruction.
193 bool DwarfEHPrepare::IsACleanupSelector(IntrinsicInst *II) {
194   unsigned NumOps = II->getNumOperands();
195   bool IsCleanUp = (NumOps == 3);
196
197   if (IsCleanUp)
198     return true;
199
200   if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getOperand(3))) {
201     unsigned Val = CI->getZExtValue();
202
203     if (Val == 0 || Val + 3 == NumOps) {
204       // If the value is 0 or the selector has only filters in it, then it's
205       // a cleanup.
206       return true;
207     } else {
208       assert(Val + 3 < NumOps && "Ill-formed eh.selector!");
209
210       if (Val + 4 == NumOps) {
211         if (ConstantInt *FinalVal =
212             dyn_cast<ConstantInt>(II->getOperand(NumOps - 1)))
213           return (FinalVal->getZExtValue() == 0);
214       }
215     }
216   }
217
218   return false;
219 }
220
221 /// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
222 void DwarfEHPrepare::
223 FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels) {
224   for (Value::use_iterator
225          I = SelectorIntrinsic->use_begin(),
226          E = SelectorIntrinsic->use_end(); I != E; ++I) {
227     IntrinsicInst *II = cast<IntrinsicInst>(I);
228
229     if (II->getParent()->getParent() != F)
230       continue;
231
232     if (IsACleanupSelector(II))
233       Sels.insert(II);
234   }
235 }
236
237 /// FindAllURoRInvokes - Find all URoR invokes in the function.
238 void DwarfEHPrepare::
239 FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes) {
240   for (Value::use_iterator
241          I = URoR->use_begin(),
242          E = URoR->use_end(); I != E; ++I) {
243     if (InvokeInst *II = dyn_cast<InvokeInst>(I))
244       URoRInvokes.insert(II);
245   }
246 }
247
248 /// CleanupSelectors - Any remaining eh.selector intrinsic calls which still use
249 /// the ".llvm.eh.catch.all.value" call need to convert to using its
250 /// initializer instead.
251 bool DwarfEHPrepare::CleanupSelectors() {
252   if (!EHCatchAllValue) return false;
253
254   if (!SelectorIntrinsic) {
255     SelectorIntrinsic =
256       Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
257     if (!SelectorIntrinsic) return false;
258   }
259
260   bool Changed = false;
261   for (Value::use_iterator
262          I = SelectorIntrinsic->use_begin(),
263          E = SelectorIntrinsic->use_end(); I != E; ++I) {
264     IntrinsicInst *Sel = dyn_cast<IntrinsicInst>(I);
265     if (!Sel || Sel->getParent()->getParent() != F) continue;
266
267     // Index of the ".llvm.eh.catch.all.value" variable.
268     unsigned OpIdx = Sel->getNumOperands() - 1;
269     GlobalVariable *GV = dyn_cast<GlobalVariable>(Sel->getOperand(OpIdx));
270     if (GV != EHCatchAllValue) continue;
271     Sel->setOperand(OpIdx, EHCatchAllValue->getInitializer());
272     Changed = true;
273   }
274
275   return Changed;
276 }
277
278 /// FindSelectorAndURoR - Find the eh.selector call associated with the
279 /// eh.exception call. And indicate if there is a URoR "invoke" associated with
280 /// the eh.exception call. This recursively looks past instructions which don't
281 /// change the EH pointer value, like casts or PHI nodes.
282 bool
283 DwarfEHPrepare::FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
284                                     SmallPtrSet<IntrinsicInst*, 8> &SelCalls) {
285   SmallPtrSet<PHINode*, 32> SeenPHIs;
286   bool Changed = false;
287
288  restart:
289   for (Value::use_iterator
290          I = Inst->use_begin(), E = Inst->use_end(); I != E; ++I) {
291     Instruction *II = dyn_cast<Instruction>(I);
292     if (!II || II->getParent()->getParent() != F) continue;
293     
294     if (IntrinsicInst *Sel = dyn_cast<IntrinsicInst>(II)) {
295       if (Sel->getIntrinsicID() == Intrinsic::eh_selector)
296         SelCalls.insert(Sel);
297     } else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(II)) {
298       if (Invoke->getCalledFunction() == URoR)
299         URoRInvoke = true;
300     } else if (CastInst *CI = dyn_cast<CastInst>(II)) {
301       Changed |= FindSelectorAndURoR(CI, URoRInvoke, SelCalls);
302     } else if (StoreInst *SI = dyn_cast<StoreInst>(II)) {
303       if (!PromoteStoreInst(SI)) continue;
304       Changed = true;
305       SeenPHIs.clear();
306       goto restart;             // Uses may have changed, restart loop.
307     } else if (PHINode *PN = dyn_cast<PHINode>(II)) {
308       if (SeenPHIs.insert(PN))
309         // Don't process a PHI node more than once.
310         Changed |= FindSelectorAndURoR(PN, URoRInvoke, SelCalls);
311     }
312   }
313
314   return Changed;
315 }
316
317 /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow" calls. The
318 /// "unwind" part of these invokes jump to a landing pad within the current
319 /// function. This is a candidate to merge the selector associated with the URoR
320 /// invoke with the one from the URoR's landing pad.
321 bool DwarfEHPrepare::HandleURoRInvokes() {
322   if (!DT) return CleanupSelectors(); // We require DominatorTree information.
323
324   if (!EHCatchAllValue) {
325     EHCatchAllValue =
326       F->getParent()->getNamedGlobal(".llvm.eh.catch.all.value");
327     if (!EHCatchAllValue) return false;
328   }
329
330   if (!SelectorIntrinsic) {
331     SelectorIntrinsic =
332       Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
333     if (!SelectorIntrinsic) return false;
334   }
335
336   if (!URoR) {
337     URoR = F->getParent()->getFunction("_Unwind_Resume_or_Rethrow");
338     if (!URoR) return CleanupSelectors();
339   }
340
341   SmallPtrSet<IntrinsicInst*, 32> Sels;
342   SmallPtrSet<InvokeInst*, 32> URoRInvokes;
343   FindAllCleanupSelectors(Sels);
344   FindAllURoRInvokes(URoRInvokes);
345
346   SmallPtrSet<IntrinsicInst*, 32> SelsToConvert;
347
348   for (SmallPtrSet<IntrinsicInst*, 32>::iterator
349          SI = Sels.begin(), SE = Sels.end(); SI != SE; ++SI) {
350     const BasicBlock *SelBB = (*SI)->getParent();
351     for (SmallPtrSet<InvokeInst*, 32>::iterator
352            UI = URoRInvokes.begin(), UE = URoRInvokes.end(); UI != UE; ++UI) {
353       const BasicBlock *URoRBB = (*UI)->getParent();
354       if (SelBB == URoRBB || DT->dominates(SelBB, URoRBB)) {
355         SelsToConvert.insert(*SI);
356         break;
357       }
358     }
359   }
360
361   bool Changed = false;
362
363   if (Sels.size() != SelsToConvert.size()) {
364     // If we haven't been able to convert all of the clean-up selectors, then
365     // loop through the slow way to see if they still need to be converted.
366     if (!ExceptionValueIntrinsic) {
367       ExceptionValueIntrinsic =
368         Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_exception);
369       if (!ExceptionValueIntrinsic) return CleanupSelectors();
370     }
371
372     for (Value::use_iterator
373            I = ExceptionValueIntrinsic->use_begin(),
374            E = ExceptionValueIntrinsic->use_end(); I != E; ++I) {
375       IntrinsicInst *EHPtr = dyn_cast<IntrinsicInst>(I);
376       if (!EHPtr || EHPtr->getParent()->getParent() != F) continue;
377
378       Changed |= PromoteEHPtrStore(EHPtr);
379
380       bool URoRInvoke = false;
381       SmallPtrSet<IntrinsicInst*, 8> SelCalls;
382       Changed |= FindSelectorAndURoR(EHPtr, URoRInvoke, SelCalls);
383
384       if (URoRInvoke) {
385         // This EH pointer is being used by an invoke of an URoR instruction and
386         // an eh.selector intrinsic call. If the eh.selector is a 'clean-up', we
387         // need to convert it to a 'catch-all'.
388         for (SmallPtrSet<IntrinsicInst*, 8>::iterator
389                SI = SelCalls.begin(), SE = SelCalls.end(); SI != SE; ++SI)
390           if (IsACleanupSelector(*SI))
391               SelsToConvert.insert(*SI);
392       }
393     }
394   }
395
396   if (!SelsToConvert.empty()) {
397     // Convert all clean-up eh.selectors, which are associated with "invokes" of
398     // URoR calls, into catch-all eh.selectors.
399     Changed = true;
400
401     for (SmallPtrSet<IntrinsicInst*, 8>::iterator
402            SI = SelsToConvert.begin(), SE = SelsToConvert.end();
403          SI != SE; ++SI) {
404       IntrinsicInst *II = *SI;
405       SmallVector<Value*, 8> Args;
406
407       // Use the exception object pointer and the personality function
408       // from the original selector.
409       Args.push_back(II->getOperand(1)); // Exception object pointer.
410       Args.push_back(II->getOperand(2)); // Personality function.
411
412       unsigned I = 3;
413       unsigned E = II->getNumOperands() -
414         (isa<ConstantInt>(II->getOperand(II->getNumOperands() - 1)) ? 1 : 0);
415
416       // Add in any filter IDs.
417       for (; I < E; ++I)
418         Args.push_back(II->getOperand(I));
419
420       Args.push_back(EHCatchAllValue->getInitializer()); // Catch-all indicator.
421
422       CallInst *NewSelector =
423         CallInst::Create(SelectorIntrinsic, Args.begin(), Args.end(),
424                          "eh.sel.catch.all", II);
425
426       NewSelector->setTailCall(II->isTailCall());
427       NewSelector->setAttributes(II->getAttributes());
428       NewSelector->setCallingConv(II->getCallingConv());
429
430       II->replaceAllUsesWith(NewSelector);
431       II->eraseFromParent();
432     }
433   }
434
435   Changed |= CleanupSelectors();
436   return Changed;
437 }
438
439 /// NormalizeLandingPads - Normalize and discover landing pads, noting them
440 /// in the LandingPads set.  A landing pad is normal if the only CFG edges
441 /// that end at it are unwind edges from invoke instructions. If we inlined
442 /// through an invoke we could have a normal branch from the previous
443 /// unwind block through to the landing pad for the original invoke.
444 /// Abnormal landing pads are fixed up by redirecting all unwind edges to
445 /// a new basic block which falls through to the original.
446 bool DwarfEHPrepare::NormalizeLandingPads() {
447   bool Changed = false;
448
449   const MCAsmInfo *MAI = TM->getMCAsmInfo();
450   bool usingSjLjEH = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
451
452   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
453     TerminatorInst *TI = I->getTerminator();
454     if (!isa<InvokeInst>(TI))
455       continue;
456     BasicBlock *LPad = TI->getSuccessor(1);
457     // Skip landing pads that have already been normalized.
458     if (LandingPads.count(LPad))
459       continue;
460
461     // Check that only invoke unwind edges end at the landing pad.
462     bool OnlyUnwoundTo = true;
463     bool SwitchOK = usingSjLjEH;
464     for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad);
465          PI != PE; ++PI) {
466       TerminatorInst *PT = (*PI)->getTerminator();
467       // The SjLj dispatch block uses a switch instruction. This is effectively
468       // an unwind edge, so we can disregard it here. There will only ever
469       // be one dispatch, however, so if there are multiple switches, one
470       // of them truly is a normal edge, not an unwind edge.
471       if (SwitchOK && isa<SwitchInst>(PT)) {
472         SwitchOK = false;
473         continue;
474       }
475       if (!isa<InvokeInst>(PT) || LPad == PT->getSuccessor(0)) {
476         OnlyUnwoundTo = false;
477         break;
478       }
479     }
480
481     if (OnlyUnwoundTo) {
482       // Only unwind edges lead to the landing pad.  Remember the landing pad.
483       LandingPads.insert(LPad);
484       continue;
485     }
486
487     // At least one normal edge ends at the landing pad.  Redirect the unwind
488     // edges to a new basic block which falls through into this one.
489
490     // Create the new basic block.
491     BasicBlock *NewBB = BasicBlock::Create(F->getContext(),
492                                            LPad->getName() + "_unwind_edge");
493
494     // Insert it into the function right before the original landing pad.
495     LPad->getParent()->getBasicBlockList().insert(LPad, NewBB);
496
497     // Redirect unwind edges from the original landing pad to NewBB.
498     for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad); PI != PE; ) {
499       TerminatorInst *PT = (*PI++)->getTerminator();
500       if (isa<InvokeInst>(PT) && PT->getSuccessor(1) == LPad)
501         // Unwind to the new block.
502         PT->setSuccessor(1, NewBB);
503     }
504
505     // If there are any PHI nodes in LPad, we need to update them so that they
506     // merge incoming values from NewBB instead.
507     for (BasicBlock::iterator II = LPad->begin(); isa<PHINode>(II); ++II) {
508       PHINode *PN = cast<PHINode>(II);
509       pred_iterator PB = pred_begin(NewBB), PE = pred_end(NewBB);
510
511       // Check to see if all of the values coming in via unwind edges are the
512       // same.  If so, we don't need to create a new PHI node.
513       Value *InVal = PN->getIncomingValueForBlock(*PB);
514       for (pred_iterator PI = PB; PI != PE; ++PI) {
515         if (PI != PB && InVal != PN->getIncomingValueForBlock(*PI)) {
516           InVal = 0;
517           break;
518         }
519       }
520
521       if (InVal == 0) {
522         // Different unwind edges have different values.  Create a new PHI node
523         // in NewBB.
524         PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".unwind",
525                                          NewBB);
526         // Add an entry for each unwind edge, using the value from the old PHI.
527         for (pred_iterator PI = PB; PI != PE; ++PI)
528           NewPN->addIncoming(PN->getIncomingValueForBlock(*PI), *PI);
529
530         // Now use this new PHI as the common incoming value for NewBB in PN.
531         InVal = NewPN;
532       }
533
534       // Revector exactly one entry in the PHI node to come from NewBB
535       // and delete all other entries that come from unwind edges.  If
536       // there are both normal and unwind edges from the same predecessor,
537       // this leaves an entry for the normal edge.
538       for (pred_iterator PI = PB; PI != PE; ++PI)
539         PN->removeIncomingValue(*PI);
540       PN->addIncoming(InVal, NewBB);
541     }
542
543     // Add a fallthrough from NewBB to the original landing pad.
544     BranchInst::Create(LPad, NewBB);
545
546     // Now update DominatorTree and DominanceFrontier analysis information.
547     if (DT)
548       DT->splitBlock(NewBB);
549     if (DF)
550       DF->splitBlock(NewBB);
551
552     // Remember the newly constructed landing pad.  The original landing pad
553     // LPad is no longer a landing pad now that all unwind edges have been
554     // revectored to NewBB.
555     LandingPads.insert(NewBB);
556     ++NumLandingPadsSplit;
557     Changed = true;
558   }
559
560   return Changed;
561 }
562
563 /// LowerUnwinds - Turn unwind instructions into calls to _Unwind_Resume,
564 /// rethrowing any previously caught exception.  This will crash horribly
565 /// at runtime if there is no such exception: using unwind to throw a new
566 /// exception is currently not supported.
567 bool DwarfEHPrepare::LowerUnwinds() {
568   SmallVector<TerminatorInst*, 16> UnwindInsts;
569
570   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
571     TerminatorInst *TI = I->getTerminator();
572     if (isa<UnwindInst>(TI))
573       UnwindInsts.push_back(TI);
574   }
575
576   if (UnwindInsts.empty()) return false;
577
578   // Find the rewind function if we didn't already.
579   if (!RewindFunction) {
580     LLVMContext &Ctx = UnwindInsts[0]->getContext();
581     std::vector<const Type*>
582       Params(1, Type::getInt8PtrTy(Ctx));
583     FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
584                                           Params, false);
585     const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
586     RewindFunction = F->getParent()->getOrInsertFunction(RewindName, FTy);
587   }
588
589   bool Changed = false;
590
591   for (SmallVectorImpl<TerminatorInst*>::iterator
592          I = UnwindInsts.begin(), E = UnwindInsts.end(); I != E; ++I) {
593     TerminatorInst *TI = *I;
594
595     // Replace the unwind instruction with a call to _Unwind_Resume (or the
596     // appropriate target equivalent) followed by an UnreachableInst.
597
598     // Create the call...
599     CallInst *CI = CallInst::Create(RewindFunction,
600                                     CreateReadOfExceptionValue(TI->getParent()),
601                                     "", TI);
602     CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
603     // ...followed by an UnreachableInst.
604     new UnreachableInst(TI->getContext(), TI);
605
606     // Nuke the unwind instruction.
607     TI->eraseFromParent();
608     ++NumUnwindsLowered;
609     Changed = true;
610   }
611
612   return Changed;
613 }
614
615 /// MoveExceptionValueCalls - Ensure that eh.exception is only ever called from
616 /// landing pads by replacing calls outside of landing pads with loads from a
617 /// stack temporary.  Move eh.exception calls inside landing pads to the start
618 /// of the landing pad (optional, but may make things simpler for later passes).
619 bool DwarfEHPrepare::MoveExceptionValueCalls() {
620   // If the eh.exception intrinsic is not declared in the module then there is
621   // nothing to do.  Speed up compilation by checking for this common case.
622   if (!ExceptionValueIntrinsic &&
623       !F->getParent()->getFunction(Intrinsic::getName(Intrinsic::eh_exception)))
624     return false;
625
626   bool Changed = false;
627
628   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
629     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
630       if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
631         if (CI->getIntrinsicID() == Intrinsic::eh_exception) {
632           if (!CI->use_empty()) {
633             Value *ExceptionValue = CreateReadOfExceptionValue(BB);
634             if (CI == ExceptionValue) {
635               // The call was at the start of a landing pad - leave it alone.
636               assert(LandingPads.count(BB) &&
637                      "Created eh.exception call outside landing pad!");
638               continue;
639             }
640             CI->replaceAllUsesWith(ExceptionValue);
641           }
642           CI->eraseFromParent();
643           ++NumExceptionValuesMoved;
644           Changed = true;
645         }
646   }
647
648   return Changed;
649 }
650
651 /// FinishStackTemporaries - If we introduced a stack variable to hold the
652 /// exception value then initialize it in each landing pad.
653 bool DwarfEHPrepare::FinishStackTemporaries() {
654   if (!ExceptionValueVar)
655     // Nothing to do.
656     return false;
657
658   bool Changed = false;
659
660   // Make sure that there is a store of the exception value at the start of
661   // each landing pad.
662   for (BBSet::iterator LI = LandingPads.begin(), LE = LandingPads.end();
663        LI != LE; ++LI) {
664     Instruction *ExceptionValue = CreateReadOfExceptionValue(*LI);
665     Instruction *Store = new StoreInst(ExceptionValue, ExceptionValueVar);
666     Store->insertAfter(ExceptionValue);
667     Changed = true;
668   }
669
670   return Changed;
671 }
672
673 /// PromoteStackTemporaries - Turn any stack temporaries we introduced into
674 /// registers if possible.
675 bool DwarfEHPrepare::PromoteStackTemporaries() {
676   if (ExceptionValueVar && DT && DF && isAllocaPromotable(ExceptionValueVar)) {
677     // Turn the exception temporary into registers and phi nodes if possible.
678     std::vector<AllocaInst*> Allocas(1, ExceptionValueVar);
679     PromoteMemToReg(Allocas, *DT, *DF);
680     return true;
681   }
682   return false;
683 }
684
685 /// CreateExceptionValueCall - Insert a call to the eh.exception intrinsic at
686 /// the start of the basic block (unless there already is one, in which case
687 /// the existing call is returned).
688 Instruction *DwarfEHPrepare::CreateExceptionValueCall(BasicBlock *BB) {
689   Instruction *Start = BB->getFirstNonPHIOrDbg();
690   // Is this a call to eh.exception?
691   if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Start))
692     if (CI->getIntrinsicID() == Intrinsic::eh_exception)
693       // Reuse the existing call.
694       return Start;
695
696   // Find the eh.exception intrinsic if we didn't already.
697   if (!ExceptionValueIntrinsic)
698     ExceptionValueIntrinsic = Intrinsic::getDeclaration(F->getParent(),
699                                                        Intrinsic::eh_exception);
700
701   // Create the call.
702   return CallInst::Create(ExceptionValueIntrinsic, "eh.value.call", Start);
703 }
704
705 /// CreateValueLoad - Insert a load of the exception value stack variable
706 /// (creating it if necessary) at the start of the basic block (unless
707 /// there already is a load, in which case the existing load is returned).
708 Instruction *DwarfEHPrepare::CreateValueLoad(BasicBlock *BB) {
709   Instruction *Start = BB->getFirstNonPHIOrDbg();
710   // Is this a load of the exception temporary?
711   if (ExceptionValueVar)
712     if (LoadInst* LI = dyn_cast<LoadInst>(Start))
713       if (LI->getPointerOperand() == ExceptionValueVar)
714         // Reuse the existing load.
715         return Start;
716
717   // Create the temporary if we didn't already.
718   if (!ExceptionValueVar) {
719     ExceptionValueVar = new AllocaInst(PointerType::getUnqual(
720            Type::getInt8Ty(BB->getContext())), "eh.value", F->begin()->begin());
721     ++NumStackTempsIntroduced;
722   }
723
724   // Load the value.
725   return new LoadInst(ExceptionValueVar, "eh.value.load", Start);
726 }
727
728 bool DwarfEHPrepare::runOnFunction(Function &Fn) {
729   bool Changed = false;
730
731   // Initialize internal state.
732   DT = getAnalysisIfAvailable<DominatorTree>();
733   DF = getAnalysisIfAvailable<DominanceFrontier>();
734   ExceptionValueVar = 0;
735   F = &Fn;
736
737   // Ensure that only unwind edges end at landing pads (a landing pad is a
738   // basic block where an invoke unwind edge ends).
739   Changed |= NormalizeLandingPads();
740
741   // Turn unwind instructions into libcalls.
742   Changed |= LowerUnwinds();
743
744   // TODO: Move eh.selector calls to landing pads and combine them.
745
746   // Move eh.exception calls to landing pads.
747   Changed |= MoveExceptionValueCalls();
748
749   // Initialize any stack temporaries we introduced.
750   Changed |= FinishStackTemporaries();
751
752   // Turn any stack temporaries into registers if possible.
753   if (!CompileFast)
754     Changed |= PromoteStackTemporaries();
755
756   Changed |= HandleURoRInvokes();
757
758   LandingPads.clear();
759
760   return Changed;
761 }