Clean up #includes
[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/Instructions.h"
18 using namespace llvm;
19
20 //===----------------------------------------------------------------------===//
21 //  Local constant propagation...
22 //
23
24 /// doConstantPropagation - If an instruction references constants, try to fold
25 /// them together...
26 ///
27 bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
28   if (Constant *C = ConstantFoldInstruction(II)) {
29     // Replaces all of the uses of a variable with uses of the constant.
30     II->replaceAllUsesWith(C);
31     
32     // Remove the instruction from the basic block...
33     II = II->getParent()->getInstList().erase(II);
34     return true;
35   }
36
37   return false;
38 }
39
40 /// ConstantFoldInstruction - Attempt to constant fold the specified
41 /// instruction.  If successful, the constant result is returned, if not, null
42 /// is returned.  Note that this function can only fail when attempting to fold
43 /// instructions like loads and stores, which have no constant expression form.
44 ///
45 Constant *llvm::ConstantFoldInstruction(Instruction *I) {
46   if (PHINode *PN = dyn_cast<PHINode>(I)) {
47     if (PN->getNumIncomingValues() == 0)
48       return Constant::getNullValue(PN->getType());
49     
50     Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
51     if (Result == 0) return 0;
52
53     // Handle PHI nodes specially here...
54     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
55       if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
56         return 0;   // Not all the same incoming constants...
57     
58     // If we reach here, all incoming values are the same constant.
59     return Result;
60   }
61
62   Constant *Op0 = 0, *Op1 = 0;
63   switch (I->getNumOperands()) {
64   default:
65   case 2:
66     Op1 = dyn_cast<Constant>(I->getOperand(1));
67     if (Op1 == 0) return 0;        // Not a constant?, can't fold
68   case 1:
69     Op0 = dyn_cast<Constant>(I->getOperand(0));
70     if (Op0 == 0) return 0;        // Not a constant?, can't fold
71     break;
72   case 0: return 0;
73   }
74
75   if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
76     return ConstantExpr::get(I->getOpcode(), Op0, Op1);    
77
78   switch (I->getOpcode()) {
79   default: return 0;
80   case Instruction::Cast:
81     return ConstantExpr::getCast(Op0, I->getType());
82   case Instruction::GetElementPtr:
83     std::vector<Constant*> IdxList;
84     IdxList.reserve(I->getNumOperands()-1);
85     if (Op1) IdxList.push_back(Op1);
86     for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
87       if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
88         IdxList.push_back(C);
89       else
90         return 0;  // Non-constant operand
91     return ConstantExpr::getGetElementPtr(Op0, IdxList);
92   }
93 }
94
95 // ConstantFoldTerminator - If a terminator instruction is predicated on a
96 // constant value, convert it into an unconditional branch to the constant
97 // destination.
98 //
99 bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
100   TerminatorInst *T = BB->getTerminator();
101       
102   // Branch - See if we are conditional jumping on constant
103   if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
104     if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
105     BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
106     BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
107
108     if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
109       // Are we branching on constant?
110       // YES.  Change to unconditional branch...
111       BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
112       BasicBlock *OldDest     = Cond->getValue() ? Dest2 : Dest1;
113
114       //cerr << "Function: " << T->getParent()->getParent() 
115       //     << "\nRemoving branch from " << T->getParent() 
116       //     << "\n\nTo: " << OldDest << endl;
117
118       // Let the basic block know that we are letting go of it.  Based on this,
119       // it will adjust it's PHI nodes.
120       assert(BI->getParent() && "Terminator not inserted in block!");
121       OldDest->removePredecessor(BI->getParent());
122
123       // Set the unconditional destination, and change the insn to be an
124       // unconditional branch.
125       BI->setUnconditionalDest(Destination);
126       return true;
127     } else if (Dest2 == Dest1) {       // Conditional branch to same location?
128       // This branch matches something like this:  
129       //     br bool %cond, label %Dest, label %Dest
130       // and changes it into:  br label %Dest
131
132       // Let the basic block know that we are letting go of one copy of it.
133       assert(BI->getParent() && "Terminator not inserted in block!");
134       Dest1->removePredecessor(BI->getParent());
135
136       // Change a conditional branch to unconditional.
137       BI->setUnconditionalDest(Dest1);
138       return true;
139     }
140   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
141     // If we are switching on a constant, we can convert the switch into a
142     // single branch instruction!
143     ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
144     BasicBlock *TheOnlyDest = SI->getSuccessor(0);  // The default dest
145     BasicBlock *DefaultDest = TheOnlyDest;
146     assert(TheOnlyDest == SI->getDefaultDest() &&
147            "Default destination is not successor #0?");
148
149     // Figure out which case it goes to...
150     for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
151       // Found case matching a constant operand?
152       if (SI->getSuccessorValue(i) == CI) {
153         TheOnlyDest = SI->getSuccessor(i);
154         break;
155       }
156
157       // Check to see if this branch is going to the same place as the default
158       // dest.  If so, eliminate it as an explicit compare.
159       if (SI->getSuccessor(i) == DefaultDest) {
160         // Remove this entry...
161         DefaultDest->removePredecessor(SI->getParent());
162         SI->removeCase(i);
163         --i; --e;  // Don't skip an entry...
164         continue;
165       }
166
167       // Otherwise, check to see if the switch only branches to one destination.
168       // We do this by reseting "TheOnlyDest" to null when we find two non-equal
169       // destinations.
170       if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
171     }
172
173     if (CI && !TheOnlyDest) {
174       // Branching on a constant, but not any of the cases, go to the default
175       // successor.
176       TheOnlyDest = SI->getDefaultDest();
177     }
178
179     // If we found a single destination that we can fold the switch into, do so
180     // now.
181     if (TheOnlyDest) {
182       // Insert the new branch..
183       new BranchInst(TheOnlyDest, SI);
184       BasicBlock *BB = SI->getParent();
185
186       // Remove entries from PHI nodes which we no longer branch to...
187       for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
188         // Found case matching a constant operand?
189         BasicBlock *Succ = SI->getSuccessor(i);
190         if (Succ == TheOnlyDest)
191           TheOnlyDest = 0;  // Don't modify the first branch to TheOnlyDest
192         else
193           Succ->removePredecessor(BB);
194       }
195
196       // Delete the old switch...
197       BB->getInstList().erase(SI);
198       return true;
199     } else if (SI->getNumSuccessors() == 2) {
200       // Otherwise, we can fold this switch into a conditional branch
201       // instruction if it has only one non-default destination.
202       Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
203                                     SI->getSuccessorValue(1), "cond", SI);
204       // Insert the new branch...
205       new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
206
207       // Delete the old switch...
208       SI->getParent()->getInstList().erase(SI);
209       return true;
210     }
211   }
212   return false;
213 }
214
215
216
217 //===----------------------------------------------------------------------===//
218 //  Local dead code elimination...
219 //
220
221 bool llvm::isInstructionTriviallyDead(Instruction *I) {
222   return I->use_empty() && !I->mayWriteToMemory() && !isa<TerminatorInst>(I);
223 }
224
225 // dceInstruction - Inspect the instruction at *BBI and figure out if it's
226 // [trivially] dead.  If so, remove the instruction and update the iterator
227 // to point to the instruction that immediately succeeded the original
228 // instruction.
229 //
230 bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
231   // Look for un"used" definitions...
232   if (isInstructionTriviallyDead(BBI)) {
233     BBI = BBI->getParent()->getInstList().erase(BBI);   // Bye bye
234     return true;
235   }
236   return false;
237 }
238
239 //===----------------------------------------------------------------------===//
240 //  PHI Instruction Simplification
241 //
242
243 /// hasConstantValue - If the specified PHI node always merges together the same
244 /// value, return the value, otherwise return null.
245 ///
246 Value *llvm::hasConstantValue(PHINode *PN) {
247   // If the PHI node only has one incoming value, eliminate the PHI node...
248   if (PN->getNumIncomingValues() == 1)
249     return PN->getIncomingValue(0);
250
251   // Otherwise if all of the incoming values are the same for the PHI, replace
252   // the PHI node with the incoming value.
253   //
254   Value *InVal = 0;
255   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
256     if (PN->getIncomingValue(i) != PN)  // Not the PHI node itself...
257       if (InVal && PN->getIncomingValue(i) != InVal)
258         return 0;  // Not the same, bail out.
259       else
260         InVal = PN->getIncomingValue(i);
261
262   // The only case that could cause InVal to be null is if we have a PHI node
263   // that only has entries for itself.  In this case, there is no entry into the
264   // loop, so kill the PHI.
265   //
266   if (InVal == 0) InVal = Constant::getNullValue(PN->getType());
267
268   // All of the incoming values are the same, return the value now.
269   return InVal;
270 }