blob: d5a2ed977f3a47b765cc8e301f631073bbd26ece [file] [log] [blame]
Duncan Sandsb0f1e172009-05-22 20:36:31 +00001//===-- 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
Bill Wendling2ad4aca2010-03-26 23:41:30 +000011// generation. Required if using dwarf exception handling.
Duncan Sandsb0f1e172009-05-22 20:36:31 +000012//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "dwarfehprepare"
Duncan Sandsb0f1e172009-05-22 20:36:31 +000016#include "llvm/Function.h"
17#include "llvm/Instructions.h"
18#include "llvm/IntrinsicInst.h"
19#include "llvm/Module.h"
20#include "llvm/Pass.h"
Bill Wendling2ad4aca2010-03-26 23:41:30 +000021#include "llvm/ADT/Statistic.h"
22#include "llvm/Analysis/Dominators.h"
23#include "llvm/CodeGen/Passes.h"
Jim Grosbach8d77cc82010-01-20 23:03:55 +000024#include "llvm/MC/MCAsmInfo.h"
Gabor Greif2bf4b3b2010-06-25 11:25:30 +000025#include "llvm/Support/CallSite.h"
Duncan Sandsb0f1e172009-05-22 20:36:31 +000026#include "llvm/Target/TargetLowering.h"
27#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Duncan Sands850fcd42010-09-03 08:31:48 +000028#include "llvm/Transforms/Utils/SSAUpdater.h"
Duncan Sandsb0f1e172009-05-22 20:36:31 +000029using namespace llvm;
30
Bill Wendlingf58898f2009-10-29 00:22:16 +000031STATISTIC(NumLandingPadsSplit, "Number of landing pads split");
Bill Wendlingf58898f2009-10-29 00:22:16 +000032STATISTIC(NumUnwindsLowered, "Number of unwind instructions lowered");
Bill Wendling8bedf972009-10-29 00:37:35 +000033STATISTIC(NumExceptionValuesMoved, "Number of eh.exception calls moved");
Duncan Sandsb0f1e172009-05-22 20:36:31 +000034
35namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000036 class DwarfEHPrepare : public FunctionPass {
Dan Gohman55e59c12010-04-19 19:05:59 +000037 const TargetMachine *TM;
Duncan Sandsb0f1e172009-05-22 20:36:31 +000038 const TargetLowering *TLI;
Duncan Sandsb0f1e172009-05-22 20:36:31 +000039
40 // The eh.exception intrinsic.
Bill Wendling8bedf972009-10-29 00:37:35 +000041 Function *ExceptionValueIntrinsic;
Duncan Sandsb0f1e172009-05-22 20:36:31 +000042
Bill Wendling2ad4aca2010-03-26 23:41:30 +000043 // The eh.selector intrinsic.
44 Function *SelectorIntrinsic;
45
Bill Wendling49ad7312010-10-29 07:46:01 +000046 // _Unwind_Resume_or_Rethrow or _Unwind_SjLj_Resume call.
Bill Wendling2ad4aca2010-03-26 23:41:30 +000047 Constant *URoR;
48
49 // The EH language-specific catch-all type.
50 GlobalVariable *EHCatchAllValue;
51
Duncan Sandsb0f1e172009-05-22 20:36:31 +000052 // _Unwind_Resume or the target equivalent.
53 Constant *RewindFunction;
54
Duncan Sands22efc182010-08-31 09:05:06 +000055 // We both use and preserve dominator info.
Duncan Sandsb0f1e172009-05-22 20:36:31 +000056 DominatorTree *DT;
Duncan Sandsb0f1e172009-05-22 20:36:31 +000057
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
Duncan Sandsb0f1e172009-05-22 20:36:31 +000065 bool NormalizeLandingPads();
66 bool LowerUnwinds();
67 bool MoveExceptionValueCalls();
Duncan Sandsb0f1e172009-05-22 20:36:31 +000068
69 Instruction *CreateExceptionValueCall(BasicBlock *BB);
Duncan Sandsb0f1e172009-05-22 20:36:31 +000070
Bill Wendlingbfbd8532010-03-27 01:19:12 +000071 /// CleanupSelectors - Any remaining eh.selector intrinsic calls which still
Bill Wendling23295cc2010-07-26 22:36:52 +000072 /// use the "llvm.eh.catch.all.value" call need to convert to using its
Bill Wendlingbfbd8532010-03-27 01:19:12 +000073 /// initializer instead.
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +000074 bool CleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels);
Bill Wendlingbfbd8532010-03-27 01:19:12 +000075
Bill Wendlingefbf3062010-06-24 18:49:10 +000076 bool HasCatchAllInSelector(IntrinsicInst *);
Bill Wendling94366112010-06-12 02:34:29 +000077
Bill Wendlingbfde6442010-03-29 23:02:46 +000078 /// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +000079 void FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels,
80 SmallPtrSet<IntrinsicInst*, 32> &CatchAllSels);
Bill Wendlingbfde6442010-03-29 23:02:46 +000081
82 /// FindAllURoRInvokes - Find all URoR invokes in the function.
83 void FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes);
84
Bill Wendling49ad7312010-10-29 07:46:01 +000085 /// 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.
Bill Wendling2ad4aca2010-03-26 23:41:30 +000090 bool HandleURoRInvokes();
91
Bill Wendling201f5f02010-03-29 23:37:07 +000092 /// 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,
Bill Wendling28cc1aa2011-03-15 01:03:17 +000096 SmallPtrSet<IntrinsicInst*, 8> &SelCalls,
97 SmallPtrSet<PHINode*, 32> &SeenPHIs);
Bill Wendling201f5f02010-03-29 23:37:07 +000098
Duncan Sandsb0f1e172009-05-22 20:36:31 +000099 public:
100 static char ID; // Pass identification, replacement for typeid.
Duncan Sands22efc182010-08-31 09:05:06 +0000101 DwarfEHPrepare(const TargetMachine *tm) :
Owen Anderson90c579d2010-08-06 18:33:48 +0000102 FunctionPass(ID), TM(tm), TLI(TM->getTargetLowering()),
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000103 ExceptionValueIntrinsic(0), SelectorIntrinsic(0),
Owen Anderson081c34b2010-10-19 17:21:58 +0000104 URoR(0), EHCatchAllValue(0), RewindFunction(0) {
105 initializeDominatorTreePass(*PassRegistry::getPassRegistry());
106 }
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000107
108 virtual bool runOnFunction(Function &Fn);
109
Duncan Sands850fcd42010-09-03 08:31:48 +0000110 // getAnalysisUsage - We need the dominator tree for handling URoR.
Bill Wendling8bedf972009-10-29 00:37:35 +0000111 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Duncan Sands22efc182010-08-31 09:05:06 +0000112 AU.addRequired<DominatorTree>();
Bill Wendling8bedf972009-10-29 00:37:35 +0000113 AU.addPreserved<DominatorTree>();
Bill Wendling8bedf972009-10-29 00:37:35 +0000114 }
115
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000116 const char *getPassName() const {
117 return "Exception handling preparation";
118 }
119
120 };
121} // end anonymous namespace
122
123char DwarfEHPrepare::ID = 0;
124
Duncan Sands22efc182010-08-31 09:05:06 +0000125FunctionPass *llvm::createDwarfEHPass(const TargetMachine *tm) {
126 return new DwarfEHPrepare(tm);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000127}
128
Bill Wendlingefbf3062010-06-24 18:49:10 +0000129/// HasCatchAllInSelector - Return true if the intrinsic instruction has a
130/// catch-all.
131bool DwarfEHPrepare::HasCatchAllInSelector(IntrinsicInst *II) {
132 if (!EHCatchAllValue) return false;
Bill Wendling94366112010-06-12 02:34:29 +0000133
Gabor Greif2bf4b3b2010-06-25 11:25:30 +0000134 unsigned ArgIdx = II->getNumArgOperands() - 1;
135 GlobalVariable *GV = dyn_cast<GlobalVariable>(II->getArgOperand(ArgIdx));
Bill Wendlingefbf3062010-06-24 18:49:10 +0000136 return GV == EHCatchAllValue;
Bill Wendling94366112010-06-12 02:34:29 +0000137}
138
Bill Wendlingbfde6442010-03-29 23:02:46 +0000139/// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups.
140void DwarfEHPrepare::
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000141FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels,
142 SmallPtrSet<IntrinsicInst*, 32> &CatchAllSels) {
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000143 for (Value::use_iterator
Bill Wendlingbfde6442010-03-29 23:02:46 +0000144 I = SelectorIntrinsic->use_begin(),
145 E = SelectorIntrinsic->use_end(); I != E; ++I) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000146 IntrinsicInst *II = cast<IntrinsicInst>(*I);
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000147
Bill Wendling94366112010-06-12 02:34:29 +0000148 if (II->getParent()->getParent() != F)
149 continue;
Bill Wendlingbfde6442010-03-29 23:02:46 +0000150
Bill Wendlingefbf3062010-06-24 18:49:10 +0000151 if (!HasCatchAllInSelector(II))
Bill Wendling94366112010-06-12 02:34:29 +0000152 Sels.insert(II);
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000153 else
154 CatchAllSels.insert(II);
Bill Wendlingbfde6442010-03-29 23:02:46 +0000155 }
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) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000164 if (InvokeInst *II = dyn_cast<InvokeInst>(*I))
Bill Wendlingbfde6442010-03-29 23:02:46 +0000165 URoRInvokes.insert(II);
166 }
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000167}
168
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000169/// CleanupSelectors - Any remaining eh.selector intrinsic calls which still use
Bill Wendling23295cc2010-07-26 22:36:52 +0000170/// the "llvm.eh.catch.all.value" call need to convert to using its
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000171/// initializer instead.
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000172bool DwarfEHPrepare::CleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels) {
Bill Wendlingbfde6442010-03-29 23:02:46 +0000173 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
Bill Wendling43de15f2010-03-27 01:22:38 +0000181 bool Changed = false;
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000182 for (SmallPtrSet<IntrinsicInst*, 32>::iterator
183 I = Sels.begin(), E = Sels.end(); I != E; ++I) {
184 IntrinsicInst *Sel = *I;
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000185
Bill Wendling23295cc2010-07-26 22:36:52 +0000186 // Index of the "llvm.eh.catch.all.value" variable.
Gabor Greif9d677682010-06-29 13:03:46 +0000187 unsigned OpIdx = Sel->getNumArgOperands() - 1;
188 GlobalVariable *GV = dyn_cast<GlobalVariable>(Sel->getArgOperand(OpIdx));
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000189 if (GV != EHCatchAllValue) continue;
Gabor Greif9d677682010-06-29 13:03:46 +0000190 Sel->setArgOperand(OpIdx, EHCatchAllValue->getInitializer());
Bill Wendling43de15f2010-03-27 01:22:38 +0000191 Changed = true;
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000192 }
Bill Wendling43de15f2010-03-27 01:22:38 +0000193
194 return Changed;
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000195}
196
Bill Wendling201f5f02010-03-29 23:37:07 +0000197/// 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,
Bill Wendling28cc1aa2011-03-15 01:03:17 +0000203 SmallPtrSet<IntrinsicInst*, 8> &SelCalls,
204 SmallPtrSet<PHINode*, 32> &SeenPHIs) {
Bill Wendling201f5f02010-03-29 23:37:07 +0000205 bool Changed = false;
206
Bill Wendling201f5f02010-03-29 23:37:07 +0000207 for (Value::use_iterator
208 I = Inst->use_begin(), E = Inst->use_end(); I != E; ++I) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000209 Instruction *II = dyn_cast<Instruction>(*I);
Bill Wendling201f5f02010-03-29 23:37:07 +0000210 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)) {
Bill Wendling28cc1aa2011-03-15 01:03:17 +0000219 Changed |= FindSelectorAndURoR(CI, URoRInvoke, SelCalls, SeenPHIs);
Bill Wendling201f5f02010-03-29 23:37:07 +0000220 } else if (PHINode *PN = dyn_cast<PHINode>(II)) {
221 if (SeenPHIs.insert(PN))
222 // Don't process a PHI node more than once.
Bill Wendling28cc1aa2011-03-15 01:03:17 +0000223 Changed |= FindSelectorAndURoR(PN, URoRInvoke, SelCalls, SeenPHIs);
Bill Wendling201f5f02010-03-29 23:37:07 +0000224 }
225 }
226
227 return Changed;
228}
229
Bill Wendling49ad7312010-10-29 07:46:01 +0000230/// 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.
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000235bool DwarfEHPrepare::HandleURoRInvokes() {
236 if (!EHCatchAllValue) {
237 EHCatchAllValue =
Bill Wendling23295cc2010-07-26 22:36:52 +0000238 F->getParent()->getNamedGlobal("llvm.eh.catch.all.value");
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000239 if (!EHCatchAllValue) return false;
240 }
241
Bill Wendlingbfbd8532010-03-27 01:19:12 +0000242 if (!SelectorIntrinsic) {
243 SelectorIntrinsic =
244 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
245 if (!SelectorIntrinsic) return false;
246 }
247
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000248 SmallPtrSet<IntrinsicInst*, 32> Sels;
249 SmallPtrSet<IntrinsicInst*, 32> CatchAllSels;
250 FindAllCleanupSelectors(Sels, CatchAllSels);
251
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000252 if (!URoR) {
253 URoR = F->getParent()->getFunction("_Unwind_Resume_or_Rethrow");
Bill Wendling49ad7312010-10-29 07:46:01 +0000254 if (!URoR) {
255 URoR = F->getParent()->getFunction("_Unwind_SjLj_Resume");
256 if (!URoR) return CleanupSelectors(CatchAllSels);
257 }
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000258 }
259
Bill Wendlingbfde6442010-03-29 23:02:46 +0000260 SmallPtrSet<InvokeInst*, 32> URoRInvokes;
Bill Wendlingbfde6442010-03-29 23:02:46 +0000261 FindAllURoRInvokes(URoRInvokes);
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000262
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000263 SmallPtrSet<IntrinsicInst*, 32> SelsToConvert;
264
Bill Wendlingbfde6442010-03-29 23:02:46 +0000265 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();
Dan Gohmance0fe5d2010-07-26 17:38:15 +0000271 if (DT->dominates(SelBB, URoRBB)) {
Bill Wendlingbfde6442010-03-29 23:02:46 +0000272 SelsToConvert.insert(*SI);
273 break;
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000274 }
275 }
276 }
277
Bill Wendlingbfde6442010-03-29 23:02:46 +0000278 bool Changed = false;
279
Bill Wendling201f5f02010-03-29 23:37:07 +0000280 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);
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000286 if (!ExceptionValueIntrinsic)
287 return CleanupSelectors(CatchAllSels);
Bill Wendling201f5f02010-03-29 23:37:07 +0000288 }
289
290 for (Value::use_iterator
291 I = ExceptionValueIntrinsic->use_begin(),
292 E = ExceptionValueIntrinsic->use_end(); I != E; ++I) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000293 IntrinsicInst *EHPtr = dyn_cast<IntrinsicInst>(*I);
Bill Wendling201f5f02010-03-29 23:37:07 +0000294 if (!EHPtr || EHPtr->getParent()->getParent() != F) continue;
295
Bill Wendling201f5f02010-03-29 23:37:07 +0000296 bool URoRInvoke = false;
297 SmallPtrSet<IntrinsicInst*, 8> SelCalls;
Bill Wendling28cc1aa2011-03-15 01:03:17 +0000298 SmallPtrSet<PHINode*, 32> SeenPHIs;
299 Changed |= FindSelectorAndURoR(EHPtr, URoRInvoke, SelCalls, SeenPHIs);
Bill Wendling201f5f02010-03-29 23:37:07 +0000300
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
Bill Wendling94366112010-06-12 02:34:29 +0000306 SI = SelCalls.begin(), SE = SelCalls.end(); SI != SE; ++SI)
Bill Wendlingefbf3062010-06-24 18:49:10 +0000307 if (!HasCatchAllInSelector(*SI))
Bill Wendling94366112010-06-12 02:34:29 +0000308 SelsToConvert.insert(*SI);
Bill Wendling201f5f02010-03-29 23:37:07 +0000309 }
310 }
311 }
312
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000313 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;
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000322
323 // Use the exception object pointer and the personality function
324 // from the original selector.
Gabor Greif2bf4b3b2010-06-25 11:25:30 +0000325 CallSite CS(II);
326 IntrinsicInst::op_iterator I = CS.arg_begin();
Gabor Greif2bf4b3b2010-06-25 11:25:30 +0000327 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;
Bill Wendling94366112010-06-12 02:34:29 +0000332
Gabor Greif32621ad2010-06-28 16:40:52 +0000333 // Add exception object pointer (front).
334 // Add personality function (next).
335 // Add in any filter IDs (rest).
336 SmallVector<Value*, 8> Args(I, E);
Bill Wendling94366112010-06-12 02:34:29 +0000337
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000338 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
Bill Wendlingd9e3b2b2010-06-30 22:49:53 +0000353 Changed |= CleanupSelectors(CatchAllSels);
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000354 return Changed;
355}
356
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000357/// NormalizeLandingPads - Normalize and discover landing pads, noting them
358/// in the LandingPads set. A landing pad is normal if the only CFG edges
Eric Christopherec26bf72009-09-15 21:56:46 +0000359/// 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.
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000362/// 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
Dan Gohman55e59c12010-04-19 19:05:59 +0000367 const MCAsmInfo *MAI = TM->getMCAsmInfo();
Jim Grosbach8d77cc82010-01-20 23:03:55 +0000368 bool usingSjLjEH = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
369
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000370 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;
Jim Grosbach8d77cc82010-01-20 23:03:55 +0000381 bool SwitchOK = usingSjLjEH;
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000382 for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad);
383 PI != PE; ++PI) {
384 TerminatorInst *PT = (*PI)->getTerminator();
Jim Grosbach8d77cc82010-01-20 23:03:55 +0000385 // 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 }
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000393 if (!isa<InvokeInst>(PT) || LPad == PT->getSuccessor(0)) {
394 OnlyUnwoundTo = false;
395 break;
396 }
397 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000398
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000399 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.
Bill Wendling8bedf972009-10-29 00:37:35 +0000409 BasicBlock *NewBB = BasicBlock::Create(F->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +0000410 LPad->getName() + "_unwind_edge");
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000411
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 // 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);
447
448 // Now use this new PHI as the common incoming value for NewBB in PN.
449 InVal = NewPN;
450 }
451
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);
459 }
460
461 // Add a fallthrough from NewBB to the original landing pad.
462 BranchInst::Create(LPad, NewBB);
463
Duncan Sands22efc182010-08-31 09:05:06 +0000464 // Now update DominatorTree analysis information.
465 DT->splitBlock(NewBB);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000466
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;
472 Changed = true;
473 }
474
475 return Changed;
476}
477
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.
482bool DwarfEHPrepare::LowerUnwinds() {
Bill Wendling43488712009-09-14 20:52:37 +0000483 SmallVector<TerminatorInst*, 16> UnwindInsts;
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000484
485 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
486 TerminatorInst *TI = I->getTerminator();
Bill Wendling43488712009-09-14 20:52:37 +0000487 if (isa<UnwindInst>(TI))
488 UnwindInsts.push_back(TI);
489 }
490
491 if (UnwindInsts.empty()) return false;
492
493 // Find the rewind function if we didn't already.
494 if (!RewindFunction) {
Bill Wendling8bedf972009-10-29 00:37:35 +0000495 LLVMContext &Ctx = UnwindInsts[0]->getContext();
Bill Wendling43488712009-09-14 20:52:37 +0000496 std::vector<const Type*>
Bill Wendling8bedf972009-10-29 00:37:35 +0000497 Params(1, Type::getInt8PtrTy(Ctx));
498 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
Bill Wendling43488712009-09-14 20:52:37 +0000499 Params, false);
500 const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
501 RewindFunction = F->getParent()->getOrInsertFunction(RewindName, FTy);
502 }
503
Bill Wendling8bedf972009-10-29 00:37:35 +0000504 bool Changed = false;
505
Bill Wendling43488712009-09-14 20:52:37 +0000506 for (SmallVectorImpl<TerminatorInst*>::iterator
507 I = UnwindInsts.begin(), E = UnwindInsts.end(); I != E; ++I) {
508 TerminatorInst *TI = *I;
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000509
510 // Replace the unwind instruction with a call to _Unwind_Resume (or the
511 // appropriate target equivalent) followed by an UnreachableInst.
512
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000513 // Create the call...
Eric Christopher82f149d2009-09-04 01:14:14 +0000514 CallInst *CI = CallInst::Create(RewindFunction,
Duncan Sands850fcd42010-09-03 08:31:48 +0000515 CreateExceptionValueCall(TI->getParent()),
Bill Wendling43488712009-09-14 20:52:37 +0000516 "", TI);
Eric Christopher82f149d2009-09-04 01:14:14 +0000517 CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000518 // ...followed by an UnreachableInst.
Bill Wendling8bedf972009-10-29 00:37:35 +0000519 new UnreachableInst(TI->getContext(), TI);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000520
521 // Nuke the unwind instruction.
522 TI->eraseFromParent();
523 ++NumUnwindsLowered;
524 Changed = true;
525 }
526
527 return Changed;
528}
529
530/// MoveExceptionValueCalls - Ensure that eh.exception is only ever called from
Duncan Sands850fcd42010-09-03 08:31:48 +0000531/// landing pads by replacing calls outside of landing pads with direct use of
532/// a register holding the appropriate value; this requires adding calls inside
533/// all landing pads to initialize the register. Also, move eh.exception calls
534/// inside landing pads to the start of the landing pad (optional, but may make
535/// things simpler for later passes).
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000536bool DwarfEHPrepare::MoveExceptionValueCalls() {
537 // If the eh.exception intrinsic is not declared in the module then there is
538 // nothing to do. Speed up compilation by checking for this common case.
Bill Wendling8bedf972009-10-29 00:37:35 +0000539 if (!ExceptionValueIntrinsic &&
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000540 !F->getParent()->getFunction(Intrinsic::getName(Intrinsic::eh_exception)))
541 return false;
542
543 bool Changed = false;
544
Duncan Sands850fcd42010-09-03 08:31:48 +0000545 // Move calls to eh.exception that are inside a landing pad to the start of
546 // the landing pad.
547 for (BBSet::const_iterator LI = LandingPads.begin(), LE = LandingPads.end();
Eric Christopheradc581f2010-09-01 17:29:10 +0000548 LI != LE; ++LI) {
Duncan Sands850fcd42010-09-03 08:31:48 +0000549 BasicBlock *LP = *LI;
550 for (BasicBlock::iterator II = LP->getFirstNonPHIOrDbg(), IE = LP->end();
551 II != IE;)
552 if (EHExceptionInst *EI = dyn_cast<EHExceptionInst>(II++)) {
553 // Found a call to eh.exception.
554 if (!EI->use_empty()) {
555 // If there is already a call to eh.exception at the start of the
556 // landing pad, then get hold of it; otherwise create such a call.
557 Value *CallAtStart = CreateExceptionValueCall(LP);
558
559 // If the call was at the start of a landing pad then leave it alone.
560 if (EI == CallAtStart)
561 continue;
562 EI->replaceAllUsesWith(CallAtStart);
563 }
564 EI->eraseFromParent();
565 ++NumExceptionValuesMoved;
566 Changed = true;
567 }
Duncan Sandsfb4e8ab2010-09-01 14:07:47 +0000568 }
569
Duncan Sands850fcd42010-09-03 08:31:48 +0000570 // Look for calls to eh.exception that are not in a landing pad. If one is
571 // found, then a register that holds the exception value will be created in
572 // each landing pad, and the SSAUpdater will be used to compute the values
573 // returned by eh.exception calls outside of landing pads.
574 SSAUpdater SSA;
575
576 // Remember where we found the eh.exception call, to avoid rescanning earlier
577 // basic blocks which we already know contain no eh.exception calls.
578 bool FoundCallOutsideLandingPad = false;
579 Function::iterator BB = F->begin();
580 for (Function::iterator BE = F->end(); BB != BE; ++BB) {
581 // Skip over landing pads.
582 if (LandingPads.count(BB))
583 continue;
584
585 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
586 II != IE; ++II)
587 if (isa<EHExceptionInst>(II)) {
588 SSA.Initialize(II->getType(), II->getName());
589 FoundCallOutsideLandingPad = true;
590 break;
591 }
592
593 if (FoundCallOutsideLandingPad)
594 break;
595 }
596
597 // If all calls to eh.exception are in landing pads then we are done.
598 if (!FoundCallOutsideLandingPad)
599 return Changed;
600
601 // Add a call to eh.exception at the start of each landing pad, and tell the
602 // SSAUpdater that this is the value produced by the landing pad.
603 for (BBSet::iterator LI = LandingPads.begin(), LE = LandingPads.end();
604 LI != LE; ++LI)
605 SSA.AddAvailableValue(*LI, CreateExceptionValueCall(*LI));
606
607 // Now turn all calls to eh.exception that are not in a landing pad into a use
608 // of the appropriate register.
609 for (Function::iterator BE = F->end(); BB != BE; ++BB) {
610 // Skip over landing pads.
611 if (LandingPads.count(BB))
612 continue;
613
614 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
615 II != IE;)
616 if (EHExceptionInst *EI = dyn_cast<EHExceptionInst>(II++)) {
617 // Found a call to eh.exception, replace it with the value from any
618 // upstream landing pad(s).
619 EI->replaceAllUsesWith(SSA.GetValueAtEndOfBlock(BB));
620 EI->eraseFromParent();
621 ++NumExceptionValuesMoved;
622 }
623 }
624
625 return true;
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000626}
627
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000628/// CreateExceptionValueCall - Insert a call to the eh.exception intrinsic at
629/// the start of the basic block (unless there already is one, in which case
630/// the existing call is returned).
631Instruction *DwarfEHPrepare::CreateExceptionValueCall(BasicBlock *BB) {
Dale Johannesen7249ef02010-04-02 21:49:27 +0000632 Instruction *Start = BB->getFirstNonPHIOrDbg();
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000633 // Is this a call to eh.exception?
634 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Start))
635 if (CI->getIntrinsicID() == Intrinsic::eh_exception)
636 // Reuse the existing call.
637 return Start;
638
639 // Find the eh.exception intrinsic if we didn't already.
Bill Wendling8bedf972009-10-29 00:37:35 +0000640 if (!ExceptionValueIntrinsic)
641 ExceptionValueIntrinsic = Intrinsic::getDeclaration(F->getParent(),
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000642 Intrinsic::eh_exception);
643
644 // Create the call.
Bill Wendling8bedf972009-10-29 00:37:35 +0000645 return CallInst::Create(ExceptionValueIntrinsic, "eh.value.call", Start);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000646}
647
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000648bool DwarfEHPrepare::runOnFunction(Function &Fn) {
649 bool Changed = false;
650
651 // Initialize internal state.
Duncan Sands22efc182010-08-31 09:05:06 +0000652 DT = &getAnalysis<DominatorTree>();
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000653 F = &Fn;
654
655 // Ensure that only unwind edges end at landing pads (a landing pad is a
656 // basic block where an invoke unwind edge ends).
657 Changed |= NormalizeLandingPads();
658
659 // Turn unwind instructions into libcalls.
660 Changed |= LowerUnwinds();
661
Bill Wendling8bedf972009-10-29 00:37:35 +0000662 // TODO: Move eh.selector calls to landing pads and combine them.
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000663
664 // Move eh.exception calls to landing pads.
665 Changed |= MoveExceptionValueCalls();
666
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000667 Changed |= HandleURoRInvokes();
668
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000669 LandingPads.clear();
670
671 return Changed;
672}