blob: 7a90c76d3cbc738fe0d49bf15d498de1cae6eb9b [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
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//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000032// N. This list is incomplete
33//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner471bd762003-05-22 19:07:21 +000038#include "llvm/Instructions.h"
Chris Lattner51ea1272004-02-28 05:22:00 +000039#include "llvm/Intrinsics.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner34428442003-05-27 16:40:51 +000041#include "llvm/Constants.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000042#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000043#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
48#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner60a65912002-02-12 21:07:25 +000049#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/Support/Debug.h"
53#include "llvm/ADT/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000057
Chris Lattner260ab202002-04-18 17:39:14 +000058namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000059 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
62
Chris Lattnerc8e66542002-04-27 06:56:12 +000063 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000064 public InstVisitor<InstCombiner, Instruction*> {
65 // Worklist of all of the instructions that need to be simplified.
66 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000067 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000068
Chris Lattner51ea1272004-02-28 05:22:00 +000069 /// AddUsersToWorkList - When an instruction is simplified, add all users of
70 /// the instruction to the work lists because they might get more simplified
71 /// now.
72 ///
73 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000074 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000075 UI != UE; ++UI)
76 WorkList.push_back(cast<Instruction>(*UI));
77 }
78
Chris Lattner51ea1272004-02-28 05:22:00 +000079 /// AddUsesToWorkList - When an instruction is simplified, add operands to
80 /// the work lists because they might get more simplified now.
81 ///
82 void AddUsesToWorkList(Instruction &I) {
83 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
84 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
85 WorkList.push_back(Op);
86 }
87
Chris Lattner99f48c62002-09-02 04:59:56 +000088 // removeFromWorkList - remove all instances of I from the worklist.
89 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000090 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000091 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000092
Chris Lattnerf12cc842002-04-28 21:27:06 +000093 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000094 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000095 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000096 }
97
Chris Lattner69193f92004-04-05 01:30:19 +000098 TargetData &getTargetData() const { return *TD; }
99
Chris Lattner260ab202002-04-18 17:39:14 +0000100 // Visitation implementation - Implement instruction combining for different
101 // instruction types. The semantics are as follows:
102 // Return Value:
103 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000104 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000105 // otherwise - Change was made, replace I with returned instruction
106 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000107 Instruction *visitAdd(BinaryOperator &I);
108 Instruction *visitSub(BinaryOperator &I);
109 Instruction *visitMul(BinaryOperator &I);
110 Instruction *visitDiv(BinaryOperator &I);
111 Instruction *visitRem(BinaryOperator &I);
112 Instruction *visitAnd(BinaryOperator &I);
113 Instruction *visitOr (BinaryOperator &I);
114 Instruction *visitXor(BinaryOperator &I);
115 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000116 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000117 Instruction *visitCastInst(CastInst &CI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000118 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000119 Instruction *visitCallInst(CallInst &CI);
120 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000121 Instruction *visitPHINode(PHINode &PN);
122 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000123 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000124 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000125 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000126 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000127 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000128
129 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000130 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000131
Chris Lattner970c33a2003-06-19 17:00:31 +0000132 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000133 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000134 bool transformConstExprCastCall(CallSite CS);
135
Chris Lattner69193f92004-04-05 01:30:19 +0000136 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000137 // InsertNewInstBefore - insert an instruction New before instruction Old
138 // in the program. Add the new instruction to the worklist.
139 //
Chris Lattnere79e8542004-02-23 06:38:22 +0000140 Value *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000141 assert(New && New->getParent() == 0 &&
142 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000143 BasicBlock *BB = Old.getParent();
144 BB->getInstList().insert(&Old, New); // Insert inst
145 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000146 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000147 }
148
149 // ReplaceInstUsesWith - This method is to be used when an instruction is
150 // found to be dead, replacable with another preexisting expression. Here
151 // we add all uses of I to the worklist, replace all uses of I with the new
152 // value, then return I, so that the inst combiner will know that I was
153 // modified.
154 //
155 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000156 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000157 if (&I != V) {
158 I.replaceAllUsesWith(V);
159 return &I;
160 } else {
161 // If we are replacing the instruction with itself, this must be in a
162 // segment of unreachable code, so just clobber the instruction.
163 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
164 return &I;
165 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000166 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000167
168 // EraseInstFromFunction - When dealing with an instruction that has side
169 // effects or produces a void value, we can't rely on DCE to delete the
170 // instruction. Instead, visit methods should return the value returned by
171 // this function.
172 Instruction *EraseInstFromFunction(Instruction &I) {
173 assert(I.use_empty() && "Cannot erase instruction that is used!");
174 AddUsesToWorkList(I);
175 removeFromWorkList(&I);
176 I.getParent()->getInstList().erase(&I);
177 return 0; // Don't do anything with FI
178 }
179
180
Chris Lattner3ac7c262003-08-13 20:16:26 +0000181 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000182 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
183 /// InsertBefore instruction. This is specialized a bit to avoid inserting
184 /// casts that are known to not do anything...
185 ///
186 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
187 Instruction *InsertBefore);
188
Chris Lattner7fb29e12003-03-11 00:12:48 +0000189 // SimplifyCommutative - This performs a few simplifications for commutative
190 // operators...
191 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000192
193 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
194 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner260ab202002-04-18 17:39:14 +0000195 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000196
Chris Lattnerc8b70922002-07-26 21:12:46 +0000197 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000198}
199
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000200// getComplexity: Assign a complexity or rank value to LLVM Values...
201// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
202static unsigned getComplexity(Value *V) {
203 if (isa<Instruction>(V)) {
204 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
205 return 2;
206 return 3;
207 }
208 if (isa<Argument>(V)) return 2;
209 return isa<Constant>(V) ? 0 : 1;
210}
Chris Lattner260ab202002-04-18 17:39:14 +0000211
Chris Lattner7fb29e12003-03-11 00:12:48 +0000212// isOnlyUse - Return true if this instruction will be deleted if we stop using
213// it.
214static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000215 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000216}
217
Chris Lattnere79e8542004-02-23 06:38:22 +0000218// getPromotedType - Return the specified type promoted as it would be to pass
219// though a va_arg area...
220static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000221 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000222 case Type::SByteTyID:
223 case Type::ShortTyID: return Type::IntTy;
224 case Type::UByteTyID:
225 case Type::UShortTyID: return Type::UIntTy;
226 case Type::FloatTyID: return Type::DoubleTy;
227 default: return Ty;
228 }
229}
230
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000231// SimplifyCommutative - This performs a few simplifications for commutative
232// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000233//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000234// 1. Order operands such that they are listed from right (least complex) to
235// left (most complex). This puts constants before unary operators before
236// binary operators.
237//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000238// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
239// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000240//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000241bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000242 bool Changed = false;
243 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
244 Changed = !I.swapOperands();
245
246 if (!I.isAssociative()) return Changed;
247 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000248 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
249 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
250 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000251 Constant *Folded = ConstantExpr::get(I.getOpcode(),
252 cast<Constant>(I.getOperand(1)),
253 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000254 I.setOperand(0, Op->getOperand(0));
255 I.setOperand(1, Folded);
256 return true;
257 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
258 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
259 isOnlyUse(Op) && isOnlyUse(Op1)) {
260 Constant *C1 = cast<Constant>(Op->getOperand(1));
261 Constant *C2 = cast<Constant>(Op1->getOperand(1));
262
263 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000264 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000265 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
266 Op1->getOperand(0),
267 Op1->getName(), &I);
268 WorkList.push_back(New);
269 I.setOperand(0, New);
270 I.setOperand(1, Folded);
271 return true;
272 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000273 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000274 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000275}
Chris Lattnerca081252001-12-14 16:52:21 +0000276
Chris Lattnerbb74e222003-03-10 23:06:50 +0000277// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
278// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000279//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000280static inline Value *dyn_castNegVal(Value *V) {
281 if (BinaryOperator::isNeg(V))
282 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
283
Chris Lattner9244df62003-04-30 22:19:10 +0000284 // Constants can be considered to be negated values if they can be folded...
285 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000286 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000287 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000288}
289
Chris Lattnerbb74e222003-03-10 23:06:50 +0000290static inline Value *dyn_castNotVal(Value *V) {
291 if (BinaryOperator::isNot(V))
292 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
293
294 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000295 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000296 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000297 return 0;
298}
299
Chris Lattner7fb29e12003-03-11 00:12:48 +0000300// dyn_castFoldableMul - If this value is a multiply that can be folded into
301// other computations (because it has a constant operand), return the
302// non-constant operand of the multiply.
303//
304static inline Value *dyn_castFoldableMul(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000305 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000306 if (Instruction *I = dyn_cast<Instruction>(V))
307 if (I->getOpcode() == Instruction::Mul)
308 if (isa<Constant>(I->getOperand(1)))
309 return I->getOperand(0);
310 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000311}
Chris Lattner31ae8632002-08-14 17:51:49 +0000312
Chris Lattner3082c5a2003-02-18 19:28:33 +0000313// Log2 - Calculate the log base 2 for the specified value if it is exactly a
314// power of 2.
315static unsigned Log2(uint64_t Val) {
316 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
317 unsigned Count = 0;
318 while (Val != 1) {
319 if (Val & 1) return 0; // Multiple bits set?
320 Val >>= 1;
321 ++Count;
322 }
323 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000324}
325
Chris Lattnerb8b97502003-08-13 19:01:45 +0000326
327/// AssociativeOpt - Perform an optimization on an associative operator. This
328/// function is designed to check a chain of associative operators for a
329/// potential to apply a certain optimization. Since the optimization may be
330/// applicable if the expression was reassociated, this checks the chain, then
331/// reassociates the expression as necessary to expose the optimization
332/// opportunity. This makes use of a special Functor, which must define
333/// 'shouldApply' and 'apply' methods.
334///
335template<typename Functor>
336Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
337 unsigned Opcode = Root.getOpcode();
338 Value *LHS = Root.getOperand(0);
339
340 // Quick check, see if the immediate LHS matches...
341 if (F.shouldApply(LHS))
342 return F.apply(Root);
343
344 // Otherwise, if the LHS is not of the same opcode as the root, return.
345 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000346 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000347 // Should we apply this transform to the RHS?
348 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
349
350 // If not to the RHS, check to see if we should apply to the LHS...
351 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
352 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
353 ShouldApply = true;
354 }
355
356 // If the functor wants to apply the optimization to the RHS of LHSI,
357 // reassociate the expression from ((? op A) op B) to (? op (A op B))
358 if (ShouldApply) {
359 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000360
361 // Now all of the instructions are in the current basic block, go ahead
362 // and perform the reassociation.
363 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
364
365 // First move the selected RHS to the LHS of the root...
366 Root.setOperand(0, LHSI->getOperand(1));
367
368 // Make what used to be the LHS of the root be the user of the root...
369 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000370 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000371 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
372 return 0;
373 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000374 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000375 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000376 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
377 BasicBlock::iterator ARI = &Root; ++ARI;
378 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
379 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000380
381 // Now propagate the ExtraOperand down the chain of instructions until we
382 // get to LHSI.
383 while (TmpLHSI != LHSI) {
384 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000385 // Move the instruction to immediately before the chain we are
386 // constructing to avoid breaking dominance properties.
387 NextLHSI->getParent()->getInstList().remove(NextLHSI);
388 BB->getInstList().insert(ARI, NextLHSI);
389 ARI = NextLHSI;
390
Chris Lattnerb8b97502003-08-13 19:01:45 +0000391 Value *NextOp = NextLHSI->getOperand(1);
392 NextLHSI->setOperand(1, ExtraOperand);
393 TmpLHSI = NextLHSI;
394 ExtraOperand = NextOp;
395 }
396
397 // Now that the instructions are reassociated, have the functor perform
398 // the transformation...
399 return F.apply(Root);
400 }
401
402 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
403 }
404 return 0;
405}
406
407
408// AddRHS - Implements: X + X --> X << 1
409struct AddRHS {
410 Value *RHS;
411 AddRHS(Value *rhs) : RHS(rhs) {}
412 bool shouldApply(Value *LHS) const { return LHS == RHS; }
413 Instruction *apply(BinaryOperator &Add) const {
414 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
415 ConstantInt::get(Type::UByteTy, 1));
416 }
417};
418
419// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
420// iff C1&C2 == 0
421struct AddMaskingAnd {
422 Constant *C2;
423 AddMaskingAnd(Constant *c) : C2(c) {}
424 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000425 ConstantInt *C1;
426 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
427 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000428 }
429 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000430 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000431 }
432};
433
Chris Lattner183b3362004-04-09 19:05:30 +0000434static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
435 InstCombiner *IC) {
436 // Figure out if the constant is the left or the right argument.
437 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
438 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000439
Chris Lattner183b3362004-04-09 19:05:30 +0000440 if (Constant *SOC = dyn_cast<Constant>(SO)) {
441 if (ConstIsRHS)
442 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
443 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
444 }
445
446 Value *Op0 = SO, *Op1 = ConstOperand;
447 if (!ConstIsRHS)
448 std::swap(Op0, Op1);
449 Instruction *New;
450 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
451 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
452 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
453 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattnerf9d96652004-04-10 19:15:56 +0000454 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000455 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000456 abort();
457 }
Chris Lattner183b3362004-04-09 19:05:30 +0000458 return IC->InsertNewInstBefore(New, BI);
459}
460
461// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
462// constant as the other operand, try to fold the binary operator into the
463// select arguments.
464static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
465 InstCombiner *IC) {
466 // Don't modify shared select instructions
467 if (!SI->hasOneUse()) return 0;
468 Value *TV = SI->getOperand(1);
469 Value *FV = SI->getOperand(2);
470
471 if (isa<Constant>(TV) || isa<Constant>(FV)) {
472 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
473 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
474
475 return new SelectInst(SI->getCondition(), SelectTrueVal,
476 SelectFalseVal);
477 }
478 return 0;
479}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000480
Chris Lattner113f4f42002-06-25 16:13:24 +0000481Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000482 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000483 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000484
Chris Lattnercf4a9962004-04-10 22:01:55 +0000485 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
486 // X + 0 --> X
487 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
488 RHSC->isNullValue())
489 return ReplaceInstUsesWith(I, LHS);
490
491 // X + (signbit) --> X ^ signbit
492 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
493 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
494 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
495 if (Val == (1ULL << NumBits-1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000496 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000497 }
498 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000499
Chris Lattnerb8b97502003-08-13 19:01:45 +0000500 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000501 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000502 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000503 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000504
Chris Lattner147e9752002-05-08 22:46:53 +0000505 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000506 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000507 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000508
509 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000510 if (!isa<Constant>(RHS))
511 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000512 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000513
Chris Lattner57c8d992003-02-18 19:57:07 +0000514 // X*C + X --> X * (C+1)
515 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000516 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000517 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000518 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
519 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000520 return BinaryOperator::createMul(RHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000521 }
522
523 // X + X*C --> X * (C+1)
524 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000525 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000526 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000527 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
528 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000529 return BinaryOperator::createMul(LHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000530 }
531
Chris Lattnerb8b97502003-08-13 19:01:45 +0000532 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000533 ConstantInt *C2;
534 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000535 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000536
Chris Lattnerb9cde762003-10-02 15:11:26 +0000537 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000538 Value *X;
539 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
540 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
541 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000542 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000543
544 // Try to fold constant add into select arguments.
545 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
546 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
547 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000548 }
549
Chris Lattner113f4f42002-06-25 16:13:24 +0000550 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000551}
552
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000553// isSignBit - Return true if the value represented by the constant only has the
554// highest order bit set.
555static bool isSignBit(ConstantInt *CI) {
556 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
557 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
558}
559
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000560static unsigned getTypeSizeInBits(const Type *Ty) {
561 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
562}
563
Chris Lattner022167f2004-03-13 00:11:49 +0000564/// RemoveNoopCast - Strip off nonconverting casts from the value.
565///
566static Value *RemoveNoopCast(Value *V) {
567 if (CastInst *CI = dyn_cast<CastInst>(V)) {
568 const Type *CTy = CI->getType();
569 const Type *OpTy = CI->getOperand(0)->getType();
570 if (CTy->isInteger() && OpTy->isInteger()) {
571 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
572 return RemoveNoopCast(CI->getOperand(0));
573 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
574 return RemoveNoopCast(CI->getOperand(0));
575 }
576 return V;
577}
578
Chris Lattner113f4f42002-06-25 16:13:24 +0000579Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000580 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000581
Chris Lattnere6794492002-08-12 21:17:25 +0000582 if (Op0 == Op1) // sub X, X -> 0
583 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000584
Chris Lattnere6794492002-08-12 21:17:25 +0000585 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000586 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000587 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000588
Chris Lattner8f2f5982003-11-05 01:06:05 +0000589 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
590 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000591 if (C->isAllOnesValue())
592 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000593
Chris Lattner8f2f5982003-11-05 01:06:05 +0000594 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000595 Value *X;
596 if (match(Op1, m_Not(m_Value(X))))
597 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000598 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000599 // -((uint)X >> 31) -> ((int)X >> 31)
600 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000601 if (C->isNullValue()) {
602 Value *NoopCastedRHS = RemoveNoopCast(Op1);
603 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000604 if (SI->getOpcode() == Instruction::Shr)
605 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
606 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000607 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000608 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000609 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000610 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000611 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000612 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000613 // Ok, the transformation is safe. Insert a cast of the incoming
614 // value, then the new shift, then the new cast.
615 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
616 SI->getOperand(0)->getName());
617 Value *InV = InsertNewInstBefore(FirstCast, I);
618 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
619 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000620 if (NewShift->getType() == I.getType())
621 return NewShift;
622 else {
623 InV = InsertNewInstBefore(NewShift, I);
624 return new CastInst(NewShift, I.getType());
625 }
Chris Lattner92295c52004-03-12 23:53:13 +0000626 }
627 }
Chris Lattner022167f2004-03-13 00:11:49 +0000628 }
Chris Lattner183b3362004-04-09 19:05:30 +0000629
630 // Try to fold constant sub into select arguments.
631 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
632 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
633 return R;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000634 }
635
Chris Lattner3082c5a2003-02-18 19:28:33 +0000636 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000637 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000638 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
639 // is not used by anyone else...
640 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000641 if (Op1I->getOpcode() == Instruction::Sub &&
642 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000643 // Swap the two operands of the subexpr...
644 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
645 Op1I->setOperand(0, IIOp1);
646 Op1I->setOperand(1, IIOp0);
647
648 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000649 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000650 }
651
652 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
653 //
654 if (Op1I->getOpcode() == Instruction::And &&
655 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
656 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
657
Chris Lattner396dbfe2004-06-09 05:08:07 +0000658 Value *NewNot =
659 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000660 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000661 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000662
663 // X - X*C --> X * (1-C)
664 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000665 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000666 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner34428442003-05-27 16:40:51 +0000667 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000668 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000669 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000670 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000671 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000672
Chris Lattner57c8d992003-02-18 19:57:07 +0000673 // X*C - X --> X * (C-1)
674 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000675 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000676 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner34428442003-05-27 16:40:51 +0000677 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000678 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000679 return BinaryOperator::createMul(Op1, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000680 }
681
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000682 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000683}
684
Chris Lattnere79e8542004-02-23 06:38:22 +0000685/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
686/// really just returns true if the most significant (sign) bit is set.
687static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
688 if (RHS->getType()->isSigned()) {
689 // True if source is LHS < 0 or LHS <= -1
690 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
691 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
692 } else {
693 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
694 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
695 // the size of the integer type.
696 if (Opcode == Instruction::SetGE)
697 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
698 if (Opcode == Instruction::SetGT)
699 return RHSC->getValue() ==
700 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
701 }
702 return false;
703}
704
Chris Lattner113f4f42002-06-25 16:13:24 +0000705Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000706 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000707 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000708
Chris Lattnere6794492002-08-12 21:17:25 +0000709 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000710 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
711 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000712
713 // ((X << C1)*C2) == (X * (C2 << C1))
714 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
715 if (SI->getOpcode() == Instruction::Shl)
716 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000717 return BinaryOperator::createMul(SI->getOperand(0),
718 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000719
Chris Lattnercce81be2003-09-11 22:24:54 +0000720 if (CI->isNullValue())
721 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
722 if (CI->equalsInt(1)) // X * 1 == X
723 return ReplaceInstUsesWith(I, Op0);
724 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000725 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000726
Chris Lattnercce81be2003-09-11 22:24:54 +0000727 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000728 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
729 return new ShiftInst(Instruction::Shl, Op0,
730 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000731 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000732 if (Op1F->isNullValue())
733 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000734
Chris Lattner3082c5a2003-02-18 19:28:33 +0000735 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
736 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
737 if (Op1F->getValue() == 1.0)
738 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
739 }
Chris Lattner183b3362004-04-09 19:05:30 +0000740
741 // Try to fold constant mul into select arguments.
742 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
743 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
744 return R;
Chris Lattner260ab202002-04-18 17:39:14 +0000745 }
746
Chris Lattner934a64cf2003-03-10 23:23:04 +0000747 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
748 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000749 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000750
Chris Lattner2635b522004-02-23 05:39:21 +0000751 // If one of the operands of the multiply is a cast from a boolean value, then
752 // we know the bool is either zero or one, so this is a 'masking' multiply.
753 // See if we can simplify things based on how the boolean was originally
754 // formed.
755 CastInst *BoolCast = 0;
756 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
757 if (CI->getOperand(0)->getType() == Type::BoolTy)
758 BoolCast = CI;
759 if (!BoolCast)
760 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
761 if (CI->getOperand(0)->getType() == Type::BoolTy)
762 BoolCast = CI;
763 if (BoolCast) {
764 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
765 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
766 const Type *SCOpTy = SCIOp0->getType();
767
Chris Lattnere79e8542004-02-23 06:38:22 +0000768 // If the setcc is true iff the sign bit of X is set, then convert this
769 // multiply into a shift/and combination.
770 if (isa<ConstantInt>(SCIOp1) &&
771 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000772 // Shift the X value right to turn it into "all signbits".
773 Constant *Amt = ConstantUInt::get(Type::UByteTy,
774 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000775 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000776 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000777 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
778 SCIOp0->getName()), I);
779 }
780
781 Value *V =
782 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
783 BoolCast->getOperand(0)->getName()+
784 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000785
786 // If the multiply type is not the same as the source type, sign extend
787 // or truncate to the multiply type.
788 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000789 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000790
791 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000792 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000793 }
794 }
795 }
796
Chris Lattner113f4f42002-06-25 16:13:24 +0000797 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000798}
799
Chris Lattner113f4f42002-06-25 16:13:24 +0000800Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000801 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000802 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000803 if (RHS->equalsInt(1))
804 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000805
Chris Lattnere20c3342004-04-26 14:01:59 +0000806 // div X, -1 == -X
807 if (RHS->isAllOnesValue())
808 return BinaryOperator::createNeg(I.getOperand(0));
809
Chris Lattner3082c5a2003-02-18 19:28:33 +0000810 // Check to see if this is an unsigned division with an exact power of 2,
811 // if so, convert to a right shift.
812 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
813 if (uint64_t Val = C->getValue()) // Don't break X / 0
814 if (uint64_t C = Log2(Val))
815 return new ShiftInst(Instruction::Shr, I.getOperand(0),
816 ConstantUInt::get(Type::UByteTy, C));
817 }
818
819 // 0 / X == 0, we don't need to preserve faults!
820 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
821 if (LHS->equalsInt(0))
822 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
823
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000824 return 0;
825}
826
827
Chris Lattner113f4f42002-06-25 16:13:24 +0000828Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000829 if (I.getType()->isSigned())
830 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner98c6bdf2004-07-06 07:11:42 +0000831 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +0000832 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000833 // X % -Y -> X % Y
834 AddUsesToWorkList(I);
835 I.setOperand(1, RHSNeg);
836 return &I;
837 }
838
Chris Lattner3082c5a2003-02-18 19:28:33 +0000839 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
840 if (RHS->equalsInt(1)) // X % 1 == 0
841 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
842
843 // Check to see if this is an unsigned remainder with an exact power of 2,
844 // if so, convert to a bitwise and.
845 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
846 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +0000847 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000848 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattner3082c5a2003-02-18 19:28:33 +0000849 ConstantUInt::get(I.getType(), Val-1));
850 }
851
852 // 0 % X == 0, we don't need to preserve faults!
853 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
854 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000855 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
856
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000857 return 0;
858}
859
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000860// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000861static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000862 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
863 // Calculate -1 casted to the right type...
864 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
865 uint64_t Val = ~0ULL; // All ones
866 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
867 return CU->getValue() == Val-1;
868 }
869
870 const ConstantSInt *CS = cast<ConstantSInt>(C);
871
872 // Calculate 0111111111..11111
873 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
874 int64_t Val = INT64_MAX; // All ones
875 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
876 return CS->getValue() == Val-1;
877}
878
879// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000880static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000881 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
882 return CU->getValue() == 1;
883
884 const ConstantSInt *CS = cast<ConstantSInt>(C);
885
886 // Calculate 1111111111000000000000
887 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
888 int64_t Val = -1; // All ones
889 Val <<= TypeBits-1; // Shift over to the right spot
890 return CS->getValue() == Val+1;
891}
892
Chris Lattner35167c32004-06-09 07:59:58 +0000893// isOneBitSet - Return true if there is exactly one bit set in the specified
894// constant.
895static bool isOneBitSet(const ConstantInt *CI) {
896 uint64_t V = CI->getRawValue();
897 return V && (V & (V-1)) == 0;
898}
899
Chris Lattner8fc5af42004-09-23 21:46:38 +0000900#if 0 // Currently unused
901// isLowOnes - Return true if the constant is of the form 0+1+.
902static bool isLowOnes(const ConstantInt *CI) {
903 uint64_t V = CI->getRawValue();
904
905 // There won't be bits set in parts that the type doesn't contain.
906 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
907
908 uint64_t U = V+1; // If it is low ones, this should be a power of two.
909 return U && V && (U & V) == 0;
910}
911#endif
912
913// isHighOnes - Return true if the constant is of the form 1+0+.
914// This is the same as lowones(~X).
915static bool isHighOnes(const ConstantInt *CI) {
916 uint64_t V = ~CI->getRawValue();
917
918 // There won't be bits set in parts that the type doesn't contain.
919 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
920
921 uint64_t U = V+1; // If it is low ones, this should be a power of two.
922 return U && V && (U & V) == 0;
923}
924
925
Chris Lattner3ac7c262003-08-13 20:16:26 +0000926/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
927/// are carefully arranged to allow folding of expressions such as:
928///
929/// (A < B) | (A > B) --> (A != B)
930///
931/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
932/// represents that the comparison is true if A == B, and bit value '1' is true
933/// if A < B.
934///
935static unsigned getSetCondCode(const SetCondInst *SCI) {
936 switch (SCI->getOpcode()) {
937 // False -> 0
938 case Instruction::SetGT: return 1;
939 case Instruction::SetEQ: return 2;
940 case Instruction::SetGE: return 3;
941 case Instruction::SetLT: return 4;
942 case Instruction::SetNE: return 5;
943 case Instruction::SetLE: return 6;
944 // True -> 7
945 default:
946 assert(0 && "Invalid SetCC opcode!");
947 return 0;
948 }
949}
950
951/// getSetCCValue - This is the complement of getSetCondCode, which turns an
952/// opcode and two operands into either a constant true or false, or a brand new
953/// SetCC instruction.
954static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
955 switch (Opcode) {
956 case 0: return ConstantBool::False;
957 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
958 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
959 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
960 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
961 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
962 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
963 case 7: return ConstantBool::True;
964 default: assert(0 && "Illegal SetCCCode!"); return 0;
965 }
966}
967
968// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
969struct FoldSetCCLogical {
970 InstCombiner &IC;
971 Value *LHS, *RHS;
972 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
973 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
974 bool shouldApply(Value *V) const {
975 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
976 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
977 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
978 return false;
979 }
980 Instruction *apply(BinaryOperator &Log) const {
981 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
982 if (SCI->getOperand(0) != LHS) {
983 assert(SCI->getOperand(1) == LHS);
984 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
985 }
986
987 unsigned LHSCode = getSetCondCode(SCI);
988 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
989 unsigned Code;
990 switch (Log.getOpcode()) {
991 case Instruction::And: Code = LHSCode & RHSCode; break;
992 case Instruction::Or: Code = LHSCode | RHSCode; break;
993 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +0000994 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +0000995 }
996
997 Value *RV = getSetCCValue(Code, LHS, RHS);
998 if (Instruction *I = dyn_cast<Instruction>(RV))
999 return I;
1000 // Otherwise, it's a constant boolean value...
1001 return IC.ReplaceInstUsesWith(Log, RV);
1002 }
1003};
1004
1005
Chris Lattnerba1cb382003-09-19 17:17:26 +00001006// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1007// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1008// guaranteed to be either a shift instruction or a binary operator.
1009Instruction *InstCombiner::OptAndOp(Instruction *Op,
1010 ConstantIntegral *OpRHS,
1011 ConstantIntegral *AndRHS,
1012 BinaryOperator &TheAnd) {
1013 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001014 Constant *Together = 0;
1015 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001016 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001017
Chris Lattnerba1cb382003-09-19 17:17:26 +00001018 switch (Op->getOpcode()) {
1019 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001020 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001021 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001022 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001023 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001024 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1025 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001026 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001027 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001028 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001029 }
1030 break;
1031 case Instruction::Or:
1032 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001033 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001034 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001035 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001036 if (Together == AndRHS) // (X | C) & C --> C
1037 return ReplaceInstUsesWith(TheAnd, AndRHS);
1038
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001039 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001040 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1041 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001042 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001043 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001044 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001045 }
1046 }
1047 break;
1048 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001049 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001050 // Adding a one to a single bit bit-field should be turned into an XOR
1051 // of the bit. First thing to check is to see if this AND is with a
1052 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001053 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001054
1055 // Clear bits that are not part of the constant.
1056 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1057
1058 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001059 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001060 // Ok, at this point, we know that we are masking the result of the
1061 // ADD down to exactly one bit. If the constant we are adding has
1062 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001063 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001064
1065 // Check to see if any bits below the one bit set in AndRHSV are set.
1066 if ((AddRHS & (AndRHSV-1)) == 0) {
1067 // If not, the only thing that can effect the output of the AND is
1068 // the bit specified by AndRHSV. If that bit is set, the effect of
1069 // the XOR is to toggle the bit. If it is clear, then the ADD has
1070 // no effect.
1071 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1072 TheAnd.setOperand(0, X);
1073 return &TheAnd;
1074 } else {
1075 std::string Name = Op->getName(); Op->setName("");
1076 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001077 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001078 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001079 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001080 }
1081 }
1082 }
1083 }
1084 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001085
1086 case Instruction::Shl: {
1087 // We know that the AND will not produce any of the bits shifted in, so if
1088 // the anded constant includes them, clear them now!
1089 //
1090 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001091 Constant *CI = ConstantExpr::getAnd(AndRHS,
1092 ConstantExpr::getShl(AllOne, OpRHS));
Chris Lattner2da29172003-09-19 19:05:02 +00001093 if (CI != AndRHS) {
1094 TheAnd.setOperand(1, CI);
1095 return &TheAnd;
1096 }
1097 break;
1098 }
1099 case Instruction::Shr:
1100 // We know that the AND will not produce any of the bits shifted in, so if
1101 // the anded constant includes them, clear them now! This only applies to
1102 // unsigned shifts, because a signed shr may bring in set bits!
1103 //
1104 if (AndRHS->getType()->isUnsigned()) {
1105 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001106 Constant *CI = ConstantExpr::getAnd(AndRHS,
1107 ConstantExpr::getShr(AllOne, OpRHS));
Chris Lattner2da29172003-09-19 19:05:02 +00001108 if (CI != AndRHS) {
1109 TheAnd.setOperand(1, CI);
1110 return &TheAnd;
1111 }
1112 }
1113 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001114 }
1115 return 0;
1116}
1117
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001118
Chris Lattner113f4f42002-06-25 16:13:24 +00001119Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001120 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001121 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001122
1123 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001124 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1125 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001126
1127 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001128 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001129 if (RHS->isAllOnesValue())
1130 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001131
Chris Lattnerba1cb382003-09-19 17:17:26 +00001132 // Optimize a variety of ((val OP C1) & C2) combinations...
1133 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1134 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001135 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001136 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001137 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1138 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001139 }
Chris Lattner183b3362004-04-09 19:05:30 +00001140
1141 // Try to fold constant and into select arguments.
1142 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1143 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1144 return R;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001145 }
1146
Chris Lattnerbb74e222003-03-10 23:06:50 +00001147 Value *Op0NotVal = dyn_castNotVal(Op0);
1148 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001149
Chris Lattner023a4832004-06-18 06:07:51 +00001150 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1151 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1152
Misha Brukman9c003d82004-07-30 12:50:08 +00001153 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001154 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001155 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1156 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001157 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001158 return BinaryOperator::createNot(Or);
1159 }
1160
Chris Lattner3ac7c262003-08-13 20:16:26 +00001161 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1162 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1163 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1164 return R;
1165
Chris Lattner113f4f42002-06-25 16:13:24 +00001166 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001167}
1168
1169
1170
Chris Lattner113f4f42002-06-25 16:13:24 +00001171Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001172 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001173 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001174
1175 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001176 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1177 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001178
1179 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001180 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001181 if (RHS->isAllOnesValue())
1182 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001183
Chris Lattnerd4252a72004-07-30 07:50:03 +00001184 ConstantInt *C1; Value *X;
1185 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1186 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1187 std::string Op0Name = Op0->getName(); Op0->setName("");
1188 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1189 InsertNewInstBefore(Or, I);
1190 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1191 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001192
Chris Lattnerd4252a72004-07-30 07:50:03 +00001193 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1194 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1195 std::string Op0Name = Op0->getName(); Op0->setName("");
1196 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1197 InsertNewInstBefore(Or, I);
1198 return BinaryOperator::createXor(Or,
1199 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001200 }
Chris Lattner183b3362004-04-09 19:05:30 +00001201
1202 // Try to fold constant and into select arguments.
1203 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1204 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1205 return R;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001206 }
1207
Chris Lattner812aab72003-08-12 19:11:07 +00001208 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001209 Value *A, *B; ConstantInt *C1, *C2;
1210 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1211 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1212 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001213
Chris Lattnerd4252a72004-07-30 07:50:03 +00001214 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1215 if (A == Op1) // ~A | A == -1
1216 return ReplaceInstUsesWith(I,
1217 ConstantIntegral::getAllOnesValue(I.getType()));
1218 } else {
1219 A = 0;
1220 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001221
Chris Lattnerd4252a72004-07-30 07:50:03 +00001222 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1223 if (Op0 == B)
1224 return ReplaceInstUsesWith(I,
1225 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001226
Misha Brukman9c003d82004-07-30 12:50:08 +00001227 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001228 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1229 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1230 I.getName()+".demorgan"), I);
1231 return BinaryOperator::createNot(And);
1232 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001233 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001234
Chris Lattner3ac7c262003-08-13 20:16:26 +00001235 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
1236 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1237 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1238 return R;
1239
Chris Lattner113f4f42002-06-25 16:13:24 +00001240 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001241}
1242
Chris Lattnerc2076352004-02-16 01:20:27 +00001243// XorSelf - Implements: X ^ X --> 0
1244struct XorSelf {
1245 Value *RHS;
1246 XorSelf(Value *rhs) : RHS(rhs) {}
1247 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1248 Instruction *apply(BinaryOperator &Xor) const {
1249 return &Xor;
1250 }
1251};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001252
1253
Chris Lattner113f4f42002-06-25 16:13:24 +00001254Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001255 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001256 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001257
Chris Lattnerc2076352004-02-16 01:20:27 +00001258 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1259 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1260 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001261 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001262 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001263
Chris Lattner97638592003-07-23 21:37:07 +00001264 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001265 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001266 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001267 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001268
Chris Lattner97638592003-07-23 21:37:07 +00001269 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001270 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001271 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001272 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001273 return new SetCondInst(SCI->getInverseCondition(),
1274 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001275
Chris Lattner8f2f5982003-11-05 01:06:05 +00001276 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001277 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1278 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001279 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1280 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001281 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001282 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001283 }
Chris Lattner023a4832004-06-18 06:07:51 +00001284
1285 // ~(~X & Y) --> (X | ~Y)
1286 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1287 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1288 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1289 Instruction *NotY =
1290 BinaryOperator::createNot(Op0I->getOperand(1),
1291 Op0I->getOperand(1)->getName()+".not");
1292 InsertNewInstBefore(NotY, I);
1293 return BinaryOperator::createOr(Op0NotVal, NotY);
1294 }
1295 }
Chris Lattner97638592003-07-23 21:37:07 +00001296
1297 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001298 switch (Op0I->getOpcode()) {
1299 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001300 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001301 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001302 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1303 return BinaryOperator::createSub(
1304 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001305 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001306 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001307 }
Chris Lattnere5806662003-11-04 23:50:51 +00001308 break;
1309 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001310 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001311 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1312 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001313 break;
1314 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001315 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001316 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001317 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001318 break;
1319 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001320 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001321 }
Chris Lattner183b3362004-04-09 19:05:30 +00001322
1323 // Try to fold constant and into select arguments.
1324 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1325 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1326 return R;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001327 }
1328
Chris Lattnerbb74e222003-03-10 23:06:50 +00001329 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001330 if (X == Op1)
1331 return ReplaceInstUsesWith(I,
1332 ConstantIntegral::getAllOnesValue(I.getType()));
1333
Chris Lattnerbb74e222003-03-10 23:06:50 +00001334 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001335 if (X == Op0)
1336 return ReplaceInstUsesWith(I,
1337 ConstantIntegral::getAllOnesValue(I.getType()));
1338
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001339 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001340 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001341 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1342 cast<BinaryOperator>(Op1I)->swapOperands();
1343 I.swapOperands();
1344 std::swap(Op0, Op1);
1345 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1346 I.swapOperands();
1347 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001348 }
1349 } else if (Op1I->getOpcode() == Instruction::Xor) {
1350 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1351 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1352 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1353 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1354 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001355
1356 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001357 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001358 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1359 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001360 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001361 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1362 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001363 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001364 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001365 } else if (Op0I->getOpcode() == Instruction::Xor) {
1366 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1367 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1368 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1369 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001370 }
1371
Chris Lattner7aa2d472004-08-01 19:42:59 +00001372 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001373 Value *A, *B; ConstantInt *C1, *C2;
1374 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1375 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00001376 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00001377 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001378
Chris Lattner3ac7c262003-08-13 20:16:26 +00001379 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1380 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1381 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1382 return R;
1383
Chris Lattner113f4f42002-06-25 16:13:24 +00001384 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001385}
1386
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001387// AddOne, SubOne - Add or subtract a constant one from an integer constant...
1388static Constant *AddOne(ConstantInt *C) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001389 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001390}
1391static Constant *SubOne(ConstantInt *C) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001392 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001393}
1394
Chris Lattner1fc23f32002-05-09 20:11:54 +00001395// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1396// true when both operands are equal...
1397//
Chris Lattner113f4f42002-06-25 16:13:24 +00001398static bool isTrueWhenEqual(Instruction &I) {
1399 return I.getOpcode() == Instruction::SetEQ ||
1400 I.getOpcode() == Instruction::SetGE ||
1401 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +00001402}
1403
Chris Lattner113f4f42002-06-25 16:13:24 +00001404Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001405 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001406 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1407 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001408
1409 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001410 if (Op0 == Op1)
1411 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001412
Chris Lattnerd07283a2003-08-13 05:38:46 +00001413 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1414 if (isa<ConstantPointerNull>(Op1) &&
1415 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001416 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1417
Chris Lattnerd07283a2003-08-13 05:38:46 +00001418
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001419 // setcc's with boolean values can always be turned into bitwise operations
1420 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00001421 switch (I.getOpcode()) {
1422 default: assert(0 && "Invalid setcc instruction!");
1423 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001424 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001425 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001426 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001427 }
Chris Lattner4456da62004-08-11 00:50:51 +00001428 case Instruction::SetNE:
1429 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001430
Chris Lattner4456da62004-08-11 00:50:51 +00001431 case Instruction::SetGT:
1432 std::swap(Op0, Op1); // Change setgt -> setlt
1433 // FALL THROUGH
1434 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1435 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1436 InsertNewInstBefore(Not, I);
1437 return BinaryOperator::createAnd(Not, Op1);
1438 }
1439 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001440 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00001441 // FALL THROUGH
1442 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1443 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1444 InsertNewInstBefore(Not, I);
1445 return BinaryOperator::createOr(Not, Op1);
1446 }
1447 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001448 }
1449
Chris Lattner2dd01742004-06-09 04:24:29 +00001450 // See if we are doing a comparison between a constant and an instruction that
1451 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001452 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere1e10e12004-05-25 06:32:08 +00001453 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001454 switch (LHSI->getOpcode()) {
1455 case Instruction::And:
1456 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1457 LHSI->getOperand(0)->hasOneUse()) {
1458 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1459 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1460 // happens a LOT in code produced by the C front-end, for bitfield
1461 // access.
1462 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1463 ConstantUInt *ShAmt;
1464 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1465 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1466 const Type *Ty = LHSI->getType();
1467
1468 // We can fold this as long as we can't shift unknown bits
1469 // into the mask. This can only happen with signed shift
1470 // rights, as they sign-extend.
1471 if (ShAmt) {
1472 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
1473 Shift->getType()->isUnsigned();
1474 if (!CanFold) {
1475 // To test for the bad case of the signed shr, see if any
1476 // of the bits shifted in could be tested after the mask.
1477 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00001478 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001479 Constant *ShVal =
1480 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1481 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1482 CanFold = true;
1483 }
1484
1485 if (CanFold) {
1486 unsigned ShiftOp = Shift->getOpcode() == Instruction::Shl
1487 ? Instruction::Shr : Instruction::Shl;
1488 Constant *NewCst = ConstantExpr::get(ShiftOp, CI, ShAmt);
1489
1490 // Check to see if we are shifting out any of the bits being
1491 // compared.
1492 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1493 // If we shifted bits out, the fold is not going to work out.
1494 // As a special case, check to see if this means that the
1495 // result is always true or false now.
1496 if (I.getOpcode() == Instruction::SetEQ)
1497 return ReplaceInstUsesWith(I, ConstantBool::False);
1498 if (I.getOpcode() == Instruction::SetNE)
1499 return ReplaceInstUsesWith(I, ConstantBool::True);
1500 } else {
1501 I.setOperand(1, NewCst);
1502 LHSI->setOperand(1, ConstantExpr::get(ShiftOp, AndCST,ShAmt));
1503 LHSI->setOperand(0, Shift->getOperand(0));
1504 WorkList.push_back(Shift); // Shift is dead.
1505 AddUsesToWorkList(I);
1506 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00001507 }
1508 }
Chris Lattner35167c32004-06-09 07:59:58 +00001509 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001510 }
1511 break;
1512 case Instruction::Div:
1513 if (0 && isa<ConstantInt>(LHSI->getOperand(1))) {
1514 std::cerr << "COULD FOLD: " << *LHSI;
1515 std::cerr << "COULD FOLD: " << I << "\n";
1516 }
1517 break;
1518 case Instruction::Select:
1519 // If either operand of the select is a constant, we can fold the
1520 // comparison into the select arms, which will cause one to be
1521 // constant folded and the select turned into a bitwise or.
1522 Value *Op1 = 0, *Op2 = 0;
1523 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00001524 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00001525 // Fold the known value into the constant operand.
1526 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
1527 // Insert a new SetCC of the other select operand.
1528 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00001529 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00001530 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00001531 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00001532 // Fold the known value into the constant operand.
1533 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
1534 // Insert a new SetCC of the other select operand.
1535 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00001536 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00001537 I.getName()), I);
1538 }
Chris Lattner2dd01742004-06-09 04:24:29 +00001539 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001540
1541 if (Op1)
1542 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
1543 break;
1544 }
1545
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001546 // Simplify seteq and setne instructions...
1547 if (I.getOpcode() == Instruction::SetEQ ||
1548 I.getOpcode() == Instruction::SetNE) {
1549 bool isSetNE = I.getOpcode() == Instruction::SetNE;
1550
Chris Lattnercfbce7c2003-07-23 17:26:36 +00001551 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001552 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00001553 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1554 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00001555 case Instruction::Rem:
1556 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1557 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
1558 BO->hasOneUse() &&
1559 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
1560 if (unsigned L2 =
1561 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
1562 const Type *UTy = BO->getType()->getUnsignedVersion();
1563 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
1564 UTy, "tmp"), I);
1565 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
1566 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
1567 RHSCst, BO->getName()), I);
1568 return BinaryOperator::create(I.getOpcode(), NewRem,
1569 Constant::getNullValue(UTy));
1570 }
1571 break;
1572
Chris Lattnerc992add2003-08-13 05:33:12 +00001573 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00001574 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1575 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00001576 if (BO->hasOneUse())
1577 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1578 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00001579 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00001580 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1581 // efficiently invertible, or if the add has just this one use.
1582 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00001583
Chris Lattnerc992add2003-08-13 05:33:12 +00001584 if (Value *NegVal = dyn_castNegVal(BOp1))
1585 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1586 else if (Value *NegVal = dyn_castNegVal(BOp0))
1587 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001588 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00001589 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1590 BO->setName("");
1591 InsertNewInstBefore(Neg, I);
1592 return new SetCondInst(I.getOpcode(), BOp0, Neg);
1593 }
1594 }
1595 break;
1596 case Instruction::Xor:
1597 // For the xor case, we can xor two constants together, eliminating
1598 // the explicit xor.
1599 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1600 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001601 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00001602
1603 // FALLTHROUGH
1604 case Instruction::Sub:
1605 // Replace (([sub|xor] A, B) != 0) with (A != B)
1606 if (CI->isNullValue())
1607 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1608 BO->getOperand(1));
1609 break;
1610
1611 case Instruction::Or:
1612 // If bits are being or'd in that are not present in the constant we
1613 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001614 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001615 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001616 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001617 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001618 }
Chris Lattnerc992add2003-08-13 05:33:12 +00001619 break;
1620
1621 case Instruction::And:
1622 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001623 // If bits are being compared against that are and'd out, then the
1624 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001625 if (!ConstantExpr::getAnd(CI,
1626 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001627 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00001628
Chris Lattner35167c32004-06-09 07:59:58 +00001629 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00001630 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00001631 return new SetCondInst(isSetNE ? Instruction::SetEQ :
1632 Instruction::SetNE, Op0,
1633 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00001634
Chris Lattnerc992add2003-08-13 05:33:12 +00001635 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
1636 // to be a signed value as appropriate.
1637 if (isSignBit(BOC)) {
1638 Value *X = BO->getOperand(0);
1639 // If 'X' is not signed, insert a cast now...
1640 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001641 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerc992add2003-08-13 05:33:12 +00001642 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1643 InsertNewInstBefore(NewCI, I);
1644 X = NewCI;
1645 }
1646 return new SetCondInst(isSetNE ? Instruction::SetLT :
1647 Instruction::SetGE, X,
1648 Constant::getNullValue(X->getType()));
1649 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00001650
1651 // ((X & ~7) == 0) --> X < 7
1652 if (CI->isNullValue() && isHighOnes(BOC)) {
1653 Value *X = BO->getOperand(0);
1654 Constant *NotX = ConstantExpr::getNot(BOC);
1655
1656 // If 'X' is signed, insert a cast now.
1657 if (!NotX->getType()->isSigned()) {
1658 const Type *DestTy = NotX->getType()->getUnsignedVersion();
1659 CastInst *NewCI = new CastInst(X, DestTy, X->getName()+".uns");
1660 InsertNewInstBefore(NewCI, I);
1661 X = NewCI;
1662 NotX = ConstantExpr::getCast(NotX, DestTy);
1663 }
1664
1665 return new SetCondInst(isSetNE ? Instruction::SetGE :
1666 Instruction::SetLT, X, NotX);
1667 }
1668
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001669 }
Chris Lattnerc992add2003-08-13 05:33:12 +00001670 default: break;
1671 }
1672 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00001673 } else { // Not a SetEQ/SetNE
1674 // If the LHS is a cast from an integral value of the same size,
1675 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
1676 Value *CastOp = Cast->getOperand(0);
1677 const Type *SrcTy = CastOp->getType();
1678 unsigned SrcTySize = SrcTy->getPrimitiveSize();
1679 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
1680 SrcTySize == Cast->getType()->getPrimitiveSize()) {
1681 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
1682 "Source and destination signednesses should differ!");
1683 if (Cast->getType()->isSigned()) {
1684 // If this is a signed comparison, check for comparisons in the
1685 // vicinity of zero.
1686 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
1687 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001688 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00001689 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
1690 else if (I.getOpcode() == Instruction::SetGT &&
1691 cast<ConstantSInt>(CI)->getValue() == -1)
1692 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001693 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00001694 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
1695 } else {
1696 ConstantUInt *CUI = cast<ConstantUInt>(CI);
1697 if (I.getOpcode() == Instruction::SetLT &&
1698 CUI->getValue() == 1ULL << (SrcTySize*8-1))
1699 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001700 return BinaryOperator::createSetGT(CastOp,
1701 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00001702 else if (I.getOpcode() == Instruction::SetGT &&
1703 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
1704 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001705 return BinaryOperator::createSetLT(CastOp,
1706 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00001707 }
1708 }
1709 }
Chris Lattnere967b342003-06-04 05:10:11 +00001710 }
Chris Lattner791ac1a2003-06-01 03:35:25 +00001711
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001712 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +00001713 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001714 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1715 return ReplaceInstUsesWith(I, ConstantBool::False);
1716 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1717 return ReplaceInstUsesWith(I, ConstantBool::True);
1718 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001719 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001720 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001721 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001722
Chris Lattnere6794492002-08-12 21:17:25 +00001723 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001724 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1725 return ReplaceInstUsesWith(I, ConstantBool::False);
1726 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1727 return ReplaceInstUsesWith(I, ConstantBool::True);
1728 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001729 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001730 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001731 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001732
1733 // Comparing against a value really close to min or max?
1734 } else if (isMinValuePlusOne(CI)) {
1735 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001736 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001737 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001738 return BinaryOperator::createSetNE(Op0, SubOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001739
1740 } else if (isMaxValueMinusOne(CI)) {
1741 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001742 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001743 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001744 return BinaryOperator::createSetNE(Op0, AddOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001745 }
Chris Lattner59611142004-02-23 05:47:48 +00001746
1747 // If we still have a setle or setge instruction, turn it into the
1748 // appropriate setlt or setgt instruction. Since the border cases have
1749 // already been handled above, this requires little checking.
1750 //
1751 if (I.getOpcode() == Instruction::SetLE)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001752 return BinaryOperator::createSetLT(Op0, AddOne(CI));
Chris Lattner59611142004-02-23 05:47:48 +00001753 if (I.getOpcode() == Instruction::SetGE)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001754 return BinaryOperator::createSetGT(Op0, SubOne(CI));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001755 }
1756
Chris Lattner16930792003-11-03 04:25:02 +00001757 // Test to see if the operands of the setcc are casted versions of other
1758 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00001759 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1760 Value *CastOp0 = CI->getOperand(0);
1761 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00001762 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00001763 (I.getOpcode() == Instruction::SetEQ ||
1764 I.getOpcode() == Instruction::SetNE)) {
1765 // We keep moving the cast from the left operand over to the right
1766 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00001767 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00001768
1769 // If operand #1 is a cast instruction, see if we can eliminate it as
1770 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00001771 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
1772 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00001773 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00001774 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00001775
1776 // If Op1 is a constant, we can fold the cast into the constant.
1777 if (Op1->getType() != Op0->getType())
1778 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1779 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
1780 } else {
1781 // Otherwise, cast the RHS right before the setcc
1782 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
1783 InsertNewInstBefore(cast<Instruction>(Op1), I);
1784 }
1785 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
1786 }
1787
Chris Lattner6444c372003-11-03 05:17:03 +00001788 // Handle the special case of: setcc (cast bool to X), <cst>
1789 // This comes up when you have code like
1790 // int X = A < B;
1791 // if (X) ...
1792 // For generality, we handle any zero-extension of any operand comparison
1793 // with a constant.
1794 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
1795 const Type *SrcTy = CastOp0->getType();
1796 const Type *DestTy = Op0->getType();
1797 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
1798 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
1799 // Ok, we have an expansion of operand 0 into a new type. Get the
1800 // constant value, masink off bits which are not set in the RHS. These
1801 // could be set if the destination value is signed.
1802 uint64_t ConstVal = ConstantRHS->getRawValue();
1803 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
1804
1805 // If the constant we are comparing it with has high bits set, which
1806 // don't exist in the original value, the values could never be equal,
1807 // because the source would be zero extended.
1808 unsigned SrcBits =
1809 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00001810 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
1811 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00001812 switch (I.getOpcode()) {
1813 default: assert(0 && "Unknown comparison type!");
1814 case Instruction::SetEQ:
1815 return ReplaceInstUsesWith(I, ConstantBool::False);
1816 case Instruction::SetNE:
1817 return ReplaceInstUsesWith(I, ConstantBool::True);
1818 case Instruction::SetLT:
1819 case Instruction::SetLE:
1820 if (DestTy->isSigned() && HasSignBit)
1821 return ReplaceInstUsesWith(I, ConstantBool::False);
1822 return ReplaceInstUsesWith(I, ConstantBool::True);
1823 case Instruction::SetGT:
1824 case Instruction::SetGE:
1825 if (DestTy->isSigned() && HasSignBit)
1826 return ReplaceInstUsesWith(I, ConstantBool::True);
1827 return ReplaceInstUsesWith(I, ConstantBool::False);
1828 }
1829 }
1830
1831 // Otherwise, we can replace the setcc with a setcc of the smaller
1832 // operand value.
1833 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
1834 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
1835 }
1836 }
1837 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001838 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001839}
1840
1841
1842
Chris Lattnere8d6c602003-03-10 19:16:08 +00001843Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001844 assert(I.getOperand(1)->getType() == Type::UByteTy);
1845 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001846 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001847
1848 // shl X, 0 == X and shr X, 0 == X
1849 // shl 0, X == 0 and shr 0, X == 0
1850 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00001851 Op0 == Constant::getNullValue(Op0->getType()))
1852 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001853
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001854 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
1855 if (!isLeftShift)
1856 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1857 if (CSI->isAllOnesValue())
1858 return ReplaceInstUsesWith(I, CSI);
1859
Chris Lattner183b3362004-04-09 19:05:30 +00001860 // Try to fold constant and into select arguments.
1861 if (isa<Constant>(Op0))
1862 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1863 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1864 return R;
1865
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001866 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001867 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1868 // of a signed value.
1869 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00001870 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00001871 if (CUI->getValue() >= TypeBits) {
1872 if (!Op0->getType()->isSigned() || isLeftShift)
1873 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
1874 else {
1875 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
1876 return &I;
1877 }
1878 }
Chris Lattner55f3d942002-09-10 23:04:09 +00001879
Chris Lattnerede3fe02003-08-13 04:18:28 +00001880 // ((X*C1) << C2) == (X * (C1 << C2))
1881 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1882 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1883 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001884 return BinaryOperator::createMul(BO->getOperand(0),
1885 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00001886
Chris Lattner183b3362004-04-09 19:05:30 +00001887 // Try to fold constant and into select arguments.
1888 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1889 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1890 return R;
Chris Lattnerede3fe02003-08-13 04:18:28 +00001891
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001892 // If the operand is an bitwise operator with a constant RHS, and the
1893 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001894 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001895 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1896 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1897 bool isValid = true; // Valid only for And, Or, Xor
1898 bool highBitSet = false; // Transform if high bit of constant set?
1899
1900 switch (Op0BO->getOpcode()) {
1901 default: isValid = false; break; // Do not perform transform!
1902 case Instruction::Or:
1903 case Instruction::Xor:
1904 highBitSet = false;
1905 break;
1906 case Instruction::And:
1907 highBitSet = true;
1908 break;
1909 }
1910
1911 // If this is a signed shift right, and the high bit is modified
1912 // by the logical operation, do not perform the transformation.
1913 // The highBitSet boolean indicates the value of the high bit of
1914 // the constant which would cause it to be modified for this
1915 // operation.
1916 //
1917 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1918 uint64_t Val = Op0C->getRawValue();
1919 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1920 }
1921
1922 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001923 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001924
1925 Instruction *NewShift =
1926 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1927 Op0BO->getName());
1928 Op0BO->setName("");
1929 InsertNewInstBefore(NewShift, I);
1930
1931 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1932 NewRHS);
1933 }
1934 }
1935
Chris Lattner3204d4e2003-07-24 17:52:58 +00001936 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001937 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00001938 if (ConstantUInt *ShiftAmt1C =
1939 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001940 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1941 unsigned ShiftAmt2 = CUI->getValue();
1942
1943 // Check for (A << c1) << c2 and (A >> c1) >> c2
1944 if (I.getOpcode() == Op0SI->getOpcode()) {
1945 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00001946 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
1947 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00001948 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1949 ConstantUInt::get(Type::UByteTy, Amt));
1950 }
1951
Chris Lattnerab780df2003-07-24 18:38:56 +00001952 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1953 // signed types, we can only support the (A >> c1) << c2 configuration,
1954 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001955 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001956 // Calculate bitmask for what gets shifted off the edge...
1957 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001958 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001959 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001960 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001961 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00001962
1963 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001964 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
1965 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00001966 InsertNewInstBefore(Mask, I);
1967
1968 // Figure out what flavor of shift we should use...
1969 if (ShiftAmt1 == ShiftAmt2)
1970 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
1971 else if (ShiftAmt1 < ShiftAmt2) {
1972 return new ShiftInst(I.getOpcode(), Mask,
1973 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1974 } else {
1975 return new ShiftInst(Op0SI->getOpcode(), Mask,
1976 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1977 }
1978 }
1979 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001980 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00001981
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001982 return 0;
1983}
1984
Chris Lattner4e2dbc62004-07-20 00:59:32 +00001985enum CastType {
1986 Noop = 0,
1987 Truncate = 1,
1988 Signext = 2,
1989 Zeroext = 3
1990};
1991
1992/// getCastType - In the future, we will split the cast instruction into these
1993/// various types. Until then, we have to do the analysis here.
1994static CastType getCastType(const Type *Src, const Type *Dest) {
1995 assert(Src->isIntegral() && Dest->isIntegral() &&
1996 "Only works on integral types!");
1997 unsigned SrcSize = Src->getPrimitiveSize()*8;
1998 if (Src == Type::BoolTy) SrcSize = 1;
1999 unsigned DestSize = Dest->getPrimitiveSize()*8;
2000 if (Dest == Type::BoolTy) DestSize = 1;
2001
2002 if (SrcSize == DestSize) return Noop;
2003 if (SrcSize > DestSize) return Truncate;
2004 if (Src->isSigned()) return Signext;
2005 return Zeroext;
2006}
2007
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002008
Chris Lattner48a44f72002-05-02 17:06:02 +00002009// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2010// instruction.
2011//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002012static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00002013 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002014
Chris Lattner650b6da2002-08-02 20:00:25 +00002015 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2016 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00002017 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00002018 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00002019 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00002020
Chris Lattner4fbad962004-07-21 04:27:24 +00002021 // If we are casting between pointer and integer types, treat pointers as
2022 // integers of the appropriate size for the code below.
2023 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2024 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2025 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00002026
Chris Lattner48a44f72002-05-02 17:06:02 +00002027 // Allow free casting and conversion of sizes as long as the sign doesn't
2028 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002029 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002030 CastType FirstCast = getCastType(SrcTy, MidTy);
2031 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00002032
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002033 // Capture the effect of these two casts. If the result is a legal cast,
2034 // the CastType is stored here, otherwise a special code is used.
2035 static const unsigned CastResult[] = {
2036 // First cast is noop
2037 0, 1, 2, 3,
2038 // First cast is a truncate
2039 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2040 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00002041 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002042 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00002043 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002044 };
2045
2046 unsigned Result = CastResult[FirstCast*4+SecondCast];
2047 switch (Result) {
2048 default: assert(0 && "Illegal table value!");
2049 case 0:
2050 case 1:
2051 case 2:
2052 case 3:
2053 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2054 // truncates, we could eliminate more casts.
2055 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2056 case 4:
2057 return false; // Not possible to eliminate this here.
2058 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00002059 // Sign or zero extend followed by truncate is always ok if the result
2060 // is a truncate or noop.
2061 CastType ResultCast = getCastType(SrcTy, DstTy);
2062 if (ResultCast == Noop || ResultCast == Truncate)
2063 return true;
2064 // Otherwise we are still growing the value, we are only safe if the
2065 // result will match the sign/zeroextendness of the result.
2066 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00002067 }
Chris Lattner650b6da2002-08-02 20:00:25 +00002068 }
Chris Lattner48a44f72002-05-02 17:06:02 +00002069 return false;
2070}
2071
Chris Lattner11ffd592004-07-20 05:21:00 +00002072static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002073 if (V->getType() == Ty || isa<Constant>(V)) return false;
2074 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00002075 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2076 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002077 return false;
2078 return true;
2079}
2080
2081/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2082/// InsertBefore instruction. This is specialized a bit to avoid inserting
2083/// casts that are known to not do anything...
2084///
2085Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2086 Instruction *InsertBefore) {
2087 if (V->getType() == DestTy) return V;
2088 if (Constant *C = dyn_cast<Constant>(V))
2089 return ConstantExpr::getCast(C, DestTy);
2090
2091 CastInst *CI = new CastInst(V, DestTy, V->getName());
2092 InsertNewInstBefore(CI, *InsertBefore);
2093 return CI;
2094}
Chris Lattner48a44f72002-05-02 17:06:02 +00002095
2096// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002097//
Chris Lattner113f4f42002-06-25 16:13:24 +00002098Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002099 Value *Src = CI.getOperand(0);
2100
Chris Lattner48a44f72002-05-02 17:06:02 +00002101 // If the user is casting a value to the same type, eliminate this cast
2102 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002103 if (CI.getType() == Src->getType())
2104 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002105
Chris Lattner48a44f72002-05-02 17:06:02 +00002106 // If casting the result of another cast instruction, try to eliminate this
2107 // one!
2108 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002109 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002110 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner11ffd592004-07-20 05:21:00 +00002111 CSrc->getType(), CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002112 // This instruction now refers directly to the cast's src operand. This
2113 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002114 CI.setOperand(0, CSrc->getOperand(0));
2115 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002116 }
2117
Chris Lattner650b6da2002-08-02 20:00:25 +00002118 // If this is an A->B->A cast, and we are dealing with integral types, try
2119 // to convert this into a logical 'and' instruction.
2120 //
2121 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002122 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002123 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2124 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2125 assert(CSrc->getType() != Type::ULongTy &&
2126 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002127 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002128 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002129 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002130 }
2131 }
2132
Chris Lattner03841652004-05-25 04:29:21 +00002133 // If this is a cast to bool, turn it into the appropriate setne instruction.
2134 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002135 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002136 Constant::getNullValue(CI.getOperand(0)->getType()));
2137
Chris Lattnerd0d51602003-06-21 23:12:02 +00002138 // If casting the result of a getelementptr instruction with no offset, turn
2139 // this into a cast of the original pointer!
2140 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002141 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002142 bool AllZeroOperands = true;
2143 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2144 if (!isa<Constant>(GEP->getOperand(i)) ||
2145 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2146 AllZeroOperands = false;
2147 break;
2148 }
2149 if (AllZeroOperands) {
2150 CI.setOperand(0, GEP->getOperand(0));
2151 return &CI;
2152 }
2153 }
2154
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002155 // If we are casting a malloc or alloca to a pointer to a type of the same
2156 // size, rewrite the allocation instruction to allocate the "right" type.
2157 //
2158 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002159 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002160 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2161 // Get the type really allocated and the type casted to...
2162 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002163 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002164 if (AllocElTy->isSized() && CastElTy->isSized()) {
2165 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2166 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002167
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002168 // If the allocation is for an even multiple of the cast type size
2169 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2170 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002171 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002172 std::string Name = AI->getName(); AI->setName("");
2173 AllocationInst *New;
2174 if (isa<MallocInst>(AI))
2175 New = new MallocInst(CastElTy, Amt, Name);
2176 else
2177 New = new AllocaInst(CastElTy, Amt, Name);
2178 InsertNewInstBefore(New, *AI);
2179 return ReplaceInstUsesWith(CI, New);
2180 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002181 }
2182 }
2183
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002184 // If the source value is an instruction with only this use, we can attempt to
2185 // propagate the cast into the instruction. Also, only handle integral types
2186 // for now.
2187 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002188 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002189 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2190 const Type *DestTy = CI.getType();
2191 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2192 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2193
2194 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2195 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2196
2197 switch (SrcI->getOpcode()) {
2198 case Instruction::Add:
2199 case Instruction::Mul:
2200 case Instruction::And:
2201 case Instruction::Or:
2202 case Instruction::Xor:
2203 // If we are discarding information, or just changing the sign, rewrite.
2204 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2205 // Don't insert two casts if they cannot be eliminated. We allow two
2206 // casts to be inserted if the sizes are the same. This could only be
2207 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00002208 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2209 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002210 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2211 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2212 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2213 ->getOpcode(), Op0c, Op1c);
2214 }
2215 }
2216 break;
2217 case Instruction::Shl:
2218 // Allow changing the sign of the source operand. Do not allow changing
2219 // the size of the shift, UNLESS the shift amount is a constant. We
2220 // mush not change variable sized shifts to a smaller size, because it
2221 // is undefined to shift more bits out than exist in the value.
2222 if (DestBitSize == SrcBitSize ||
2223 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2224 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2225 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2226 }
2227 break;
2228 }
2229 }
2230
Chris Lattner260ab202002-04-18 17:39:14 +00002231 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00002232}
2233
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002234/// GetSelectFoldableOperands - We want to turn code that looks like this:
2235/// %C = or %A, %B
2236/// %D = select %cond, %C, %A
2237/// into:
2238/// %C = select %cond, %B, 0
2239/// %D = or %A, %C
2240///
2241/// Assuming that the specified instruction is an operand to the select, return
2242/// a bitmask indicating which operands of this instruction are foldable if they
2243/// equal the other incoming value of the select.
2244///
2245static unsigned GetSelectFoldableOperands(Instruction *I) {
2246 switch (I->getOpcode()) {
2247 case Instruction::Add:
2248 case Instruction::Mul:
2249 case Instruction::And:
2250 case Instruction::Or:
2251 case Instruction::Xor:
2252 return 3; // Can fold through either operand.
2253 case Instruction::Sub: // Can only fold on the amount subtracted.
2254 case Instruction::Shl: // Can only fold on the shift amount.
2255 case Instruction::Shr:
2256 return 1;
2257 default:
2258 return 0; // Cannot fold
2259 }
2260}
2261
2262/// GetSelectFoldableConstant - For the same transformation as the previous
2263/// function, return the identity constant that goes into the select.
2264static Constant *GetSelectFoldableConstant(Instruction *I) {
2265 switch (I->getOpcode()) {
2266 default: assert(0 && "This cannot happen!"); abort();
2267 case Instruction::Add:
2268 case Instruction::Sub:
2269 case Instruction::Or:
2270 case Instruction::Xor:
2271 return Constant::getNullValue(I->getType());
2272 case Instruction::Shl:
2273 case Instruction::Shr:
2274 return Constant::getNullValue(Type::UByteTy);
2275 case Instruction::And:
2276 return ConstantInt::getAllOnesValue(I->getType());
2277 case Instruction::Mul:
2278 return ConstantInt::get(I->getType(), 1);
2279 }
2280}
2281
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002282Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00002283 Value *CondVal = SI.getCondition();
2284 Value *TrueVal = SI.getTrueValue();
2285 Value *FalseVal = SI.getFalseValue();
2286
2287 // select true, X, Y -> X
2288 // select false, X, Y -> Y
2289 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002290 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00002291 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002292 else {
2293 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00002294 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002295 }
Chris Lattner533bc492004-03-30 19:37:13 +00002296
2297 // select C, X, X -> X
2298 if (TrueVal == FalseVal)
2299 return ReplaceInstUsesWith(SI, TrueVal);
2300
Chris Lattner1c631e82004-04-08 04:43:23 +00002301 if (SI.getType() == Type::BoolTy)
2302 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2303 if (C == ConstantBool::True) {
2304 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002305 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002306 } else {
2307 // Change: A = select B, false, C --> A = and !B, C
2308 Value *NotCond =
2309 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2310 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002311 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002312 }
2313 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2314 if (C == ConstantBool::False) {
2315 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002316 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002317 } else {
2318 // Change: A = select B, C, true --> A = or !B, C
2319 Value *NotCond =
2320 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2321 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002322 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002323 }
2324 }
2325
Chris Lattner183b3362004-04-09 19:05:30 +00002326 // Selecting between two integer constants?
2327 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2328 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2329 // select C, 1, 0 -> cast C to int
2330 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2331 return new CastInst(CondVal, SI.getType());
2332 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2333 // select C, 0, 1 -> cast !C to int
2334 Value *NotCond =
2335 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00002336 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00002337 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00002338 }
Chris Lattner35167c32004-06-09 07:59:58 +00002339
2340 // If one of the constants is zero (we know they can't both be) and we
2341 // have a setcc instruction with zero, and we have an 'and' with the
2342 // non-constant value, eliminate this whole mess. This corresponds to
2343 // cases like this: ((X & 27) ? 27 : 0)
2344 if (TrueValC->isNullValue() || FalseValC->isNullValue())
2345 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
2346 if ((IC->getOpcode() == Instruction::SetEQ ||
2347 IC->getOpcode() == Instruction::SetNE) &&
2348 isa<ConstantInt>(IC->getOperand(1)) &&
2349 cast<Constant>(IC->getOperand(1))->isNullValue())
2350 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
2351 if (ICA->getOpcode() == Instruction::And &&
2352 isa<ConstantInt>(ICA->getOperand(1)) &&
2353 (ICA->getOperand(1) == TrueValC ||
2354 ICA->getOperand(1) == FalseValC) &&
2355 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
2356 // Okay, now we know that everything is set up, we just don't
2357 // know whether we have a setne or seteq and whether the true or
2358 // false val is the zero.
2359 bool ShouldNotVal = !TrueValC->isNullValue();
2360 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
2361 Value *V = ICA;
2362 if (ShouldNotVal)
2363 V = InsertNewInstBefore(BinaryOperator::create(
2364 Instruction::Xor, V, ICA->getOperand(1)), SI);
2365 return ReplaceInstUsesWith(SI, V);
2366 }
Chris Lattner533bc492004-03-30 19:37:13 +00002367 }
Chris Lattner623fba12004-04-10 22:21:27 +00002368
2369 // See if we are selecting two values based on a comparison of the two values.
2370 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
2371 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
2372 // Transform (X == Y) ? X : Y -> Y
2373 if (SCI->getOpcode() == Instruction::SetEQ)
2374 return ReplaceInstUsesWith(SI, FalseVal);
2375 // Transform (X != Y) ? X : Y -> X
2376 if (SCI->getOpcode() == Instruction::SetNE)
2377 return ReplaceInstUsesWith(SI, TrueVal);
2378 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2379
2380 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
2381 // Transform (X == Y) ? Y : X -> X
2382 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00002383 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00002384 // Transform (X != Y) ? Y : X -> Y
2385 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00002386 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00002387 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2388 }
2389 }
Chris Lattner1c631e82004-04-08 04:43:23 +00002390
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002391 // See if we can fold the select into one of our operands.
2392 if (SI.getType()->isInteger()) {
2393 // See the comment above GetSelectFoldableOperands for a description of the
2394 // transformation we are doing here.
2395 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
2396 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
2397 !isa<Constant>(FalseVal))
2398 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
2399 unsigned OpToFold = 0;
2400 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
2401 OpToFold = 1;
2402 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
2403 OpToFold = 2;
2404 }
2405
2406 if (OpToFold) {
2407 Constant *C = GetSelectFoldableConstant(TVI);
2408 std::string Name = TVI->getName(); TVI->setName("");
2409 Instruction *NewSel =
2410 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
2411 Name);
2412 InsertNewInstBefore(NewSel, SI);
2413 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
2414 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
2415 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
2416 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
2417 else {
2418 assert(0 && "Unknown instruction!!");
2419 }
2420 }
2421 }
2422
2423 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
2424 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
2425 !isa<Constant>(TrueVal))
2426 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
2427 unsigned OpToFold = 0;
2428 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
2429 OpToFold = 1;
2430 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
2431 OpToFold = 2;
2432 }
2433
2434 if (OpToFold) {
2435 Constant *C = GetSelectFoldableConstant(FVI);
2436 std::string Name = FVI->getName(); FVI->setName("");
2437 Instruction *NewSel =
2438 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
2439 Name);
2440 InsertNewInstBefore(NewSel, SI);
2441 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
2442 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
2443 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
2444 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
2445 else {
2446 assert(0 && "Unknown instruction!!");
2447 }
2448 }
2449 }
2450 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002451 return 0;
2452}
2453
2454
Chris Lattner970c33a2003-06-19 17:00:31 +00002455// CallInst simplification
2456//
2457Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00002458 // Intrinsics cannot occur in an invoke, so handle them here instead of in
2459 // visitCallSite.
2460 if (Function *F = CI.getCalledFunction())
2461 switch (F->getIntrinsicID()) {
2462 case Intrinsic::memmove:
2463 case Intrinsic::memcpy:
2464 case Intrinsic::memset:
2465 // memmove/cpy/set of zero bytes is a noop.
2466 if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
2467 if (NumBytes->isNullValue())
2468 return EraseInstFromFunction(CI);
2469 }
2470 break;
2471 default:
2472 break;
2473 }
2474
Chris Lattneraec3d942003-10-07 22:32:43 +00002475 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00002476}
2477
2478// InvokeInst simplification
2479//
2480Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00002481 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00002482}
2483
Chris Lattneraec3d942003-10-07 22:32:43 +00002484// visitCallSite - Improvements for call and invoke instructions.
2485//
2486Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002487 bool Changed = false;
2488
2489 // If the callee is a constexpr cast of a function, attempt to move the cast
2490 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00002491 if (transformConstExprCastCall(CS)) return 0;
2492
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002493 Value *Callee = CS.getCalledValue();
2494 const PointerType *PTy = cast<PointerType>(Callee->getType());
2495 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2496 if (FTy->isVarArg()) {
2497 // See if we can optimize any arguments passed through the varargs area of
2498 // the call.
2499 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
2500 E = CS.arg_end(); I != E; ++I)
2501 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
2502 // If this cast does not effect the value passed through the varargs
2503 // area, we can eliminate the use of the cast.
2504 Value *Op = CI->getOperand(0);
2505 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
2506 *I = Op;
2507 Changed = true;
2508 }
2509 }
2510 }
Chris Lattneraec3d942003-10-07 22:32:43 +00002511
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002512 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00002513}
2514
Chris Lattner970c33a2003-06-19 17:00:31 +00002515// transformConstExprCastCall - If the callee is a constexpr cast of a function,
2516// attempt to move the cast to the arguments of the call/invoke.
2517//
2518bool InstCombiner::transformConstExprCastCall(CallSite CS) {
2519 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
2520 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00002521 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00002522 return false;
Reid Spencer87436872004-07-18 00:38:32 +00002523 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00002524 Instruction *Caller = CS.getInstruction();
2525
2526 // Okay, this is a cast from a function to a different type. Unless doing so
2527 // would cause a type conversion of one of our arguments, change this call to
2528 // be a direct call with arguments casted to the appropriate types.
2529 //
2530 const FunctionType *FT = Callee->getFunctionType();
2531 const Type *OldRetTy = Caller->getType();
2532
Chris Lattner1f7942f2004-01-14 06:06:08 +00002533 // Check to see if we are changing the return type...
2534 if (OldRetTy != FT->getReturnType()) {
2535 if (Callee->isExternal() &&
2536 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
2537 !Caller->use_empty())
2538 return false; // Cannot transform this return value...
2539
2540 // If the callsite is an invoke instruction, and the return value is used by
2541 // a PHI node in a successor, we cannot change the return type of the call
2542 // because there is no place to put the cast instruction (without breaking
2543 // the critical edge). Bail out in this case.
2544 if (!Caller->use_empty())
2545 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
2546 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
2547 UI != E; ++UI)
2548 if (PHINode *PN = dyn_cast<PHINode>(*UI))
2549 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00002550 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00002551 return false;
2552 }
Chris Lattner970c33a2003-06-19 17:00:31 +00002553
2554 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
2555 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2556
2557 CallSite::arg_iterator AI = CS.arg_begin();
2558 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
2559 const Type *ParamTy = FT->getParamType(i);
2560 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
2561 if (Callee->isExternal() && !isConvertible) return false;
2562 }
2563
2564 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
2565 Callee->isExternal())
2566 return false; // Do not delete arguments unless we have a function body...
2567
2568 // Okay, we decided that this is a safe thing to do: go ahead and start
2569 // inserting cast instructions as necessary...
2570 std::vector<Value*> Args;
2571 Args.reserve(NumActualArgs);
2572
2573 AI = CS.arg_begin();
2574 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
2575 const Type *ParamTy = FT->getParamType(i);
2576 if ((*AI)->getType() == ParamTy) {
2577 Args.push_back(*AI);
2578 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00002579 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
2580 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00002581 }
2582 }
2583
2584 // If the function takes more arguments than the call was taking, add them
2585 // now...
2586 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2587 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2588
2589 // If we are removing arguments to the function, emit an obnoxious warning...
2590 if (FT->getNumParams() < NumActualArgs)
2591 if (!FT->isVarArg()) {
2592 std::cerr << "WARNING: While resolving call to function '"
2593 << Callee->getName() << "' arguments were dropped!\n";
2594 } else {
2595 // Add all of the arguments in their promoted form to the arg list...
2596 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
2597 const Type *PTy = getPromotedType((*AI)->getType());
2598 if (PTy != (*AI)->getType()) {
2599 // Must promote to pass through va_arg area!
2600 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
2601 InsertNewInstBefore(Cast, *Caller);
2602 Args.push_back(Cast);
2603 } else {
2604 Args.push_back(*AI);
2605 }
2606 }
2607 }
2608
2609 if (FT->getReturnType() == Type::VoidTy)
2610 Caller->setName(""); // Void type should not have a name...
2611
2612 Instruction *NC;
2613 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00002614 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00002615 Args, Caller->getName(), Caller);
2616 } else {
2617 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
2618 }
2619
2620 // Insert a cast of the return type as necessary...
2621 Value *NV = NC;
2622 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
2623 if (NV->getType() != Type::VoidTy) {
2624 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00002625
2626 // If this is an invoke instruction, we should insert it after the first
2627 // non-phi, instruction in the normal successor block.
2628 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
2629 BasicBlock::iterator I = II->getNormalDest()->begin();
2630 while (isa<PHINode>(I)) ++I;
2631 InsertNewInstBefore(NC, *I);
2632 } else {
2633 // Otherwise, it's a call, just insert cast right after the call instr
2634 InsertNewInstBefore(NC, *Caller);
2635 }
Chris Lattner51ea1272004-02-28 05:22:00 +00002636 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00002637 } else {
2638 NV = Constant::getNullValue(Caller->getType());
2639 }
2640 }
2641
2642 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
2643 Caller->replaceAllUsesWith(NV);
2644 Caller->getParent()->getInstList().erase(Caller);
2645 removeFromWorkList(Caller);
2646 return true;
2647}
2648
2649
Chris Lattner48a44f72002-05-02 17:06:02 +00002650
Chris Lattnerbbbdd852002-05-06 18:06:38 +00002651// PHINode simplification
2652//
Chris Lattner113f4f42002-06-25 16:13:24 +00002653Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner91daeb52003-12-19 05:58:40 +00002654 if (Value *V = hasConstantValue(&PN))
2655 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00002656
2657 // If the only user of this instruction is a cast instruction, and all of the
2658 // incoming values are constants, change this PHI to merge together the casted
2659 // constants.
2660 if (PN.hasOneUse())
2661 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
2662 if (CI->getType() != PN.getType()) { // noop casts will be folded
2663 bool AllConstant = true;
2664 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2665 if (!isa<Constant>(PN.getIncomingValue(i))) {
2666 AllConstant = false;
2667 break;
2668 }
2669 if (AllConstant) {
2670 // Make a new PHI with all casted values.
2671 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
2672 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2673 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
2674 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
2675 PN.getIncomingBlock(i));
2676 }
2677
2678 // Update the cast instruction.
2679 CI->setOperand(0, New);
2680 WorkList.push_back(CI); // revisit the cast instruction to fold.
2681 WorkList.push_back(New); // Make sure to revisit the new Phi
2682 return &PN; // PN is now dead!
2683 }
2684 }
Chris Lattner91daeb52003-12-19 05:58:40 +00002685 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00002686}
2687
Chris Lattner69193f92004-04-05 01:30:19 +00002688static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
2689 Instruction *InsertPoint,
2690 InstCombiner *IC) {
2691 unsigned PS = IC->getTargetData().getPointerSize();
2692 const Type *VTy = V->getType();
2693 Instruction *Cast;
2694 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
2695 // We must insert a cast to ensure we sign-extend.
2696 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
2697 V->getName()), *InsertPoint);
2698 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
2699 *InsertPoint);
2700}
2701
Chris Lattner48a44f72002-05-02 17:06:02 +00002702
Chris Lattner113f4f42002-06-25 16:13:24 +00002703Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00002704 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00002705 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00002706 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002707 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00002708 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002709
2710 bool HasZeroPointerIndex = false;
2711 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
2712 HasZeroPointerIndex = C->isNullValue();
2713
2714 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00002715 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00002716
Chris Lattner69193f92004-04-05 01:30:19 +00002717 // Eliminate unneeded casts for indices.
2718 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00002719 gep_type_iterator GTI = gep_type_begin(GEP);
2720 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
2721 if (isa<SequentialType>(*GTI)) {
2722 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
2723 Value *Src = CI->getOperand(0);
2724 const Type *SrcTy = Src->getType();
2725 const Type *DestTy = CI->getType();
2726 if (Src->getType()->isInteger()) {
2727 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
2728 // We can always eliminate a cast from ulong or long to the other.
2729 // We can always eliminate a cast from uint to int or the other on
2730 // 32-bit pointer platforms.
2731 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
2732 MadeChange = true;
2733 GEP.setOperand(i, Src);
2734 }
2735 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2736 SrcTy->getPrimitiveSize() == 4) {
2737 // We can always eliminate a cast from int to [u]long. We can
2738 // eliminate a cast from uint to [u]long iff the target is a 32-bit
2739 // pointer target.
2740 if (SrcTy->isSigned() ||
2741 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
2742 MadeChange = true;
2743 GEP.setOperand(i, Src);
2744 }
Chris Lattner69193f92004-04-05 01:30:19 +00002745 }
2746 }
2747 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00002748 // If we are using a wider index than needed for this platform, shrink it
2749 // to what we need. If the incoming value needs a cast instruction,
2750 // insert it. This explicit cast can make subsequent optimizations more
2751 // obvious.
2752 Value *Op = GEP.getOperand(i);
2753 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00002754 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00002755 GEP.setOperand(i, ConstantExpr::getCast(C,
2756 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00002757 MadeChange = true;
2758 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00002759 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
2760 Op->getName()), GEP);
2761 GEP.setOperand(i, Op);
2762 MadeChange = true;
2763 }
Chris Lattner44d0b952004-07-20 01:48:15 +00002764
2765 // If this is a constant idx, make sure to canonicalize it to be a signed
2766 // operand, otherwise CSE and other optimizations are pessimized.
2767 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
2768 GEP.setOperand(i, ConstantExpr::getCast(CUI,
2769 CUI->getType()->getSignedVersion()));
2770 MadeChange = true;
2771 }
Chris Lattner69193f92004-04-05 01:30:19 +00002772 }
2773 if (MadeChange) return &GEP;
2774
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002775 // Combine Indices - If the source pointer to this getelementptr instruction
2776 // is a getelementptr instruction, combine the indices of the two
2777 // getelementptr instructions into a single instruction.
2778 //
Chris Lattner57c67b02004-03-25 22:59:29 +00002779 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00002780 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00002781 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00002782 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00002783 if (CE->getOpcode() == Instruction::GetElementPtr)
2784 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
2785 }
2786
2787 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00002788 // Note that if our source is a gep chain itself that we wait for that
2789 // chain to be resolved before we perform this transformation. This
2790 // avoids us creating a TON of code in some cases.
2791 //
2792 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
2793 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
2794 return 0; // Wait until our source is folded to completion.
2795
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002796 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00002797
2798 // Find out whether the last index in the source GEP is a sequential idx.
2799 bool EndsWithSequential = false;
2800 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
2801 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00002802 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00002803
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002804 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00002805 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00002806 // Replace: gep (gep %P, long B), long A, ...
2807 // With: T = long A+B; gep %P, T, ...
2808 //
Chris Lattner5f667a62004-05-07 22:09:22 +00002809 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00002810 if (SO1 == Constant::getNullValue(SO1->getType())) {
2811 Sum = GO1;
2812 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
2813 Sum = SO1;
2814 } else {
2815 // If they aren't the same type, convert both to an integer of the
2816 // target's pointer size.
2817 if (SO1->getType() != GO1->getType()) {
2818 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
2819 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
2820 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
2821 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
2822 } else {
2823 unsigned PS = TD->getPointerSize();
2824 Instruction *Cast;
2825 if (SO1->getType()->getPrimitiveSize() == PS) {
2826 // Convert GO1 to SO1's type.
2827 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
2828
2829 } else if (GO1->getType()->getPrimitiveSize() == PS) {
2830 // Convert SO1 to GO1's type.
2831 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
2832 } else {
2833 const Type *PT = TD->getIntPtrType();
2834 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
2835 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
2836 }
2837 }
2838 }
Chris Lattner5f667a62004-05-07 22:09:22 +00002839 if (isa<Constant>(SO1) && isa<Constant>(GO1))
2840 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
2841 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002842 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
2843 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00002844 }
Chris Lattner69193f92004-04-05 01:30:19 +00002845 }
Chris Lattner5f667a62004-05-07 22:09:22 +00002846
2847 // Recycle the GEP we already have if possible.
2848 if (SrcGEPOperands.size() == 2) {
2849 GEP.setOperand(0, SrcGEPOperands[0]);
2850 GEP.setOperand(1, Sum);
2851 return &GEP;
2852 } else {
2853 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2854 SrcGEPOperands.end()-1);
2855 Indices.push_back(Sum);
2856 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
2857 }
Chris Lattner69193f92004-04-05 01:30:19 +00002858 } else if (isa<Constant>(*GEP.idx_begin()) &&
2859 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00002860 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002861 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00002862 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2863 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002864 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
2865 }
2866
2867 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00002868 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002869
Chris Lattner5f667a62004-05-07 22:09:22 +00002870 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002871 // GEP of global variable. If all of the indices for this GEP are
2872 // constants, we can promote this to a constexpr instead of an instruction.
2873
2874 // Scan for nonconstants...
2875 std::vector<Constant*> Indices;
2876 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
2877 for (; I != E && isa<Constant>(*I); ++I)
2878 Indices.push_back(cast<Constant>(*I));
2879
2880 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00002881 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002882
2883 // Replace all uses of the GEP with the new constexpr...
2884 return ReplaceInstUsesWith(GEP, CE);
2885 }
Chris Lattner5f667a62004-05-07 22:09:22 +00002886 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002887 if (CE->getOpcode() == Instruction::Cast) {
2888 if (HasZeroPointerIndex) {
2889 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
2890 // into : GEP [10 x ubyte]* X, long 0, ...
2891 //
2892 // This occurs when the program declares an array extern like "int X[];"
2893 //
2894 Constant *X = CE->getOperand(0);
2895 const PointerType *CPTy = cast<PointerType>(CE->getType());
2896 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
2897 if (const ArrayType *XATy =
2898 dyn_cast<ArrayType>(XTy->getElementType()))
2899 if (const ArrayType *CATy =
2900 dyn_cast<ArrayType>(CPTy->getElementType()))
2901 if (CATy->getElementType() == XATy->getElementType()) {
2902 // At this point, we know that the cast source type is a pointer
2903 // to an array of the same type as the destination pointer
2904 // array. Because the array type is never stepped over (there
2905 // is a leading zero) we can fold the cast into this GEP.
2906 GEP.setOperand(0, X);
2907 return &GEP;
2908 }
2909 }
2910 }
Chris Lattnerca081252001-12-14 16:52:21 +00002911 }
2912
Chris Lattnerca081252001-12-14 16:52:21 +00002913 return 0;
2914}
2915
Chris Lattner1085bdf2002-11-04 16:18:53 +00002916Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
2917 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
2918 if (AI.isArrayAllocation()) // Check C != 1
2919 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
2920 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00002921 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00002922
2923 // Create and insert the replacement instruction...
2924 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00002925 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00002926 else {
2927 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00002928 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00002929 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00002930
2931 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00002932
2933 // Scan to the end of the allocation instructions, to skip over a block of
2934 // allocas if possible...
2935 //
2936 BasicBlock::iterator It = New;
2937 while (isa<AllocationInst>(*It)) ++It;
2938
2939 // Now that I is pointing to the first non-allocation-inst in the block,
2940 // insert our getelementptr instruction...
2941 //
Chris Lattner69193f92004-04-05 01:30:19 +00002942 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00002943 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
2944
2945 // Now make everything use the getelementptr instead of the original
2946 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00002947 return ReplaceInstUsesWith(AI, V);
Chris Lattner1085bdf2002-11-04 16:18:53 +00002948 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00002949
2950 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
2951 // Note that we only do this for alloca's, because malloc should allocate and
2952 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00002953 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
2954 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00002955 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
2956
Chris Lattner1085bdf2002-11-04 16:18:53 +00002957 return 0;
2958}
2959
Chris Lattner8427bff2003-12-07 01:24:23 +00002960Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
2961 Value *Op = FI.getOperand(0);
2962
2963 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
2964 if (CastInst *CI = dyn_cast<CastInst>(Op))
2965 if (isa<PointerType>(CI->getOperand(0)->getType())) {
2966 FI.setOperand(0, CI->getOperand(0));
2967 return &FI;
2968 }
2969
Chris Lattnerf3a36602004-02-28 04:57:37 +00002970 // If we have 'free null' delete the instruction. This can happen in stl code
2971 // when lots of inlining happens.
Chris Lattner51ea1272004-02-28 05:22:00 +00002972 if (isa<ConstantPointerNull>(Op))
2973 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00002974
Chris Lattner8427bff2003-12-07 01:24:23 +00002975 return 0;
2976}
2977
2978
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002979/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
2980/// constantexpr, return the constant value being addressed by the constant
2981/// expression, or null if something is funny.
2982///
2983static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00002984 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002985 return 0; // Do not allow stepping over the value!
2986
2987 // Loop over all of the operands, tracking down which value we are
2988 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00002989 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2990 for (++I; I != E; ++I)
2991 if (const StructType *STy = dyn_cast<StructType>(*I)) {
2992 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
2993 assert(CU->getValue() < STy->getNumElements() &&
2994 "Struct index out of range!");
2995 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos83243722004-08-04 08:44:43 +00002996 C = CS->getOperand(CU->getValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00002997 } else if (isa<ConstantAggregateZero>(C)) {
2998 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
2999 } else {
3000 return 0;
3001 }
3002 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3003 const ArrayType *ATy = cast<ArrayType>(*I);
3004 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3005 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003006 C = CA->getOperand(CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003007 else if (isa<ConstantAggregateZero>(C))
3008 C = Constant::getNullValue(ATy->getElementType());
3009 else
3010 return 0;
3011 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003012 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00003013 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003014 return C;
3015}
3016
Chris Lattner35e24772004-07-13 01:49:43 +00003017static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3018 User *CI = cast<User>(LI.getOperand(0));
3019
3020 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3021 if (const PointerType *SrcTy =
3022 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3023 const Type *SrcPTy = SrcTy->getElementType();
3024 if (SrcPTy->isSized() && DestPTy->isSized() &&
3025 IC.getTargetData().getTypeSize(SrcPTy) ==
3026 IC.getTargetData().getTypeSize(DestPTy) &&
3027 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3028 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3029 // Okay, we are casting from one integer or pointer type to another of
3030 // the same size. Instead of casting the pointer before the load, cast
3031 // the result of the loaded value.
3032 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003033 CI->getName(),
3034 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00003035 // Now cast the result of the load.
3036 return new CastInst(NewLoad, LI.getType());
3037 }
3038 }
3039 return 0;
3040}
3041
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003042/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00003043/// from this value cannot trap. If it is not obviously safe to load from the
3044/// specified pointer, we do a quick local scan of the basic block containing
3045/// ScanFrom, to determine if the address is already accessed.
3046static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3047 // If it is an alloca or global variable, it is always safe to load from.
3048 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3049
3050 // Otherwise, be a little bit agressive by scanning the local block where we
3051 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003052 // from/to. If so, the previous load or store would have already trapped,
3053 // so there is no harm doing an extra load (also, CSE will later eliminate
3054 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00003055 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3056
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003057 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00003058 --BBI;
3059
3060 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3061 if (LI->getOperand(0) == V) return true;
3062 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3063 if (SI->getOperand(1) == V) return true;
3064
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003065 }
Chris Lattnere6f13092004-09-19 19:18:10 +00003066 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003067}
3068
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003069Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3070 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00003071
Chris Lattner6679e462004-04-14 03:28:36 +00003072 if (Constant *C = dyn_cast<Constant>(Op))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003073 if (C->isNullValue() && !LI.isVolatile()) // load null -> 0
Chris Lattner6679e462004-04-14 03:28:36 +00003074 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003075
3076 // Instcombine load (constant global) into the value loaded...
3077 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00003078 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003079 return ReplaceInstUsesWith(LI, GV->getInitializer());
3080
3081 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
3082 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
Chris Lattner35e24772004-07-13 01:49:43 +00003083 if (CE->getOpcode() == Instruction::GetElementPtr) {
Reid Spencer87436872004-07-18 00:38:32 +00003084 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3085 if (GV->isConstant() && !GV->isExternal())
3086 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3087 return ReplaceInstUsesWith(LI, V);
Chris Lattner35e24772004-07-13 01:49:43 +00003088 } else if (CE->getOpcode() == Instruction::Cast) {
3089 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3090 return Res;
3091 }
Chris Lattnere228ee52004-04-08 20:39:49 +00003092
3093 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00003094 if (CastInst *CI = dyn_cast<CastInst>(Op))
3095 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3096 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00003097
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003098 if (!LI.isVolatile() && Op->hasOneUse()) {
3099 // Change select and PHI nodes to select values instead of addresses: this
3100 // helps alias analysis out a lot, allows many others simplifications, and
3101 // exposes redundancy in the code.
3102 //
3103 // Note that we cannot do the transformation unless we know that the
3104 // introduced loads cannot trap! Something like this is valid as long as
3105 // the condition is always false: load (select bool %C, int* null, int* %G),
3106 // but it would not be valid if we transformed it to load from null
3107 // unconditionally.
3108 //
3109 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3110 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00003111 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3112 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003113 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00003114 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003115 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00003116 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003117 return new SelectInst(SI->getCondition(), V1, V2);
3118 }
3119
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00003120 // load (select (cond, null, P)) -> load P
3121 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3122 if (C->isNullValue()) {
3123 LI.setOperand(0, SI->getOperand(2));
3124 return &LI;
3125 }
3126
3127 // load (select (cond, P, null)) -> load P
3128 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3129 if (C->isNullValue()) {
3130 LI.setOperand(0, SI->getOperand(1));
3131 return &LI;
3132 }
3133
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003134 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3135 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00003136 bool Safe = PN->getParent() == LI.getParent();
3137
3138 // Scan all of the instructions between the PHI and the load to make
3139 // sure there are no instructions that might possibly alter the value
3140 // loaded from the PHI.
3141 if (Safe) {
3142 BasicBlock::iterator I = &LI;
3143 for (--I; !isa<PHINode>(I); --I)
3144 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3145 Safe = false;
3146 break;
3147 }
3148 }
3149
3150 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00003151 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00003152 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003153 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00003154
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003155 if (Safe) {
3156 // Create the PHI.
3157 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3158 InsertNewInstBefore(NewPN, *PN);
3159 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3160
3161 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3162 BasicBlock *BB = PN->getIncomingBlock(i);
3163 Value *&TheLoad = LoadMap[BB];
3164 if (TheLoad == 0) {
3165 Value *InVal = PN->getIncomingValue(i);
3166 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3167 InVal->getName()+".val"),
3168 *BB->getTerminator());
3169 }
3170 NewPN->addIncoming(TheLoad, BB);
3171 }
3172 return ReplaceInstUsesWith(LI, NewPN);
3173 }
3174 }
3175 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003176 return 0;
3177}
3178
3179
Chris Lattner9eef8a72003-06-04 04:46:00 +00003180Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3181 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00003182 Value *X;
3183 BasicBlock *TrueDest;
3184 BasicBlock *FalseDest;
3185 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3186 !isa<Constant>(X)) {
3187 // Swap Destinations and condition...
3188 BI.setCondition(X);
3189 BI.setSuccessor(0, FalseDest);
3190 BI.setSuccessor(1, TrueDest);
3191 return &BI;
3192 }
3193
3194 // Cannonicalize setne -> seteq
3195 Instruction::BinaryOps Op; Value *Y;
3196 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3197 TrueDest, FalseDest)))
3198 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3199 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3200 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3201 std::string Name = I->getName(); I->setName("");
3202 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3203 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00003204 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00003205 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00003206 BI.setSuccessor(0, FalseDest);
3207 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003208 removeFromWorkList(I);
3209 I->getParent()->getInstList().erase(I);
3210 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00003211 return &BI;
3212 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00003213
Chris Lattner9eef8a72003-06-04 04:46:00 +00003214 return 0;
3215}
Chris Lattner1085bdf2002-11-04 16:18:53 +00003216
Chris Lattner4c9c20a2004-07-03 00:26:11 +00003217Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3218 Value *Cond = SI.getCondition();
3219 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3220 if (I->getOpcode() == Instruction::Add)
3221 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3222 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3223 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
3224 SI.setOperand(i, ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
3225 AddRHS));
3226 SI.setOperand(0, I->getOperand(0));
3227 WorkList.push_back(I);
3228 return &SI;
3229 }
3230 }
3231 return 0;
3232}
3233
Chris Lattnerca081252001-12-14 16:52:21 +00003234
Chris Lattner99f48c62002-09-02 04:59:56 +00003235void InstCombiner::removeFromWorkList(Instruction *I) {
3236 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3237 WorkList.end());
3238}
3239
Chris Lattner113f4f42002-06-25 16:13:24 +00003240bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00003241 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003242 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00003243
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003244 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3245 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00003246
Chris Lattnerca081252001-12-14 16:52:21 +00003247
3248 while (!WorkList.empty()) {
3249 Instruction *I = WorkList.back(); // Get an instruction from the worklist
3250 WorkList.pop_back();
3251
Misha Brukman632df282002-10-29 23:06:16 +00003252 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00003253 // Check to see if we can DIE the instruction...
3254 if (isInstructionTriviallyDead(I)) {
3255 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003256 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00003257 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00003258 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003259
3260 I->getParent()->getInstList().erase(I);
3261 removeFromWorkList(I);
3262 continue;
3263 }
Chris Lattner99f48c62002-09-02 04:59:56 +00003264
Misha Brukman632df282002-10-29 23:06:16 +00003265 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00003266 if (Constant *C = ConstantFoldInstruction(I)) {
3267 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00003268 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00003269 ReplaceInstUsesWith(*I, C);
3270
Chris Lattner99f48c62002-09-02 04:59:56 +00003271 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003272 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00003273 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003274 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00003275 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003276
Chris Lattnerca081252001-12-14 16:52:21 +00003277 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003278 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00003279 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00003280 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00003281 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003282 DEBUG(std::cerr << "IC: Old = " << *I
3283 << " New = " << *Result);
3284
Chris Lattner396dbfe2004-06-09 05:08:07 +00003285 // Everything uses the new instruction now.
3286 I->replaceAllUsesWith(Result);
3287
3288 // Push the new instruction and any users onto the worklist.
3289 WorkList.push_back(Result);
3290 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003291
3292 // Move the name to the new instruction first...
3293 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00003294 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003295
3296 // Insert the new instruction into the basic block...
3297 BasicBlock *InstParent = I->getParent();
3298 InstParent->getInstList().insert(I, Result);
3299
Chris Lattner63d75af2004-05-01 23:27:23 +00003300 // Make sure that we reprocess all operands now that we reduced their
3301 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003302 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3303 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3304 WorkList.push_back(OpI);
3305
Chris Lattner396dbfe2004-06-09 05:08:07 +00003306 // Instructions can end up on the worklist more than once. Make sure
3307 // we do not process an instruction that has been deleted.
3308 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003309
3310 // Erase the old instruction.
3311 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003312 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003313 DEBUG(std::cerr << "IC: MOD = " << *I);
3314
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003315 // If the instruction was modified, it's possible that it is now dead.
3316 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00003317 if (isInstructionTriviallyDead(I)) {
3318 // Make sure we process all operands now that we are reducing their
3319 // use counts.
3320 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3321 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3322 WorkList.push_back(OpI);
3323
3324 // Instructions may end up in the worklist more than once. Erase all
3325 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00003326 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00003327 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00003328 } else {
3329 WorkList.push_back(Result);
3330 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003331 }
Chris Lattner053c0932002-05-14 15:24:07 +00003332 }
Chris Lattner260ab202002-04-18 17:39:14 +00003333 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00003334 }
3335 }
3336
Chris Lattner260ab202002-04-18 17:39:14 +00003337 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00003338}
3339
Brian Gaeke38b79e82004-07-27 17:43:21 +00003340FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00003341 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00003342}
Brian Gaeke960707c2003-11-11 22:41:34 +00003343