Fix grammar-o.
[oota-llvm.git] / lib / Transforms / Utils / LowerInvoke.cpp
1 //===- LowerInvoke.cpp - Eliminate Invoke & Unwind instructions -----------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This transformation is designed for use by code generators which do not yet
11 // support stack unwinding.  This pass supports two models of exception handling
12 // lowering, the 'cheap' support and the 'expensive' support.
13 //
14 // 'Cheap' exception handling support gives the program the ability to execute
15 // any program which does not "throw an exception", by turning 'invoke'
16 // instructions into calls and by turning 'unwind' instructions into calls to
17 // abort().  If the program does dynamically use the unwind instruction, the
18 // program will print a message then abort.
19 //
20 // 'Expensive' exception handling support gives the full exception handling
21 // support to the program at making the 'invoke' instruction really expensive.
22 // It basically inserts setjmp/longjmp calls to emulate the exception handling
23 // as necessary.
24 //
25 // Because the 'expensive' support slows down programs a lot, and EH is only
26 // used for a subset of the programs, it must be specifically enabled by an
27 // option.
28 //
29 //===----------------------------------------------------------------------===//
30
31 #include "llvm/Transforms/Scalar.h"
32 #include "llvm/Constants.h"
33 #include "llvm/DerivedTypes.h"
34 #include "llvm/Instructions.h"
35 #include "llvm/Module.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 #include "Support/Statistic.h"
39 #include "Support/CommandLine.h"
40 #include <csetjmp>
41 using namespace llvm;
42
43 namespace {
44   Statistic<> NumLowered("lowerinvoke", "Number of invoke & unwinds replaced");
45   cl::opt<bool> ExpensiveEHSupport("enable-correct-eh-support", 
46  cl::desc("Make the -lowerinvoke pass insert expensive, but correct, EH code"));
47
48   class LowerInvoke : public FunctionPass {
49     // Used for both models.
50     Function *WriteFn;
51     Function *AbortFn;
52     Value *AbortMessage;
53     unsigned AbortMessageLength;
54
55     // Used for expensive EH support.
56     const Type *JBLinkTy;
57     GlobalVariable *JBListHead;
58     Function *SetJmpFn, *LongJmpFn;
59   public:
60     bool doInitialization(Module &M);
61     bool runOnFunction(Function &F);
62   private:
63     void writeAbortMessage(Instruction *IB);
64     bool insertCheapEHSupport(Function &F);
65     bool insertExpensiveEHSupport(Function &F);
66   };
67
68   RegisterOpt<LowerInvoke>
69   X("lowerinvoke", "Lower invoke and unwind, for unwindless code generators");
70 }
71
72 // Public Interface To the LowerInvoke pass.
73 FunctionPass *llvm::createLowerInvokePass() { return new LowerInvoke(); }
74
75 // doInitialization - Make sure that there is a prototype for abort in the
76 // current module.
77 bool LowerInvoke::doInitialization(Module &M) {
78   const Type *VoidPtrTy = PointerType::get(Type::SByteTy);
79   if (ExpensiveEHSupport) {
80     // Insert a type for the linked list of jump buffers.  Unfortunately, we
81     // don't know the size of the target's setjmp buffer, so we make a guess.
82     // If this guess turns out to be too small, bad stuff could happen.
83     unsigned JmpBufSize = 200;  // PPC has 192 words
84     assert(sizeof(jmp_buf) <= JmpBufSize*sizeof(void*) &&
85        "LowerInvoke doesn't know about targets with jmp_buf size > 200 words!");
86     const Type *JmpBufTy = ArrayType::get(VoidPtrTy, JmpBufSize);
87
88     { // The type is recursive, so use a type holder.
89       std::vector<const Type*> Elements;
90       OpaqueType *OT = OpaqueType::get();
91       Elements.push_back(PointerType::get(OT));
92       Elements.push_back(JmpBufTy);
93       PATypeHolder JBLType(StructType::get(Elements));
94       OT->refineAbstractTypeTo(JBLType.get());  // Complete the cycle.
95       JBLinkTy = JBLType.get();
96     }
97
98     const Type *PtrJBList = PointerType::get(JBLinkTy);
99
100     // Now that we've done that, insert the jmpbuf list head global, unless it
101     // already exists.
102     if (!(JBListHead = M.getGlobalVariable("llvm.sjljeh.jblist", PtrJBList)))
103       JBListHead = new GlobalVariable(PtrJBList, false,
104                                       GlobalValue::LinkOnceLinkage,
105                                       Constant::getNullValue(PtrJBList),
106                                       "llvm.sjljeh.jblist", &M);
107     SetJmpFn = M.getOrInsertFunction("setjmp", Type::IntTy,
108                                      PointerType::get(JmpBufTy), 0);
109     LongJmpFn = M.getOrInsertFunction("longjmp", Type::VoidTy,
110                                       PointerType::get(JmpBufTy),
111                                       Type::IntTy, 0);
112     
113     // The abort message for expensive EH support tells the user that the
114     // program 'unwound' without an 'invoke' instruction.
115     Constant *Msg =
116       ConstantArray::get("ERROR: Exception thrown, but not caught!\n");
117     AbortMessageLength = Msg->getNumOperands()-1;  // don't include \0
118   
119     GlobalVariable *MsgGV = M.getGlobalVariable("abort.msg", Msg->getType());
120     if (MsgGV && (!MsgGV->hasInitializer() || MsgGV->getInitializer() != Msg))
121       MsgGV = 0;
122     if (!MsgGV)
123       MsgGV = new GlobalVariable(Msg->getType(), true,
124                                  GlobalValue::InternalLinkage,
125                                  Msg, "abort.msg", &M);
126     std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::LongTy));
127     AbortMessage =
128       ConstantExpr::getGetElementPtr(ConstantPointerRef::get(MsgGV), GEPIdx);
129
130   } else {
131     // The abort message for cheap EH support tells the user that EH is not
132     // enabled.
133     Constant *Msg =
134       ConstantArray::get("Exception handler needed, but not enabled.  Recompile"
135                          " program with -enable-correct-eh-support.\n");
136     AbortMessageLength = Msg->getNumOperands()-1;  // don't include \0
137   
138     GlobalVariable *MsgGV = M.getGlobalVariable("abort.msg", Msg->getType());
139     if (MsgGV && (!MsgGV->hasInitializer() || MsgGV->getInitializer() != Msg))
140       MsgGV = 0;
141
142     if (!MsgGV)
143       MsgGV = new GlobalVariable(Msg->getType(), true,
144                                  GlobalValue::InternalLinkage,
145                                  Msg, "abort.msg", &M);
146     std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::LongTy));
147     AbortMessage =
148       ConstantExpr::getGetElementPtr(ConstantPointerRef::get(MsgGV), GEPIdx);
149   }
150
151   // We need the 'write' and 'abort' functions for both models.
152   AbortFn = M.getOrInsertFunction("abort", Type::VoidTy, 0);
153
154   // Unfortunately, 'write' can end up being prototyped in several different
155   // ways.  If the user defines a three (or more) operand function named 'write'
156   // we will use their prototype.  We _do not_ want to insert another instance
157   // of a write prototype, because we don't know that the funcresolve pass will
158   // run after us.  If there is a definition of a write function, but it's not
159   // suitable for our uses, we just don't emit write calls.  If there is no
160   // write prototype at all, we just add one.
161   if (Function *WF = M.getNamedFunction("write")) {
162     if (WF->getFunctionType()->getNumParams() > 3 ||
163         WF->getFunctionType()->isVarArg())
164       WriteFn = WF;
165     else
166       WriteFn = 0;
167   } else {
168     WriteFn = M.getOrInsertFunction("write", Type::VoidTy, Type::IntTy,
169                                     VoidPtrTy, Type::IntTy, 0);
170   }
171   return true;
172 }
173
174 void LowerInvoke::writeAbortMessage(Instruction *IB) {
175   if (WriteFn) {
176     // These are the arguments we WANT...
177     std::vector<Value*> Args;
178     Args.push_back(ConstantInt::get(Type::IntTy, 2));
179     Args.push_back(AbortMessage);
180     Args.push_back(ConstantInt::get(Type::IntTy, AbortMessageLength));
181
182     // If the actual declaration of write disagrees, insert casts as
183     // appropriate.
184     const FunctionType *FT = WriteFn->getFunctionType();
185     unsigned NumArgs = FT->getNumParams();
186     for (unsigned i = 0; i != 3; ++i)
187       if (i < NumArgs && FT->getParamType(i) != Args[i]->getType())
188         Args[i] = ConstantExpr::getCast(cast<Constant>(Args[i]), 
189                                         FT->getParamType(i));
190
191     new CallInst(WriteFn, Args, "", IB);
192   }
193 }
194
195 bool LowerInvoke::insertCheapEHSupport(Function &F) {
196   bool Changed = false;
197   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
198     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
199       // Insert a normal call instruction...
200       std::string Name = II->getName(); II->setName("");
201       Value *NewCall = new CallInst(II->getCalledValue(),
202                                     std::vector<Value*>(II->op_begin()+3,
203                                                         II->op_end()), Name,II);
204       II->replaceAllUsesWith(NewCall);
205       
206       // Insert an unconditional branch to the normal destination.
207       new BranchInst(II->getNormalDest(), II);
208
209       // Remove any PHI node entries from the exception destination.
210       II->getUnwindDest()->removePredecessor(BB);
211
212       // Remove the invoke instruction now.
213       BB->getInstList().erase(II);
214
215       ++NumLowered; Changed = true;
216     } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
217       // Insert a new call to write(2, AbortMessage, AbortMessageLength);
218       writeAbortMessage(UI);
219
220       // Insert a call to abort()
221       new CallInst(AbortFn, std::vector<Value*>(), "", UI);
222
223       // Insert a return instruction.  This really should be a "barrier", as it
224       // is unreachable.
225       new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
226                             Constant::getNullValue(F.getReturnType()), UI);
227
228       // Remove the unwind instruction now.
229       BB->getInstList().erase(UI);
230
231       ++NumLowered; Changed = true;
232     }
233   return Changed;
234 }
235
236 bool LowerInvoke::insertExpensiveEHSupport(Function &F) {
237   bool Changed = false;
238
239   // If a function uses invoke, we have an alloca for the jump buffer.
240   AllocaInst *JmpBuf = 0;
241
242   // If this function contains an unwind instruction, two blocks get added: one
243   // to actually perform the longjmp, and one to terminate the program if there
244   // is no handler.
245   BasicBlock *UnwindBlock = 0, *TermBlock = 0;
246   std::vector<LoadInst*> JBPtrs;
247
248   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
249     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
250       if (JmpBuf == 0)
251         JmpBuf = new AllocaInst(JBLinkTy, 0, "jblink", F.begin()->begin());
252
253       // On the entry to the invoke, we must install our JmpBuf as the top of
254       // the stack.
255       LoadInst *OldEntry = new LoadInst(JBListHead, "oldehlist", II);
256
257       // Store this old value as our 'next' field, and store our alloca as the
258       // current jblist.
259       std::vector<Value*> Idx;
260       Idx.push_back(Constant::getNullValue(Type::LongTy));
261       Idx.push_back(ConstantUInt::get(Type::UByteTy, 0));
262       Value *NextFieldPtr = new GetElementPtrInst(JmpBuf, Idx, "NextField", II);
263       new StoreInst(OldEntry, NextFieldPtr, II);
264       new StoreInst(JmpBuf, JBListHead, II);
265       
266       // Call setjmp, passing in the address of the jmpbuffer.
267       Idx[1] = ConstantUInt::get(Type::UByteTy, 1);
268       Value *JmpBufPtr = new GetElementPtrInst(JmpBuf, Idx, "TheJmpBuf", II);
269       Value *SJRet = new CallInst(SetJmpFn, JmpBufPtr, "sjret", II);
270
271       // Compare the return value to zero.
272       Value *IsNormal = BinaryOperator::create(Instruction::SetEQ, SJRet,
273                                        Constant::getNullValue(SJRet->getType()),
274                                                "notunwind", II);
275       // Create the receiver block if there is a critical edge to the normal
276       // destination.
277       SplitCriticalEdge(II, 0, this);
278       Instruction *InsertLoc = II->getNormalDest()->begin();
279       
280       // Insert a normal call instruction on the normal execution path.
281       std::string Name = II->getName(); II->setName("");
282       Value *NewCall = new CallInst(II->getCalledValue(),
283                                     std::vector<Value*>(II->op_begin()+3,
284                                                         II->op_end()), Name,
285                                     InsertLoc);
286       II->replaceAllUsesWith(NewCall);
287       
288       // If we got this far, then no exception was thrown and we can pop our
289       // jmpbuf entry off.
290       new StoreInst(OldEntry, JBListHead, InsertLoc);
291
292       // Now we change the invoke into a branch instruction.
293       new BranchInst(II->getNormalDest(), II->getUnwindDest(), IsNormal, II);
294
295       // Remove the InvokeInst now.
296       BB->getInstList().erase(II);
297       ++NumLowered; Changed = true;      
298       
299     } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
300       if (UnwindBlock == 0) {
301         // Create two new blocks, the unwind block and the terminate block.  Add
302         // them at the end of the function because they are not hot.
303         UnwindBlock = new BasicBlock("unwind", &F);
304         TermBlock = new BasicBlock("unwinderror", &F);
305
306         // Insert return instructions.  These really should be "barrier"s, as
307         // they are unreachable.
308         new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
309                        Constant::getNullValue(F.getReturnType()), UnwindBlock);
310         new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
311                        Constant::getNullValue(F.getReturnType()), TermBlock);
312       }
313
314       // Load the JBList, if it's null, then there was no catch!
315       LoadInst *Ptr = new LoadInst(JBListHead, "ehlist", UI);
316       Value *NotNull = BinaryOperator::create(Instruction::SetNE, Ptr,
317                                         Constant::getNullValue(Ptr->getType()),
318                                               "notnull", UI);
319       new BranchInst(UnwindBlock, TermBlock, NotNull, UI);
320
321       // Remember the loaded value so we can insert the PHI node as needed.
322       JBPtrs.push_back(Ptr);
323
324       // Remove the UnwindInst now.
325       BB->getInstList().erase(UI);
326       ++NumLowered; Changed = true;      
327     }
328
329   // If an unwind instruction was inserted, we need to set up the Unwind and
330   // term blocks.
331   if (UnwindBlock) {
332     // In the unwind block, we know that the pointer coming in on the JBPtrs
333     // list are non-null.
334     Instruction *RI = UnwindBlock->getTerminator();
335
336     Value *RecPtr;
337     if (JBPtrs.size() == 1)
338       RecPtr = JBPtrs[0];
339     else {
340       // If there is more than one unwind in this function, make a PHI node to
341       // merge in all of the loaded values.
342       PHINode *PN = new PHINode(JBPtrs[0]->getType(), "jbptrs", RI);
343       for (unsigned i = 0, e = JBPtrs.size(); i != e; ++i)
344         PN->addIncoming(JBPtrs[i], JBPtrs[i]->getParent());
345       RecPtr = PN;
346     }
347
348     // Now that we have a pointer to the whole record, remove the entry from the
349     // JBList.
350     std::vector<Value*> Idx;
351     Idx.push_back(Constant::getNullValue(Type::LongTy));
352     Idx.push_back(ConstantUInt::get(Type::UByteTy, 0));
353     Value *NextFieldPtr = new GetElementPtrInst(RecPtr, Idx, "NextField", RI);
354     Value *NextRec = new LoadInst(NextFieldPtr, "NextRecord", RI);
355     new StoreInst(NextRec, JBListHead, RI);
356
357     // Now that we popped the top of the JBList, get a pointer to the jmpbuf and
358     // longjmp.
359     Idx[1] = ConstantUInt::get(Type::UByteTy, 1);
360     Idx[0] = new GetElementPtrInst(RecPtr, Idx, "JmpBuf", RI);
361     Idx[1] = ConstantInt::get(Type::IntTy, 1);
362     new CallInst(LongJmpFn, Idx, "", RI);
363
364     // Now we set up the terminate block.
365     RI = TermBlock->getTerminator();
366     
367     // Insert a new call to write(2, AbortMessage, AbortMessageLength);
368     writeAbortMessage(RI);
369
370     // Insert a call to abort()
371     new CallInst(AbortFn, std::vector<Value*>(), "", RI);
372   }
373
374   return Changed;
375 }
376
377 bool LowerInvoke::runOnFunction(Function &F) {
378   if (ExpensiveEHSupport)
379     return insertExpensiveEHSupport(F);
380   else
381     return insertCheapEHSupport(F);
382 }