add a new code
[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/Target/TargetData.h"
22 #include "llvm/Support/GetElementPtrTypeIterator.h"
23 #include "llvm/Support/MathExtras.h"
24 #include <cerrno>
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                                  const TargetData *TD) {
36   if (Constant *C = ConstantFoldInstruction(II, TD)) {
37     // Replaces all of the uses of a variable with uses of the constant.
38     II->replaceAllUsesWith(C);
39
40     // Remove the instruction from the basic block...
41     II = II->getParent()->getInstList().erase(II);
42     return true;
43   }
44
45   return false;
46 }
47
48 // ConstantFoldTerminator - If a terminator instruction is predicated on a
49 // constant value, convert it into an unconditional branch to the constant
50 // destination.
51 //
52 bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
53   TerminatorInst *T = BB->getTerminator();
54
55   // Branch - See if we are conditional jumping on constant
56   if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
57     if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
58     BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
59     BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
60
61     if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
62       // Are we branching on constant?
63       // YES.  Change to unconditional branch...
64       BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
65       BasicBlock *OldDest     = Cond->getZExtValue() ? Dest2 : Dest1;
66
67       //cerr << "Function: " << T->getParent()->getParent()
68       //     << "\nRemoving branch from " << T->getParent()
69       //     << "\n\nTo: " << OldDest << endl;
70
71       // Let the basic block know that we are letting go of it.  Based on this,
72       // it will adjust it's PHI nodes.
73       assert(BI->getParent() && "Terminator not inserted in block!");
74       OldDest->removePredecessor(BI->getParent());
75
76       // Set the unconditional destination, and change the insn to be an
77       // unconditional branch.
78       BI->setUnconditionalDest(Destination);
79       return true;
80     } else if (Dest2 == Dest1) {       // Conditional branch to same location?
81       // This branch matches something like this:
82       //     br bool %cond, label %Dest, label %Dest
83       // and changes it into:  br label %Dest
84
85       // Let the basic block know that we are letting go of one copy of it.
86       assert(BI->getParent() && "Terminator not inserted in block!");
87       Dest1->removePredecessor(BI->getParent());
88
89       // Change a conditional branch to unconditional.
90       BI->setUnconditionalDest(Dest1);
91       return true;
92     }
93   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
94     // If we are switching on a constant, we can convert the switch into a
95     // single branch instruction!
96     ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
97     BasicBlock *TheOnlyDest = SI->getSuccessor(0);  // The default dest
98     BasicBlock *DefaultDest = TheOnlyDest;
99     assert(TheOnlyDest == SI->getDefaultDest() &&
100            "Default destination is not successor #0?");
101
102     // Figure out which case it goes to...
103     for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
104       // Found case matching a constant operand?
105       if (SI->getSuccessorValue(i) == CI) {
106         TheOnlyDest = SI->getSuccessor(i);
107         break;
108       }
109
110       // Check to see if this branch is going to the same place as the default
111       // dest.  If so, eliminate it as an explicit compare.
112       if (SI->getSuccessor(i) == DefaultDest) {
113         // Remove this entry...
114         DefaultDest->removePredecessor(SI->getParent());
115         SI->removeCase(i);
116         --i; --e;  // Don't skip an entry...
117         continue;
118       }
119
120       // Otherwise, check to see if the switch only branches to one destination.
121       // We do this by reseting "TheOnlyDest" to null when we find two non-equal
122       // destinations.
123       if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
124     }
125
126     if (CI && !TheOnlyDest) {
127       // Branching on a constant, but not any of the cases, go to the default
128       // successor.
129       TheOnlyDest = SI->getDefaultDest();
130     }
131
132     // If we found a single destination that we can fold the switch into, do so
133     // now.
134     if (TheOnlyDest) {
135       // Insert the new branch..
136       new BranchInst(TheOnlyDest, SI);
137       BasicBlock *BB = SI->getParent();
138
139       // Remove entries from PHI nodes which we no longer branch to...
140       for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
141         // Found case matching a constant operand?
142         BasicBlock *Succ = SI->getSuccessor(i);
143         if (Succ == TheOnlyDest)
144           TheOnlyDest = 0;  // Don't modify the first branch to TheOnlyDest
145         else
146           Succ->removePredecessor(BB);
147       }
148
149       // Delete the old switch...
150       BB->getInstList().erase(SI);
151       return true;
152     } else if (SI->getNumSuccessors() == 2) {
153       // Otherwise, we can fold this switch into a conditional branch
154       // instruction if it has only one non-default destination.
155       Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, SI->getCondition(),
156                                  SI->getSuccessorValue(1), "cond", SI);
157       // Insert the new branch...
158       new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
159
160       // Delete the old switch...
161       SI->getParent()->getInstList().erase(SI);
162       return true;
163     }
164   }
165   return false;
166 }
167
168
169 //===----------------------------------------------------------------------===//
170 //  Local dead code elimination...
171 //
172
173 bool llvm::isInstructionTriviallyDead(Instruction *I) {
174   if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
175
176   if (!I->mayWriteToMemory()) return true;
177
178   if (CallInst *CI = dyn_cast<CallInst>(I))
179     if (Function *F = CI->getCalledFunction()) {
180       unsigned IntrinsicID = F->getIntrinsicID();
181 #define GET_SIDE_EFFECT_INFO
182 #include "llvm/Intrinsics.gen"
183 #undef GET_SIDE_EFFECT_INFO
184     }
185   return false;
186 }
187
188 // dceInstruction - Inspect the instruction at *BBI and figure out if it's
189 // [trivially] dead.  If so, remove the instruction and update the iterator
190 // to point to the instruction that immediately succeeded the original
191 // instruction.
192 //
193 bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
194   // Look for un"used" definitions...
195   if (isInstructionTriviallyDead(BBI)) {
196     BBI = BBI->getParent()->getInstList().erase(BBI);   // Bye bye
197     return true;
198   }
199   return false;
200 }