SjLjEHPrepare.cpp revision b58a59b3c1563ab5bd7225748e32933bf6d76c03
1//===- SjLjEHPass.cpp - Eliminate Invoke & Unwind instructions -----------===//
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 transformation is designed for use by code generators which use SjLj
11// based exception handling.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "sjljehprepare"
16#include "llvm/Transforms/Scalar.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Instructions.h"
20#include "llvm/Intrinsics.h"
21#include "llvm/LLVMContext.h"
22#include "llvm/Module.h"
23#include "llvm/Pass.h"
24#include "llvm/CodeGen/Passes.h"
25#include "llvm/Transforms/Utils/BasicBlockUtils.h"
26#include "llvm/Transforms/Utils/Local.h"
27#include "llvm/ADT/Statistic.h"
28#include "llvm/ADT/SmallVector.h"
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/raw_ostream.h"
32#include "llvm/Target/TargetLowering.h"
33using namespace llvm;
34
35STATISTIC(NumInvokes, "Number of invokes replaced");
36STATISTIC(NumUnwinds, "Number of unwinds replaced");
37STATISTIC(NumSpilled, "Number of registers live across unwind edges");
38
39namespace {
40  class SjLjEHPass : public FunctionPass {
41
42    const TargetLowering *TLI;
43
44    const Type *FunctionContextTy;
45    Constant *RegisterFn;
46    Constant *UnregisterFn;
47    Constant *BuiltinSetjmpFn;
48    Constant *FrameAddrFn;
49    Constant *LSDAAddrFn;
50    Value *PersonalityFn;
51    Constant *SelectorFn;
52    Constant *ExceptionFn;
53    Constant *CallSiteFn;
54
55    Value *CallSite;
56  public:
57    static char ID; // Pass identification, replacement for typeid
58    explicit SjLjEHPass(const TargetLowering *tli = NULL)
59      : FunctionPass(&ID), TLI(tli) { }
60    bool doInitialization(Module &M);
61    bool runOnFunction(Function &F);
62
63    virtual void getAnalysisUsage(AnalysisUsage &AU) const { }
64    const char *getPassName() const {
65      return "SJLJ Exception Handling preparation";
66    }
67
68  private:
69    void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
70    void markInvokeCallSite(InvokeInst *II, int InvokeNo, Value *CallSite,
71                            SwitchInst *CatchSwitch);
72    void splitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
73    bool insertSjLjEHSupport(Function &F);
74  };
75} // end anonymous namespace
76
77char SjLjEHPass::ID = 0;
78
79// Public Interface To the SjLjEHPass pass.
80FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
81  return new SjLjEHPass(TLI);
82}
83// doInitialization - Set up decalarations and types needed to process
84// exceptions.
85bool SjLjEHPass::doInitialization(Module &M) {
86  // Build the function context structure.
87  // builtin_setjmp uses a five word jbuf
88  const Type *VoidPtrTy =
89          Type::getInt8PtrTy(M.getContext());
90  const Type *Int32Ty = Type::getInt32Ty(M.getContext());
91  FunctionContextTy =
92    StructType::get(M.getContext(),
93                    VoidPtrTy,                        // __prev
94                    Int32Ty,                          // call_site
95                    ArrayType::get(Int32Ty, 4),       // __data
96                    VoidPtrTy,                        // __personality
97                    VoidPtrTy,                        // __lsda
98                    ArrayType::get(VoidPtrTy, 5),     // __jbuf
99                    NULL);
100  RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
101                                     Type::getVoidTy(M.getContext()),
102                                     PointerType::getUnqual(FunctionContextTy),
103                                     (Type *)0);
104  UnregisterFn =
105    M.getOrInsertFunction("_Unwind_SjLj_Unregister",
106                          Type::getVoidTy(M.getContext()),
107                          PointerType::getUnqual(FunctionContextTy),
108                          (Type *)0);
109  FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
110  BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
111  LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
112  SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
113  ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
114  CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
115  PersonalityFn = 0;
116
117  return true;
118}
119
120/// insertCallSiteStore - Insert a store of the call-site value to the
121/// function context
122void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
123                                     Value *CallSite) {
124  ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
125                                              Number);
126  // Insert a store of the call-site number
127  new StoreInst(CallSiteNoC, CallSite, true, I);  // volatile
128}
129
130/// markInvokeCallSite - Insert code to mark the call_site for this invoke
131void SjLjEHPass::markInvokeCallSite(InvokeInst *II, int InvokeNo,
132                                    Value *CallSite,
133                                    SwitchInst *CatchSwitch) {
134  ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
135                                              InvokeNo);
136  // The runtime comes back to the dispatcher with the call_site - 1 in
137  // the context. Odd, but there it is.
138  ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
139                                            InvokeNo - 1);
140
141  // If the unwind edge has phi nodes, split the edge.
142  if (isa<PHINode>(II->getUnwindDest()->begin())) {
143    SplitCriticalEdge(II, 1, this);
144
145    // If there are any phi nodes left, they must have a single predecessor.
146    while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
147      PN->replaceAllUsesWith(PN->getIncomingValue(0));
148      PN->eraseFromParent();
149    }
150  }
151
152  // Insert the store of the call site value
153  insertCallSiteStore(II, InvokeNo, CallSite);
154
155  // Record the call site value for the back end so it stays associated with
156  // the invoke.
157  CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
158
159  // Add a switch case to our unwind block.
160  CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
161  // We still want this to look like an invoke so we emit the LSDA properly,
162  // so we don't transform the invoke into a call here.
163}
164
165/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
166/// we reach blocks we've already seen.
167static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
168  if (!LiveBBs.insert(BB).second) return; // already been here.
169
170  for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
171    MarkBlocksLiveIn(*PI, LiveBBs);
172}
173
174/// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
175/// we spill into a stack location, guaranteeing that there is nothing live
176/// across the unwind edge.  This process also splits all critical edges
177/// coming out of invoke's.
178void SjLjEHPass::
179splitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
180  // First step, split all critical edges from invoke instructions.
181  for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
182    InvokeInst *II = Invokes[i];
183    SplitCriticalEdge(II, 0, this);
184    SplitCriticalEdge(II, 1, this);
185    assert(!isa<PHINode>(II->getNormalDest()) &&
186           !isa<PHINode>(II->getUnwindDest()) &&
187           "critical edge splitting left single entry phi nodes?");
188  }
189
190  Function *F = Invokes.back()->getParent()->getParent();
191
192  // To avoid having to handle incoming arguments specially, we lower each arg
193  // to a copy instruction in the entry block.  This ensures that the argument
194  // value itself cannot be live across the entry block.
195  BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
196  while (isa<AllocaInst>(AfterAllocaInsertPt) &&
197        isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
198    ++AfterAllocaInsertPt;
199  for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
200       AI != E; ++AI) {
201    // This is always a no-op cast because we're casting AI to AI->getType() so
202    // src and destination types are identical. BitCast is the only possibility.
203    CastInst *NC = new BitCastInst(
204      AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
205    AI->replaceAllUsesWith(NC);
206    // Normally its is forbidden to replace a CastInst's operand because it
207    // could cause the opcode to reflect an illegal conversion. However, we're
208    // replacing it here with the same value it was constructed with to simply
209    // make NC its user.
210    NC->setOperand(0, AI);
211  }
212
213  // Finally, scan the code looking for instructions with bad live ranges.
214  for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
215    for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
216      // Ignore obvious cases we don't have to handle.  In particular, most
217      // instructions either have no uses or only have a single use inside the
218      // current block.  Ignore them quickly.
219      Instruction *Inst = II;
220      if (Inst->use_empty()) continue;
221      if (Inst->hasOneUse() &&
222          cast<Instruction>(Inst->use_back())->getParent() == BB &&
223          !isa<PHINode>(Inst->use_back())) continue;
224
225      // If this is an alloca in the entry block, it's not a real register
226      // value.
227      if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
228        if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
229          continue;
230
231      // Avoid iterator invalidation by copying users to a temporary vector.
232      SmallVector<Instruction*,16> Users;
233      for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
234           UI != E; ++UI) {
235        Instruction *User = cast<Instruction>(*UI);
236        if (User->getParent() != BB || isa<PHINode>(User))
237          Users.push_back(User);
238      }
239
240      // Find all of the blocks that this value is live in.
241      std::set<BasicBlock*> LiveBBs;
242      LiveBBs.insert(Inst->getParent());
243      while (!Users.empty()) {
244        Instruction *U = Users.back();
245        Users.pop_back();
246
247        if (!isa<PHINode>(U)) {
248          MarkBlocksLiveIn(U->getParent(), LiveBBs);
249        } else {
250          // Uses for a PHI node occur in their predecessor block.
251          PHINode *PN = cast<PHINode>(U);
252          for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
253            if (PN->getIncomingValue(i) == Inst)
254              MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
255        }
256      }
257
258      // Now that we know all of the blocks that this thing is live in, see if
259      // it includes any of the unwind locations.
260      bool NeedsSpill = false;
261      for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
262        BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
263        if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
264          NeedsSpill = true;
265        }
266      }
267
268      // If we decided we need a spill, do it.
269      if (NeedsSpill) {
270        ++NumSpilled;
271        DemoteRegToStack(*Inst, true);
272      }
273    }
274}
275
276bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
277  SmallVector<ReturnInst*,16> Returns;
278  SmallVector<UnwindInst*,16> Unwinds;
279  SmallVector<InvokeInst*,16> Invokes;
280
281  // Look through the terminators of the basic blocks to find invokes, returns
282  // and unwinds.
283  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
284    if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
285      // Remember all return instructions in case we insert an invoke into this
286      // function.
287      Returns.push_back(RI);
288    } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
289      Invokes.push_back(II);
290    } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
291      Unwinds.push_back(UI);
292    }
293  }
294  // If we don't have any invokes or unwinds, there's nothing to do.
295  if (Unwinds.empty() && Invokes.empty()) return false;
296
297  // Find the eh.selector.*  and eh.exception calls. We'll use the first
298  // eh.selector to determine the right personality function to use. For
299  // SJLJ, we always use the same personality for the whole function,
300  // not on a per-selector basis.
301  // FIXME: That's a bit ugly. Better way?
302  SmallVector<CallInst*,16> EH_Selectors;
303  SmallVector<CallInst*,16> EH_Exceptions;
304  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
305    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
306      if (CallInst *CI = dyn_cast<CallInst>(I)) {
307        if (CI->getCalledFunction() == SelectorFn) {
308          if (!PersonalityFn) PersonalityFn = CI->getOperand(2);
309          EH_Selectors.push_back(CI);
310        } else if (CI->getCalledFunction() == ExceptionFn) {
311          EH_Exceptions.push_back(CI);
312        }
313      }
314    }
315  }
316  // If we don't have any eh.selector calls, we can't determine the personality
317  // function. Without a personality function, we can't process exceptions.
318  if (!PersonalityFn) return false;
319
320  NumInvokes += Invokes.size();
321  NumUnwinds += Unwinds.size();
322
323  if (!Invokes.empty()) {
324    // We have invokes, so we need to add register/unregister calls to get
325    // this function onto the global unwind stack.
326    //
327    // First thing we need to do is scan the whole function for values that are
328    // live across unwind edges.  Each value that is live across an unwind edge
329    // we spill into a stack location, guaranteeing that there is nothing live
330    // across the unwind edge.  This process also splits all critical edges
331    // coming out of invoke's.
332    splitLiveRangesLiveAcrossInvokes(Invokes);
333
334    BasicBlock *EntryBB = F.begin();
335    // Create an alloca for the incoming jump buffer ptr and the new jump buffer
336    // that needs to be restored on all exits from the function.  This is an
337    // alloca because the value needs to be added to the global context list.
338    unsigned Align = 4; // FIXME: Should be a TLI check?
339    AllocaInst *FunctionContext =
340      new AllocaInst(FunctionContextTy, 0, Align,
341                     "fcn_context", F.begin()->begin());
342
343    Value *Idxs[2];
344    const Type *Int32Ty = Type::getInt32Ty(F.getContext());
345    Value *Zero = ConstantInt::get(Int32Ty, 0);
346    // We need to also keep around a reference to the call_site field
347    Idxs[0] = Zero;
348    Idxs[1] = ConstantInt::get(Int32Ty, 1);
349    CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
350                                         "call_site",
351                                         EntryBB->getTerminator());
352
353    // The exception selector comes back in context->data[1]
354    Idxs[1] = ConstantInt::get(Int32Ty, 2);
355    Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
356                                              "fc_data",
357                                              EntryBB->getTerminator());
358    Idxs[1] = ConstantInt::get(Int32Ty, 1);
359    Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
360                                                    "exc_selector_gep",
361                                                    EntryBB->getTerminator());
362    // The exception value comes back in context->data[0]
363    Idxs[1] = Zero;
364    Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
365                                                     "exception_gep",
366                                                     EntryBB->getTerminator());
367
368    // The result of the eh.selector call will be replaced with a
369    // a reference to the selector value returned in the function
370    // context. We leave the selector itself so the EH analysis later
371    // can use it.
372    for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
373      CallInst *I = EH_Selectors[i];
374      Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
375      I->replaceAllUsesWith(SelectorVal);
376    }
377    // eh.exception calls are replaced with references to the proper
378    // location in the context. Unlike eh.selector, the eh.exception
379    // calls are removed entirely.
380    for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
381      CallInst *I = EH_Exceptions[i];
382      // Possible for there to be duplicates, so check to make sure
383      // the instruction hasn't already been removed.
384      if (!I->getParent()) continue;
385      Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
386      const Type *Ty = Type::getInt8PtrTy(F.getContext());
387      Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
388
389      I->replaceAllUsesWith(Val);
390      I->eraseFromParent();
391    }
392
393    // The entry block changes to have the eh.sjlj.setjmp, with a conditional
394    // branch to a dispatch block for non-zero returns. If we return normally,
395    // we're not handling an exception and just register the function context
396    // and continue.
397
398    // Create the dispatch block.  The dispatch block is basically a big switch
399    // statement that goes to all of the invoke landing pads.
400    BasicBlock *DispatchBlock =
401            BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
402
403    // Insert a load in the Catch block, and a switch on its value.  By default,
404    // we go to a block that just does an unwind (which is the correct action
405    // for a standard call).
406    BasicBlock *UnwindBlock =
407      BasicBlock::Create(F.getContext(), "unwindbb", &F);
408    Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBlock));
409
410    Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
411                                       DispatchBlock);
412    SwitchInst *DispatchSwitch =
413      SwitchInst::Create(DispatchLoad, UnwindBlock, Invokes.size(),
414                         DispatchBlock);
415    // Split the entry block to insert the conditional branch for the setjmp.
416    BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
417                                                     "eh.sjlj.setjmp.cont");
418
419    // Populate the Function Context
420    //   1. LSDA address
421    //   2. Personality function address
422    //   3. jmpbuf (save FP and call eh.sjlj.setjmp)
423
424    // LSDA address
425    Idxs[0] = Zero;
426    Idxs[1] = ConstantInt::get(Int32Ty, 4);
427    Value *LSDAFieldPtr =
428      GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
429                                "lsda_gep",
430                                EntryBB->getTerminator());
431    Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
432                                   EntryBB->getTerminator());
433    new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
434
435    Idxs[1] = ConstantInt::get(Int32Ty, 3);
436    Value *PersonalityFieldPtr =
437      GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
438                                "lsda_gep",
439                                EntryBB->getTerminator());
440    new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
441                  EntryBB->getTerminator());
442
443    //   Save the frame pointer.
444    Idxs[1] = ConstantInt::get(Int32Ty, 5);
445    Value *FieldPtr
446      = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
447                                  "jbuf_gep",
448                                  EntryBB->getTerminator());
449    Idxs[1] = ConstantInt::get(Int32Ty, 0);
450    Value *ElemPtr =
451      GetElementPtrInst::Create(FieldPtr, Idxs, Idxs+2, "jbuf_fp_gep",
452                                EntryBB->getTerminator());
453
454    Value *Val = CallInst::Create(FrameAddrFn,
455                                  ConstantInt::get(Int32Ty, 0),
456                                  "fp",
457                                  EntryBB->getTerminator());
458    new StoreInst(Val, ElemPtr, true, EntryBB->getTerminator());
459    // Call the setjmp instrinsic. It fills in the rest of the jmpbuf
460    Value *SetjmpArg =
461      CastInst::Create(Instruction::BitCast, FieldPtr,
462                       Type::getInt8PtrTy(F.getContext()), "",
463                       EntryBB->getTerminator());
464    Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
465                                          "dispatch",
466                                          EntryBB->getTerminator());
467    // check the return value of the setjmp. non-zero goes to dispatcher
468    Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
469                                   ICmpInst::ICMP_EQ, DispatchVal, Zero,
470                                   "notunwind");
471    // Nuke the uncond branch.
472    EntryBB->getTerminator()->eraseFromParent();
473
474    // Put in a new condbranch in its place.
475    BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
476
477    // Register the function context and make sure it's known to not throw
478    CallInst *Register =
479      CallInst::Create(RegisterFn, FunctionContext, "",
480                       ContBlock->getTerminator());
481    Register->setDoesNotThrow();
482
483    // At this point, we are all set up, update the invoke instructions
484    // to mark their call_site values, and fill in the dispatch switch
485    // accordingly.
486    for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
487      markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
488
489    // Mark call instructions that aren't nounwind as no-action
490    // (call_site == -1). Skip the entry block, as prior to then, no function
491    // context has been created for this function and any unexpected exceptions
492    // thrown will go directly to the caller's context, which is what we want
493    // anyway, so no need to do anything here.
494    for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
495      for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
496        if (CallInst *CI = dyn_cast<CallInst>(I)) {
497          // Ignore calls to the EH builtins (eh.selector, eh.exception)
498          Constant *Callee = CI->getCalledFunction();
499          if (Callee != SelectorFn && Callee != ExceptionFn
500              && !CI->doesNotThrow())
501            insertCallSiteStore(CI, -1, CallSite);
502        }
503    }
504
505    // Replace all unwinds with a branch to the unwind handler.
506    // ??? Should this ever happen with sjlj exceptions?
507    for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
508      BranchInst::Create(UnwindBlock, Unwinds[i]);
509      Unwinds[i]->eraseFromParent();
510    }
511
512    // Finally, for any returns from this function, if this function contains an
513    // invoke, add a call to unregister the function context.
514    for (unsigned i = 0, e = Returns.size(); i != e; ++i)
515      CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
516  }
517
518  return true;
519}
520
521bool SjLjEHPass::runOnFunction(Function &F) {
522  bool Res = insertSjLjEHSupport(F);
523  return Res;
524}
525