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