Fix #include order
[oota-llvm.git] / lib / Transforms / Utils / Local.cpp
1 //===-- Local.cpp - Functions to perform local transformations ------------===//
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 family of functions perform various local transformations to the
11 // program.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Utils/Local.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Intrinsics.h"
20 #include "llvm/Analysis/ConstantFolding.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/MathExtras.h"
23 #include <cerrno>
24 #include <cmath>
25 using namespace llvm;
26
27 //===----------------------------------------------------------------------===//
28 //  Local constant propagation...
29 //
30
31 /// doConstantPropagation - If an instruction references constants, try to fold
32 /// them together...
33 ///
34 bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
35   if (Constant *C = ConstantFoldInstruction(II)) {
36     // Replaces all of the uses of a variable with uses of the constant.
37     II->replaceAllUsesWith(C);
38
39     // Remove the instruction from the basic block...
40     II = II->getParent()->getInstList().erase(II);
41     return true;
42   }
43
44   return false;
45 }
46
47 /// ConstantFoldInstruction - Attempt to constant fold the specified
48 /// instruction.  If successful, the constant result is returned, if not, null
49 /// is returned.  Note that this function can only fail when attempting to fold
50 /// instructions like loads and stores, which have no constant expression form.
51 ///
52 Constant *llvm::ConstantFoldInstruction(Instruction *I) {
53   if (PHINode *PN = dyn_cast<PHINode>(I)) {
54     if (PN->getNumIncomingValues() == 0)
55       return Constant::getNullValue(PN->getType());
56
57     Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
58     if (Result == 0) return 0;
59
60     // Handle PHI nodes specially here...
61     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
62       if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
63         return 0;   // Not all the same incoming constants...
64
65     // If we reach here, all incoming values are the same constant.
66     return Result;
67   } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
68     if (Function *F = CI->getCalledFunction())
69       if (canConstantFoldCallTo(F)) {
70         std::vector<Constant*> Args;
71         for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
72           if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i)))
73             Args.push_back(Op);
74           else
75             return 0;
76         return ConstantFoldCall(F, Args);
77       }
78     return 0;
79   }
80
81   Constant *Op0 = 0, *Op1 = 0;
82   switch (I->getNumOperands()) {
83   default:
84   case 2:
85     Op1 = dyn_cast<Constant>(I->getOperand(1));
86     if (Op1 == 0) return 0;        // Not a constant?, can't fold
87   case 1:
88     Op0 = dyn_cast<Constant>(I->getOperand(0));
89     if (Op0 == 0) return 0;        // Not a constant?, can't fold
90     break;
91   case 0: return 0;
92   }
93
94   if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
95     return ConstantExpr::get(I->getOpcode(), Op0, Op1);
96
97   switch (I->getOpcode()) {
98   default: return 0;
99   case Instruction::Cast:
100     return ConstantExpr::getCast(Op0, I->getType());
101   case Instruction::Select:
102     if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
103       return ConstantExpr::getSelect(Op0, Op1, Op2);
104     return 0;
105   case Instruction::GetElementPtr:
106     std::vector<Constant*> IdxList;
107     IdxList.reserve(I->getNumOperands()-1);
108     if (Op1) IdxList.push_back(Op1);
109     for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
110       if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
111         IdxList.push_back(C);
112       else
113         return 0;  // Non-constant operand
114     return ConstantExpr::getGetElementPtr(Op0, IdxList);
115   }
116 }
117
118 // ConstantFoldTerminator - If a terminator instruction is predicated on a
119 // constant value, convert it into an unconditional branch to the constant
120 // destination.
121 //
122 bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
123   TerminatorInst *T = BB->getTerminator();
124
125   // Branch - See if we are conditional jumping on constant
126   if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
127     if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
128     BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
129     BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
130
131     if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
132       // Are we branching on constant?
133       // YES.  Change to unconditional branch...
134       BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
135       BasicBlock *OldDest     = Cond->getValue() ? Dest2 : Dest1;
136
137       //cerr << "Function: " << T->getParent()->getParent()
138       //     << "\nRemoving branch from " << T->getParent()
139       //     << "\n\nTo: " << OldDest << endl;
140
141       // Let the basic block know that we are letting go of it.  Based on this,
142       // it will adjust it's PHI nodes.
143       assert(BI->getParent() && "Terminator not inserted in block!");
144       OldDest->removePredecessor(BI->getParent());
145
146       // Set the unconditional destination, and change the insn to be an
147       // unconditional branch.
148       BI->setUnconditionalDest(Destination);
149       return true;
150     } else if (Dest2 == Dest1) {       // Conditional branch to same location?
151       // This branch matches something like this:
152       //     br bool %cond, label %Dest, label %Dest
153       // and changes it into:  br label %Dest
154
155       // Let the basic block know that we are letting go of one copy of it.
156       assert(BI->getParent() && "Terminator not inserted in block!");
157       Dest1->removePredecessor(BI->getParent());
158
159       // Change a conditional branch to unconditional.
160       BI->setUnconditionalDest(Dest1);
161       return true;
162     }
163   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
164     // If we are switching on a constant, we can convert the switch into a
165     // single branch instruction!
166     ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
167     BasicBlock *TheOnlyDest = SI->getSuccessor(0);  // The default dest
168     BasicBlock *DefaultDest = TheOnlyDest;
169     assert(TheOnlyDest == SI->getDefaultDest() &&
170            "Default destination is not successor #0?");
171
172     // Figure out which case it goes to...
173     for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
174       // Found case matching a constant operand?
175       if (SI->getSuccessorValue(i) == CI) {
176         TheOnlyDest = SI->getSuccessor(i);
177         break;
178       }
179
180       // Check to see if this branch is going to the same place as the default
181       // dest.  If so, eliminate it as an explicit compare.
182       if (SI->getSuccessor(i) == DefaultDest) {
183         // Remove this entry...
184         DefaultDest->removePredecessor(SI->getParent());
185         SI->removeCase(i);
186         --i; --e;  // Don't skip an entry...
187         continue;
188       }
189
190       // Otherwise, check to see if the switch only branches to one destination.
191       // We do this by reseting "TheOnlyDest" to null when we find two non-equal
192       // destinations.
193       if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
194     }
195
196     if (CI && !TheOnlyDest) {
197       // Branching on a constant, but not any of the cases, go to the default
198       // successor.
199       TheOnlyDest = SI->getDefaultDest();
200     }
201
202     // If we found a single destination that we can fold the switch into, do so
203     // now.
204     if (TheOnlyDest) {
205       // Insert the new branch..
206       new BranchInst(TheOnlyDest, SI);
207       BasicBlock *BB = SI->getParent();
208
209       // Remove entries from PHI nodes which we no longer branch to...
210       for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
211         // Found case matching a constant operand?
212         BasicBlock *Succ = SI->getSuccessor(i);
213         if (Succ == TheOnlyDest)
214           TheOnlyDest = 0;  // Don't modify the first branch to TheOnlyDest
215         else
216           Succ->removePredecessor(BB);
217       }
218
219       // Delete the old switch...
220       BB->getInstList().erase(SI);
221       return true;
222     } else if (SI->getNumSuccessors() == 2) {
223       // Otherwise, we can fold this switch into a conditional branch
224       // instruction if it has only one non-default destination.
225       Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
226                                     SI->getSuccessorValue(1), "cond", SI);
227       // Insert the new branch...
228       new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
229
230       // Delete the old switch...
231       SI->getParent()->getInstList().erase(SI);
232       return true;
233     }
234   }
235   return false;
236 }
237
238 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
239 /// getelementptr constantexpr, return the constant value being addressed by the
240 /// constant expression, or null if something is funny and we can't decide.
241 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C, 
242                                                        ConstantExpr *CE) {
243   if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
244     return 0;  // Do not allow stepping over the value!
245   
246   // Loop over all of the operands, tracking down which value we are
247   // addressing...
248   gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
249   for (++I; I != E; ++I)
250     if (const StructType *STy = dyn_cast<StructType>(*I)) {
251       ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
252       assert(CU->getValue() < STy->getNumElements() &&
253              "Struct index out of range!");
254       unsigned El = (unsigned)CU->getValue();
255       if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
256         C = CS->getOperand(El);
257       } else if (isa<ConstantAggregateZero>(C)) {
258         C = Constant::getNullValue(STy->getElementType(El));
259       } else if (isa<UndefValue>(C)) {
260         C = UndefValue::get(STy->getElementType(El));
261       } else {
262         return 0;
263       }
264     } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
265       const ArrayType *ATy = cast<ArrayType>(*I);
266       if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
267       if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
268         C = CA->getOperand((unsigned)CI->getRawValue());
269       else if (isa<ConstantAggregateZero>(C))
270         C = Constant::getNullValue(ATy->getElementType());
271       else if (isa<UndefValue>(C))
272         C = UndefValue::get(ATy->getElementType());
273       else
274         return 0;
275     } else {
276       return 0;
277     }
278   return C;
279 }
280
281
282 //===----------------------------------------------------------------------===//
283 //  Local dead code elimination...
284 //
285
286 bool llvm::isInstructionTriviallyDead(Instruction *I) {
287   if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
288
289   if (!I->mayWriteToMemory()) return true;
290
291   if (CallInst *CI = dyn_cast<CallInst>(I))
292     if (Function *F = CI->getCalledFunction())
293       switch (F->getIntrinsicID()) {
294       default: break;
295       case Intrinsic::returnaddress:
296       case Intrinsic::frameaddress:
297       case Intrinsic::isunordered:
298       case Intrinsic::ctpop:
299       case Intrinsic::ctlz:
300       case Intrinsic::cttz:
301       case Intrinsic::sqrt:
302         return true;             // These intrinsics have no side effects.
303       }
304   return false;
305 }
306
307 // dceInstruction - Inspect the instruction at *BBI and figure out if it's
308 // [trivially] dead.  If so, remove the instruction and update the iterator
309 // to point to the instruction that immediately succeeded the original
310 // instruction.
311 //
312 bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
313   // Look for un"used" definitions...
314   if (isInstructionTriviallyDead(BBI)) {
315     BBI = BBI->getParent()->getInstList().erase(BBI);   // Bye bye
316     return true;
317   }
318   return false;
319 }