1 //===-- Local.cpp - Functions to perform local transformations ------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This family of functions perform various local transformations to the
13 //===----------------------------------------------------------------------===//
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/Support/GetElementPtrTypeIterator.h"
21 #include "llvm/Support/MathExtras.h"
26 //===----------------------------------------------------------------------===//
27 // Local constant propagation...
30 /// doConstantPropagation - If an instruction references constants, try to fold
33 bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
34 if (Constant *C = ConstantFoldInstruction(II)) {
35 // Replaces all of the uses of a variable with uses of the constant.
36 II->replaceAllUsesWith(C);
38 // Remove the instruction from the basic block...
39 II = II->getParent()->getInstList().erase(II);
46 /// ConstantFoldInstruction - Attempt to constant fold the specified
47 /// instruction. If successful, the constant result is returned, if not, null
48 /// is returned. Note that this function can only fail when attempting to fold
49 /// instructions like loads and stores, which have no constant expression form.
51 Constant *llvm::ConstantFoldInstruction(Instruction *I) {
52 if (PHINode *PN = dyn_cast<PHINode>(I)) {
53 if (PN->getNumIncomingValues() == 0)
54 return Constant::getNullValue(PN->getType());
56 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
57 if (Result == 0) return 0;
59 // Handle PHI nodes specially here...
60 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
61 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
62 return 0; // Not all the same incoming constants...
64 // If we reach here, all incoming values are the same constant.
66 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
67 if (Function *F = CI->getCalledFunction())
68 if (canConstantFoldCallTo(F)) {
69 std::vector<Constant*> Args;
70 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
71 if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i)))
75 return ConstantFoldCall(F, Args);
80 Constant *Op0 = 0, *Op1 = 0;
81 switch (I->getNumOperands()) {
84 Op1 = dyn_cast<Constant>(I->getOperand(1));
85 if (Op1 == 0) return 0; // Not a constant?, can't fold
87 Op0 = dyn_cast<Constant>(I->getOperand(0));
88 if (Op0 == 0) return 0; // Not a constant?, can't fold
93 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
94 return ConstantExpr::get(I->getOpcode(), Op0, Op1);
96 switch (I->getOpcode()) {
98 case Instruction::Cast:
99 return ConstantExpr::getCast(Op0, I->getType());
100 case Instruction::Select:
101 if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
102 return ConstantExpr::getSelect(Op0, Op1, Op2);
104 case Instruction::GetElementPtr:
105 std::vector<Constant*> IdxList;
106 IdxList.reserve(I->getNumOperands()-1);
107 if (Op1) IdxList.push_back(Op1);
108 for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
109 if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
110 IdxList.push_back(C);
112 return 0; // Non-constant operand
113 return ConstantExpr::getGetElementPtr(Op0, IdxList);
117 // ConstantFoldTerminator - If a terminator instruction is predicated on a
118 // constant value, convert it into an unconditional branch to the constant
121 bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
122 TerminatorInst *T = BB->getTerminator();
124 // Branch - See if we are conditional jumping on constant
125 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
126 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
127 BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
128 BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
130 if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
131 // Are we branching on constant?
132 // YES. Change to unconditional branch...
133 BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
134 BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;
136 //cerr << "Function: " << T->getParent()->getParent()
137 // << "\nRemoving branch from " << T->getParent()
138 // << "\n\nTo: " << OldDest << endl;
140 // Let the basic block know that we are letting go of it. Based on this,
141 // it will adjust it's PHI nodes.
142 assert(BI->getParent() && "Terminator not inserted in block!");
143 OldDest->removePredecessor(BI->getParent());
145 // Set the unconditional destination, and change the insn to be an
146 // unconditional branch.
147 BI->setUnconditionalDest(Destination);
149 } else if (Dest2 == Dest1) { // Conditional branch to same location?
150 // This branch matches something like this:
151 // br bool %cond, label %Dest, label %Dest
152 // and changes it into: br label %Dest
154 // Let the basic block know that we are letting go of one copy of it.
155 assert(BI->getParent() && "Terminator not inserted in block!");
156 Dest1->removePredecessor(BI->getParent());
158 // Change a conditional branch to unconditional.
159 BI->setUnconditionalDest(Dest1);
162 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
163 // If we are switching on a constant, we can convert the switch into a
164 // single branch instruction!
165 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
166 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
167 BasicBlock *DefaultDest = TheOnlyDest;
168 assert(TheOnlyDest == SI->getDefaultDest() &&
169 "Default destination is not successor #0?");
171 // Figure out which case it goes to...
172 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
173 // Found case matching a constant operand?
174 if (SI->getSuccessorValue(i) == CI) {
175 TheOnlyDest = SI->getSuccessor(i);
179 // Check to see if this branch is going to the same place as the default
180 // dest. If so, eliminate it as an explicit compare.
181 if (SI->getSuccessor(i) == DefaultDest) {
182 // Remove this entry...
183 DefaultDest->removePredecessor(SI->getParent());
185 --i; --e; // Don't skip an entry...
189 // Otherwise, check to see if the switch only branches to one destination.
190 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
192 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
195 if (CI && !TheOnlyDest) {
196 // Branching on a constant, but not any of the cases, go to the default
198 TheOnlyDest = SI->getDefaultDest();
201 // If we found a single destination that we can fold the switch into, do so
204 // Insert the new branch..
205 new BranchInst(TheOnlyDest, SI);
206 BasicBlock *BB = SI->getParent();
208 // Remove entries from PHI nodes which we no longer branch to...
209 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
210 // Found case matching a constant operand?
211 BasicBlock *Succ = SI->getSuccessor(i);
212 if (Succ == TheOnlyDest)
213 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
215 Succ->removePredecessor(BB);
218 // Delete the old switch...
219 BB->getInstList().erase(SI);
221 } else if (SI->getNumSuccessors() == 2) {
222 // Otherwise, we can fold this switch into a conditional branch
223 // instruction if it has only one non-default destination.
224 Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
225 SI->getSuccessorValue(1), "cond", SI);
226 // Insert the new branch...
227 new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
229 // Delete the old switch...
230 SI->getParent()->getInstList().erase(SI);
237 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
238 /// the specified function.
239 bool llvm::canConstantFoldCallTo(Function *F) {
240 const std::string &Name = F->getName();
242 switch (F->getIntrinsicID()) {
243 case Intrinsic::isunordered:
244 case Intrinsic::sqrt:
252 return Name == "acos" || Name == "asin" || Name == "atan" ||
255 return Name == "ceil" || Name == "cos" || Name == "cosf" ||
258 return Name == "exp";
260 return Name == "fabs" || Name == "fmod" || Name == "floor";
262 return Name == "log" || Name == "log10";
264 return Name == "pow";
266 return Name == "sin" || Name == "sinh" || Name == "sqrt";
268 return Name == "tan" || Name == "tanh";
274 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
279 return ConstantFP::get(Ty, V);
283 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
284 /// with the specified arguments, returning null if unsuccessful.
285 Constant *llvm::ConstantFoldCall(Function *F,
286 const std::vector<Constant*> &Operands) {
287 const std::string &Name = F->getName();
288 const Type *Ty = F->getReturnType();
290 if (Operands.size() == 1) {
291 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
292 double V = Op->getValue();
297 return ConstantFoldFP(acos, V, Ty);
298 else if (Name == "asin")
299 return ConstantFoldFP(asin, V, Ty);
300 else if (Name == "atan")
301 return ConstantFP::get(Ty, atan(V));
305 return ConstantFoldFP(ceil, V, Ty);
306 else if (Name == "cos")
307 return ConstantFP::get(Ty, cos(V));
308 else if (Name == "cosh")
309 return ConstantFP::get(Ty, cosh(V));
313 return ConstantFP::get(Ty, exp(V));
317 return ConstantFP::get(Ty, fabs(V));
318 else if (Name == "floor")
319 return ConstantFoldFP(floor, V, Ty);
322 if (Name == "log" && V > 0)
323 return ConstantFP::get(Ty, log(V));
324 else if (Name == "log10" && V > 0)
325 return ConstantFoldFP(log10, V, Ty);
326 else if (Name == "llvm.sqrt") {
328 return ConstantFP::get(Ty, sqrt(V));
330 return ConstantFP::get(Ty, 0.0);
335 return ConstantFP::get(Ty, sin(V));
336 else if (Name == "sinh")
337 return ConstantFP::get(Ty, sinh(V));
338 else if (Name == "sqrt" && V >= 0)
339 return ConstantFP::get(Ty, sqrt(V));
343 return ConstantFP::get(Ty, tan(V));
344 else if (Name == "tanh")
345 return ConstantFP::get(Ty, tanh(V));
351 } else if (Operands.size() == 2) {
352 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
353 double Op1V = Op1->getValue();
354 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
355 double Op2V = Op2->getValue();
357 if (Name == "llvm.isunordered")
358 return ConstantBool::get(IsNAN(Op1V) || IsNAN(Op2V));
362 double V = pow(Op1V, Op2V);
364 return ConstantFP::get(Ty, V);
365 } else if (Name == "fmod") {
367 double V = fmod(Op1V, Op2V);
369 return ConstantFP::get(Ty, V);
370 } else if (Name == "atan2")
371 return ConstantFP::get(Ty, atan2(Op1V,Op2V));
379 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
380 /// getelementptr constantexpr, return the constant value being addressed by the
381 /// constant expression, or null if something is funny and we can't decide.
382 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
384 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
385 return 0; // Do not allow stepping over the value!
387 // Loop over all of the operands, tracking down which value we are
389 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
390 for (++I; I != E; ++I)
391 if (const StructType *STy = dyn_cast<StructType>(*I)) {
392 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
393 assert(CU->getValue() < STy->getNumElements() &&
394 "Struct index out of range!");
395 unsigned El = (unsigned)CU->getValue();
396 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
397 C = CS->getOperand(El);
398 } else if (isa<ConstantAggregateZero>(C)) {
399 C = Constant::getNullValue(STy->getElementType(El));
400 } else if (isa<UndefValue>(C)) {
401 C = UndefValue::get(STy->getElementType(El));
405 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
406 const ArrayType *ATy = cast<ArrayType>(*I);
407 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
408 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
409 C = CA->getOperand((unsigned)CI->getRawValue());
410 else if (isa<ConstantAggregateZero>(C))
411 C = Constant::getNullValue(ATy->getElementType());
412 else if (isa<UndefValue>(C))
413 C = UndefValue::get(ATy->getElementType());
423 //===----------------------------------------------------------------------===//
424 // Local dead code elimination...
427 bool llvm::isInstructionTriviallyDead(Instruction *I) {
428 if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
430 if (!I->mayWriteToMemory()) return true;
432 if (CallInst *CI = dyn_cast<CallInst>(I))
433 if (Function *F = CI->getCalledFunction())
434 switch (F->getIntrinsicID()) {
436 case Intrinsic::returnaddress:
437 case Intrinsic::frameaddress:
438 case Intrinsic::isunordered:
439 case Intrinsic::ctpop:
440 case Intrinsic::ctlz:
441 case Intrinsic::cttz:
442 case Intrinsic::sqrt:
443 return true; // These intrinsics have no side effects.
448 // dceInstruction - Inspect the instruction at *BBI and figure out if it's
449 // [trivially] dead. If so, remove the instruction and update the iterator
450 // to point to the instruction that immediately succeeded the original
453 bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
454 // Look for un"used" definitions...
455 if (isInstructionTriviallyDead(BBI)) {
456 BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye