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