blob: 34b1a396bb721e706e5b8c8b68b3f7e8ad55d129 [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.
Jay Foad3ecfc862011-03-30 11:28:46 +0000442 PHINode *NewPN = PHINode::Create(PN->getType(),
443 PN->getNumIncomingValues(),
444 PN->getName()+".unwind", NewBB);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000445 // 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
Duncan Sands22efc182010-08-31 09:05:06 +0000465 // Now update DominatorTree analysis information.
466 DT->splitBlock(NewBB);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000467
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() {
Bill Wendling43488712009-09-14 20:52:37 +0000484 SmallVector<TerminatorInst*, 16> UnwindInsts;
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000485
486 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
487 TerminatorInst *TI = I->getTerminator();
Bill Wendling43488712009-09-14 20:52:37 +0000488 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) {
Bill Wendling8bedf972009-10-29 00:37:35 +0000496 LLVMContext &Ctx = UnwindInsts[0]->getContext();
Bill Wendling43488712009-09-14 20:52:37 +0000497 std::vector<const Type*>
Bill Wendling8bedf972009-10-29 00:37:35 +0000498 Params(1, Type::getInt8PtrTy(Ctx));
499 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
Bill Wendling43488712009-09-14 20:52:37 +0000500 Params, false);
501 const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
502 RewindFunction = F->getParent()->getOrInsertFunction(RewindName, FTy);
503 }
504
Bill Wendling8bedf972009-10-29 00:37:35 +0000505 bool Changed = false;
506
Bill Wendling43488712009-09-14 20:52:37 +0000507 for (SmallVectorImpl<TerminatorInst*>::iterator
508 I = UnwindInsts.begin(), E = UnwindInsts.end(); I != E; ++I) {
509 TerminatorInst *TI = *I;
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000510
511 // Replace the unwind instruction with a call to _Unwind_Resume (or the
512 // appropriate target equivalent) followed by an UnreachableInst.
513
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000514 // Create the call...
Eric Christopher82f149d2009-09-04 01:14:14 +0000515 CallInst *CI = CallInst::Create(RewindFunction,
Duncan Sands850fcd42010-09-03 08:31:48 +0000516 CreateExceptionValueCall(TI->getParent()),
Bill Wendling43488712009-09-14 20:52:37 +0000517 "", TI);
Eric Christopher82f149d2009-09-04 01:14:14 +0000518 CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000519 // ...followed by an UnreachableInst.
Bill Wendling8bedf972009-10-29 00:37:35 +0000520 new UnreachableInst(TI->getContext(), TI);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000521
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
Duncan Sands850fcd42010-09-03 08:31:48 +0000532/// 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).
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000537bool 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.
Bill Wendling8bedf972009-10-29 00:37:35 +0000540 if (!ExceptionValueIntrinsic &&
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000541 !F->getParent()->getFunction(Intrinsic::getName(Intrinsic::eh_exception)))
542 return false;
543
544 bool Changed = false;
545
Duncan Sands850fcd42010-09-03 08:31:48 +0000546 // 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();
Eric Christopheradc581f2010-09-01 17:29:10 +0000549 LI != LE; ++LI) {
Duncan Sands850fcd42010-09-03 08:31:48 +0000550 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 }
Duncan Sandsfb4e8ab2010-09-01 14:07:47 +0000569 }
570
Duncan Sands850fcd42010-09-03 08:31:48 +0000571 // 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;
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000627}
628
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000629/// 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) {
Dale Johannesen7249ef02010-04-02 21:49:27 +0000633 Instruction *Start = BB->getFirstNonPHIOrDbg();
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000634 // 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.
Bill Wendling8bedf972009-10-29 00:37:35 +0000641 if (!ExceptionValueIntrinsic)
642 ExceptionValueIntrinsic = Intrinsic::getDeclaration(F->getParent(),
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000643 Intrinsic::eh_exception);
644
645 // Create the call.
Bill Wendling8bedf972009-10-29 00:37:35 +0000646 return CallInst::Create(ExceptionValueIntrinsic, "eh.value.call", Start);
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000647}
648
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000649bool DwarfEHPrepare::runOnFunction(Function &Fn) {
650 bool Changed = false;
651
652 // Initialize internal state.
Duncan Sands22efc182010-08-31 09:05:06 +0000653 DT = &getAnalysis<DominatorTree>();
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000654 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
Bill Wendling8bedf972009-10-29 00:37:35 +0000663 // TODO: Move eh.selector calls to landing pads and combine them.
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000664
665 // Move eh.exception calls to landing pads.
666 Changed |= MoveExceptionValueCalls();
667
Bill Wendling2ad4aca2010-03-26 23:41:30 +0000668 Changed |= HandleURoRInvokes();
669
Duncan Sandsb0f1e172009-05-22 20:36:31 +0000670 LandingPads.clear();
671
672 return Changed;
673}