blob: e3c45d40fb25b217b03e20a4e673df9e7d1b27cc [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 Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
46#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner60a65912002-02-12 21:07:25 +000047#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000049#include "llvm/Support/PatternMatch.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000050#include "llvm/Support/Debug.h"
51#include "llvm/ADT/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000052#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000053using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000054using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000055
Chris Lattner260ab202002-04-18 17:39:14 +000056namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000057 Statistic<> NumCombined ("instcombine", "Number of insts combined");
58 Statistic<> NumConstProp("instcombine", "Number of constant folds");
59 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
60
Chris Lattnerc8e66542002-04-27 06:56:12 +000061 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000062 public InstVisitor<InstCombiner, Instruction*> {
63 // Worklist of all of the instructions that need to be simplified.
64 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000065 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000066
Chris Lattner51ea1272004-02-28 05:22:00 +000067 /// AddUsersToWorkList - When an instruction is simplified, add all users of
68 /// the instruction to the work lists because they might get more simplified
69 /// now.
70 ///
71 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000072 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000073 UI != UE; ++UI)
74 WorkList.push_back(cast<Instruction>(*UI));
75 }
76
Chris Lattner51ea1272004-02-28 05:22:00 +000077 /// AddUsesToWorkList - When an instruction is simplified, add operands to
78 /// the work lists because they might get more simplified now.
79 ///
80 void AddUsesToWorkList(Instruction &I) {
81 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
82 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
83 WorkList.push_back(Op);
84 }
85
Chris Lattner99f48c62002-09-02 04:59:56 +000086 // removeFromWorkList - remove all instances of I from the worklist.
87 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000088 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000089 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000090
Chris Lattnerf12cc842002-04-28 21:27:06 +000091 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000092 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000093 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000094 }
95
Chris Lattner69193f92004-04-05 01:30:19 +000096 TargetData &getTargetData() const { return *TD; }
97
Chris Lattner260ab202002-04-18 17:39:14 +000098 // Visitation implementation - Implement instruction combining for different
99 // instruction types. The semantics are as follows:
100 // Return Value:
101 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000102 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000103 // otherwise - Change was made, replace I with returned instruction
104 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000105 Instruction *visitAdd(BinaryOperator &I);
106 Instruction *visitSub(BinaryOperator &I);
107 Instruction *visitMul(BinaryOperator &I);
108 Instruction *visitDiv(BinaryOperator &I);
109 Instruction *visitRem(BinaryOperator &I);
110 Instruction *visitAnd(BinaryOperator &I);
111 Instruction *visitOr (BinaryOperator &I);
112 Instruction *visitXor(BinaryOperator &I);
113 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000114 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000115 Instruction *visitCastInst(CastInst &CI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000116 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000117 Instruction *visitCallInst(CallInst &CI);
118 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000119 Instruction *visitPHINode(PHINode &PN);
120 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000121 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000122 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000123 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +0000124 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000125 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000126 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000127
128 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000129 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000130
Chris Lattner970c33a2003-06-19 17:00:31 +0000131 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000132 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000133 bool transformConstExprCastCall(CallSite CS);
134
Chris Lattner69193f92004-04-05 01:30:19 +0000135 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000136 // InsertNewInstBefore - insert an instruction New before instruction Old
137 // in the program. Add the new instruction to the worklist.
138 //
Chris Lattner623826c2004-09-28 21:48:02 +0000139 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000140 assert(New && New->getParent() == 0 &&
141 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000142 BasicBlock *BB = Old.getParent();
143 BB->getInstList().insert(&Old, New); // Insert inst
144 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000145 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000146 }
147
Chris Lattner7e794272004-09-24 15:21:34 +0000148 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
149 /// This also adds the cast to the worklist. Finally, this returns the
150 /// cast.
151 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
152 if (V->getType() == Ty) return V;
153
154 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
155 WorkList.push_back(C);
156 return C;
157 }
158
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000159 // ReplaceInstUsesWith - This method is to be used when an instruction is
160 // found to be dead, replacable with another preexisting expression. Here
161 // we add all uses of I to the worklist, replace all uses of I with the new
162 // value, then return I, so that the inst combiner will know that I was
163 // modified.
164 //
165 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000166 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000167 if (&I != V) {
168 I.replaceAllUsesWith(V);
169 return &I;
170 } else {
171 // If we are replacing the instruction with itself, this must be in a
172 // segment of unreachable code, so just clobber the instruction.
173 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
174 return &I;
175 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000176 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000177
178 // EraseInstFromFunction - When dealing with an instruction that has side
179 // effects or produces a void value, we can't rely on DCE to delete the
180 // instruction. Instead, visit methods should return the value returned by
181 // this function.
182 Instruction *EraseInstFromFunction(Instruction &I) {
183 assert(I.use_empty() && "Cannot erase instruction that is used!");
184 AddUsesToWorkList(I);
185 removeFromWorkList(&I);
186 I.getParent()->getInstList().erase(&I);
187 return 0; // Don't do anything with FI
188 }
189
190
Chris Lattner3ac7c262003-08-13 20:16:26 +0000191 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000192 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
193 /// InsertBefore instruction. This is specialized a bit to avoid inserting
194 /// casts that are known to not do anything...
195 ///
196 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
197 Instruction *InsertBefore);
198
Chris Lattner7fb29e12003-03-11 00:12:48 +0000199 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000200 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000201 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000202
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000203
204 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
205 // PHI node as operand #0, see if we can fold the instruction into the PHI
206 // (which is only possible if all operands to the PHI are constants).
207 Instruction *FoldOpIntoPhi(Instruction &I);
208
Chris Lattnerba1cb382003-09-19 17:17:26 +0000209 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
210 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000211
212 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
213 bool Inside, Instruction &IB);
Chris Lattner260ab202002-04-18 17:39:14 +0000214 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000215
Chris Lattnerc8b70922002-07-26 21:12:46 +0000216 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000217}
218
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000219// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000220// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000221static unsigned getComplexity(Value *V) {
222 if (isa<Instruction>(V)) {
223 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000224 return 3;
225 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000226 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000227 if (isa<Argument>(V)) return 3;
228 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000229}
Chris Lattner260ab202002-04-18 17:39:14 +0000230
Chris Lattner7fb29e12003-03-11 00:12:48 +0000231// isOnlyUse - Return true if this instruction will be deleted if we stop using
232// it.
233static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000234 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000235}
236
Chris Lattnere79e8542004-02-23 06:38:22 +0000237// getPromotedType - Return the specified type promoted as it would be to pass
238// though a va_arg area...
239static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000240 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000241 case Type::SByteTyID:
242 case Type::ShortTyID: return Type::IntTy;
243 case Type::UByteTyID:
244 case Type::UShortTyID: return Type::UIntTy;
245 case Type::FloatTyID: return Type::DoubleTy;
246 default: return Ty;
247 }
248}
249
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000250// SimplifyCommutative - This performs a few simplifications for commutative
251// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000252//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000253// 1. Order operands such that they are listed from right (least complex) to
254// left (most complex). This puts constants before unary operators before
255// binary operators.
256//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000257// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
258// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000259//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000260bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000261 bool Changed = false;
262 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
263 Changed = !I.swapOperands();
264
265 if (!I.isAssociative()) return Changed;
266 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000267 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
268 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
269 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000270 Constant *Folded = ConstantExpr::get(I.getOpcode(),
271 cast<Constant>(I.getOperand(1)),
272 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000273 I.setOperand(0, Op->getOperand(0));
274 I.setOperand(1, Folded);
275 return true;
276 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
277 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
278 isOnlyUse(Op) && isOnlyUse(Op1)) {
279 Constant *C1 = cast<Constant>(Op->getOperand(1));
280 Constant *C2 = cast<Constant>(Op1->getOperand(1));
281
282 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000283 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000284 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
285 Op1->getOperand(0),
286 Op1->getName(), &I);
287 WorkList.push_back(New);
288 I.setOperand(0, New);
289 I.setOperand(1, Folded);
290 return true;
291 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000292 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000293 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000294}
Chris Lattnerca081252001-12-14 16:52:21 +0000295
Chris Lattnerbb74e222003-03-10 23:06:50 +0000296// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
297// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000298//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000299static inline Value *dyn_castNegVal(Value *V) {
300 if (BinaryOperator::isNeg(V))
301 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
302
Chris Lattner9244df62003-04-30 22:19:10 +0000303 // Constants can be considered to be negated values if they can be folded...
304 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000305 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000306 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000307}
308
Chris Lattnerbb74e222003-03-10 23:06:50 +0000309static inline Value *dyn_castNotVal(Value *V) {
310 if (BinaryOperator::isNot(V))
311 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
312
313 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000314 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000315 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000316 return 0;
317}
318
Chris Lattner7fb29e12003-03-11 00:12:48 +0000319// dyn_castFoldableMul - If this value is a multiply that can be folded into
320// other computations (because it has a constant operand), return the
321// non-constant operand of the multiply.
322//
323static inline Value *dyn_castFoldableMul(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000324 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000325 if (Instruction *I = dyn_cast<Instruction>(V))
326 if (I->getOpcode() == Instruction::Mul)
327 if (isa<Constant>(I->getOperand(1)))
328 return I->getOperand(0);
329 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000330}
Chris Lattner31ae8632002-08-14 17:51:49 +0000331
Chris Lattner3082c5a2003-02-18 19:28:33 +0000332// Log2 - Calculate the log base 2 for the specified value if it is exactly a
333// power of 2.
334static unsigned Log2(uint64_t Val) {
335 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
336 unsigned Count = 0;
337 while (Val != 1) {
338 if (Val & 1) return 0; // Multiple bits set?
339 Val >>= 1;
340 ++Count;
341 }
342 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000343}
344
Chris Lattner623826c2004-09-28 21:48:02 +0000345// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000346static ConstantInt *AddOne(ConstantInt *C) {
347 return cast<ConstantInt>(ConstantExpr::getAdd(C,
348 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000349}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000350static ConstantInt *SubOne(ConstantInt *C) {
351 return cast<ConstantInt>(ConstantExpr::getSub(C,
352 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000353}
354
355// isTrueWhenEqual - Return true if the specified setcondinst instruction is
356// true when both operands are equal...
357//
358static bool isTrueWhenEqual(Instruction &I) {
359 return I.getOpcode() == Instruction::SetEQ ||
360 I.getOpcode() == Instruction::SetGE ||
361 I.getOpcode() == Instruction::SetLE;
362}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000363
364/// AssociativeOpt - Perform an optimization on an associative operator. This
365/// function is designed to check a chain of associative operators for a
366/// potential to apply a certain optimization. Since the optimization may be
367/// applicable if the expression was reassociated, this checks the chain, then
368/// reassociates the expression as necessary to expose the optimization
369/// opportunity. This makes use of a special Functor, which must define
370/// 'shouldApply' and 'apply' methods.
371///
372template<typename Functor>
373Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
374 unsigned Opcode = Root.getOpcode();
375 Value *LHS = Root.getOperand(0);
376
377 // Quick check, see if the immediate LHS matches...
378 if (F.shouldApply(LHS))
379 return F.apply(Root);
380
381 // Otherwise, if the LHS is not of the same opcode as the root, return.
382 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000383 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000384 // Should we apply this transform to the RHS?
385 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
386
387 // If not to the RHS, check to see if we should apply to the LHS...
388 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
389 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
390 ShouldApply = true;
391 }
392
393 // If the functor wants to apply the optimization to the RHS of LHSI,
394 // reassociate the expression from ((? op A) op B) to (? op (A op B))
395 if (ShouldApply) {
396 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000397
398 // Now all of the instructions are in the current basic block, go ahead
399 // and perform the reassociation.
400 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
401
402 // First move the selected RHS to the LHS of the root...
403 Root.setOperand(0, LHSI->getOperand(1));
404
405 // Make what used to be the LHS of the root be the user of the root...
406 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000407 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000408 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
409 return 0;
410 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000411 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000412 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000413 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
414 BasicBlock::iterator ARI = &Root; ++ARI;
415 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
416 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000417
418 // Now propagate the ExtraOperand down the chain of instructions until we
419 // get to LHSI.
420 while (TmpLHSI != LHSI) {
421 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000422 // Move the instruction to immediately before the chain we are
423 // constructing to avoid breaking dominance properties.
424 NextLHSI->getParent()->getInstList().remove(NextLHSI);
425 BB->getInstList().insert(ARI, NextLHSI);
426 ARI = NextLHSI;
427
Chris Lattnerb8b97502003-08-13 19:01:45 +0000428 Value *NextOp = NextLHSI->getOperand(1);
429 NextLHSI->setOperand(1, ExtraOperand);
430 TmpLHSI = NextLHSI;
431 ExtraOperand = NextOp;
432 }
433
434 // Now that the instructions are reassociated, have the functor perform
435 // the transformation...
436 return F.apply(Root);
437 }
438
439 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
440 }
441 return 0;
442}
443
444
445// AddRHS - Implements: X + X --> X << 1
446struct AddRHS {
447 Value *RHS;
448 AddRHS(Value *rhs) : RHS(rhs) {}
449 bool shouldApply(Value *LHS) const { return LHS == RHS; }
450 Instruction *apply(BinaryOperator &Add) const {
451 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
452 ConstantInt::get(Type::UByteTy, 1));
453 }
454};
455
456// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
457// iff C1&C2 == 0
458struct AddMaskingAnd {
459 Constant *C2;
460 AddMaskingAnd(Constant *c) : C2(c) {}
461 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000462 ConstantInt *C1;
463 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
464 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000465 }
466 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000467 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000468 }
469};
470
Chris Lattner183b3362004-04-09 19:05:30 +0000471static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
472 InstCombiner *IC) {
473 // Figure out if the constant is the left or the right argument.
474 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
475 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000476
Chris Lattner183b3362004-04-09 19:05:30 +0000477 if (Constant *SOC = dyn_cast<Constant>(SO)) {
478 if (ConstIsRHS)
479 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
480 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
481 }
482
483 Value *Op0 = SO, *Op1 = ConstOperand;
484 if (!ConstIsRHS)
485 std::swap(Op0, Op1);
486 Instruction *New;
487 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
488 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
489 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
490 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattnerf9d96652004-04-10 19:15:56 +0000491 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000492 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000493 abort();
494 }
Chris Lattner183b3362004-04-09 19:05:30 +0000495 return IC->InsertNewInstBefore(New, BI);
496}
497
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000498
499/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
500/// node as operand #0, see if we can fold the instruction into the PHI (which
501/// is only possible if all operands to the PHI are constants).
502Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
503 PHINode *PN = cast<PHINode>(I.getOperand(0));
504 if (!PN->hasOneUse()) return 0;
505
506 // Check to see if all of the operands of the PHI are constants. If not, we
507 // cannot do the transformation.
508 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
509 if (!isa<Constant>(PN->getIncomingValue(i)))
510 return 0;
511
512 // Okay, we can do the transformation: create the new PHI node.
513 PHINode *NewPN = new PHINode(I.getType(), I.getName());
514 I.setName("");
515 NewPN->op_reserve(PN->getNumOperands());
516 InsertNewInstBefore(NewPN, *PN);
517
518 // Next, add all of the operands to the PHI.
519 if (I.getNumOperands() == 2) {
520 Constant *C = cast<Constant>(I.getOperand(1));
521 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
522 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
523 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
524 PN->getIncomingBlock(i));
525 }
526 } else {
527 assert(isa<CastInst>(I) && "Unary op should be a cast!");
528 const Type *RetTy = I.getType();
529 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
530 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
531 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
532 PN->getIncomingBlock(i));
533 }
534 }
535 return ReplaceInstUsesWith(I, NewPN);
536}
537
Chris Lattner183b3362004-04-09 19:05:30 +0000538// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
539// constant as the other operand, try to fold the binary operator into the
540// select arguments.
541static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
542 InstCombiner *IC) {
543 // Don't modify shared select instructions
544 if (!SI->hasOneUse()) return 0;
545 Value *TV = SI->getOperand(1);
546 Value *FV = SI->getOperand(2);
547
548 if (isa<Constant>(TV) || isa<Constant>(FV)) {
549 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
550 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
551
552 return new SelectInst(SI->getCondition(), SelectTrueVal,
553 SelectFalseVal);
554 }
555 return 0;
556}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000557
Chris Lattner113f4f42002-06-25 16:13:24 +0000558Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000559 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000560 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000561
Chris Lattnercf4a9962004-04-10 22:01:55 +0000562 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000563 // X + undef -> undef
564 if (isa<UndefValue>(RHS))
565 return ReplaceInstUsesWith(I, RHS);
566
Chris Lattnercf4a9962004-04-10 22:01:55 +0000567 // X + 0 --> X
568 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
569 RHSC->isNullValue())
570 return ReplaceInstUsesWith(I, LHS);
571
572 // X + (signbit) --> X ^ signbit
573 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
574 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
575 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
576 if (Val == (1ULL << NumBits-1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000577 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000578 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000579
580 if (isa<PHINode>(LHS))
581 if (Instruction *NV = FoldOpIntoPhi(I))
582 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000583 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000584
Chris Lattnerb8b97502003-08-13 19:01:45 +0000585 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000586 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000587 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000588 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000589
Chris Lattner147e9752002-05-08 22:46:53 +0000590 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000591 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000592 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000593
594 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000595 if (!isa<Constant>(RHS))
596 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000597 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000598
Chris Lattner57c8d992003-02-18 19:57:07 +0000599 // X*C + X --> X * (C+1)
600 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000601 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000602 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000603 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
604 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000605 return BinaryOperator::createMul(RHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000606 }
607
608 // X + X*C --> X * (C+1)
609 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000610 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000611 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000612 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
613 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000614 return BinaryOperator::createMul(LHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000615 }
616
Chris Lattnerb8b97502003-08-13 19:01:45 +0000617 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000618 ConstantInt *C2;
619 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000620 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000621
Chris Lattnerb9cde762003-10-02 15:11:26 +0000622 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000623 Value *X;
624 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
625 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
626 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000627 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000628
Chris Lattnerbff91d92004-10-08 05:07:56 +0000629 // (X & FF00) + xx00 -> (X+xx00) & FF00
630 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
631 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
632 if (Anded == CRHS) {
633 // See if all bits from the first bit set in the Add RHS up are included
634 // in the mask. First, get the rightmost bit.
635 uint64_t AddRHSV = CRHS->getRawValue();
636
637 // Form a mask of all bits from the lowest bit added through the top.
638 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
639 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
640
641 // See if the and mask includes all of these bits.
642 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
643
644 if (AddRHSHighBits == AddRHSHighBitsAnd) {
645 // Okay, the xform is safe. Insert the new add pronto.
646 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
647 LHS->getName()), I);
648 return BinaryOperator::createAnd(NewAdd, C2);
649 }
650 }
651 }
652
653
Chris Lattnerd4252a72004-07-30 07:50:03 +0000654 // Try to fold constant add into select arguments.
655 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
656 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
657 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000658 }
659
Chris Lattner113f4f42002-06-25 16:13:24 +0000660 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000661}
662
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000663// isSignBit - Return true if the value represented by the constant only has the
664// highest order bit set.
665static bool isSignBit(ConstantInt *CI) {
666 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
667 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
668}
669
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000670static unsigned getTypeSizeInBits(const Type *Ty) {
671 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
672}
673
Chris Lattner022167f2004-03-13 00:11:49 +0000674/// RemoveNoopCast - Strip off nonconverting casts from the value.
675///
676static Value *RemoveNoopCast(Value *V) {
677 if (CastInst *CI = dyn_cast<CastInst>(V)) {
678 const Type *CTy = CI->getType();
679 const Type *OpTy = CI->getOperand(0)->getType();
680 if (CTy->isInteger() && OpTy->isInteger()) {
681 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
682 return RemoveNoopCast(CI->getOperand(0));
683 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
684 return RemoveNoopCast(CI->getOperand(0));
685 }
686 return V;
687}
688
Chris Lattner113f4f42002-06-25 16:13:24 +0000689Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000690 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000691
Chris Lattnere6794492002-08-12 21:17:25 +0000692 if (Op0 == Op1) // sub X, X -> 0
693 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000694
Chris Lattnere6794492002-08-12 21:17:25 +0000695 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000696 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000697 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000698
Chris Lattner81a7a232004-10-16 18:11:37 +0000699 if (isa<UndefValue>(Op0))
700 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
701 if (isa<UndefValue>(Op1))
702 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
703
Chris Lattner8f2f5982003-11-05 01:06:05 +0000704 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
705 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000706 if (C->isAllOnesValue())
707 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000708
Chris Lattner8f2f5982003-11-05 01:06:05 +0000709 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000710 Value *X;
711 if (match(Op1, m_Not(m_Value(X))))
712 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000713 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000714 // -((uint)X >> 31) -> ((int)X >> 31)
715 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000716 if (C->isNullValue()) {
717 Value *NoopCastedRHS = RemoveNoopCast(Op1);
718 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000719 if (SI->getOpcode() == Instruction::Shr)
720 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
721 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000722 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000723 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000724 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000725 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000726 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000727 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000728 // Ok, the transformation is safe. Insert a cast of the incoming
729 // value, then the new shift, then the new cast.
730 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
731 SI->getOperand(0)->getName());
732 Value *InV = InsertNewInstBefore(FirstCast, I);
733 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
734 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000735 if (NewShift->getType() == I.getType())
736 return NewShift;
737 else {
738 InV = InsertNewInstBefore(NewShift, I);
739 return new CastInst(NewShift, I.getType());
740 }
Chris Lattner92295c52004-03-12 23:53:13 +0000741 }
742 }
Chris Lattner022167f2004-03-13 00:11:49 +0000743 }
Chris Lattner183b3362004-04-09 19:05:30 +0000744
745 // Try to fold constant sub into select arguments.
746 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
747 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
748 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000749
750 if (isa<PHINode>(Op0))
751 if (Instruction *NV = FoldOpIntoPhi(I))
752 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000753 }
754
Chris Lattner3082c5a2003-02-18 19:28:33 +0000755 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000756 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000757 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
758 // is not used by anyone else...
759 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000760 if (Op1I->getOpcode() == Instruction::Sub &&
761 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000762 // Swap the two operands of the subexpr...
763 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
764 Op1I->setOperand(0, IIOp1);
765 Op1I->setOperand(1, IIOp0);
766
767 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000768 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000769 }
770
771 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
772 //
773 if (Op1I->getOpcode() == Instruction::And &&
774 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
775 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
776
Chris Lattner396dbfe2004-06-09 05:08:07 +0000777 Value *NewNot =
778 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000779 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000780 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000781
Chris Lattner0aee4b72004-10-06 15:08:25 +0000782 // -(X sdiv C) -> (X sdiv -C)
783 if (Op1I->getOpcode() == Instruction::Div)
784 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
785 if (CSI->getValue() == 0)
786 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
787 return BinaryOperator::createDiv(Op1I->getOperand(0),
788 ConstantExpr::getNeg(DivRHS));
789
Chris Lattner57c8d992003-02-18 19:57:07 +0000790 // X - X*C --> X * (1-C)
791 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000792 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000793 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner34428442003-05-27 16:40:51 +0000794 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000795 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000796 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000797 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000798 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000799
Chris Lattner57c8d992003-02-18 19:57:07 +0000800 // X*C - X --> X * (C-1)
801 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000802 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000803 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner34428442003-05-27 16:40:51 +0000804 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000805 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000806 return BinaryOperator::createMul(Op1, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000807 }
808
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000809 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000810}
811
Chris Lattnere79e8542004-02-23 06:38:22 +0000812/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
813/// really just returns true if the most significant (sign) bit is set.
814static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
815 if (RHS->getType()->isSigned()) {
816 // True if source is LHS < 0 or LHS <= -1
817 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
818 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
819 } else {
820 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
821 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
822 // the size of the integer type.
823 if (Opcode == Instruction::SetGE)
824 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
825 if (Opcode == Instruction::SetGT)
826 return RHSC->getValue() ==
827 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
828 }
829 return false;
830}
831
Chris Lattner113f4f42002-06-25 16:13:24 +0000832Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000833 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000834 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000835
Chris Lattner81a7a232004-10-16 18:11:37 +0000836 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
837 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
838
Chris Lattnere6794492002-08-12 21:17:25 +0000839 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000840 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
841 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000842
843 // ((X << C1)*C2) == (X * (C2 << C1))
844 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
845 if (SI->getOpcode() == Instruction::Shl)
846 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000847 return BinaryOperator::createMul(SI->getOperand(0),
848 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000849
Chris Lattnercce81be2003-09-11 22:24:54 +0000850 if (CI->isNullValue())
851 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
852 if (CI->equalsInt(1)) // X * 1 == X
853 return ReplaceInstUsesWith(I, Op0);
854 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000855 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000856
Chris Lattnercce81be2003-09-11 22:24:54 +0000857 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000858 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
859 return new ShiftInst(Instruction::Shl, Op0,
860 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000861 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000862 if (Op1F->isNullValue())
863 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000864
Chris Lattner3082c5a2003-02-18 19:28:33 +0000865 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
866 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
867 if (Op1F->getValue() == 1.0)
868 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
869 }
Chris Lattner183b3362004-04-09 19:05:30 +0000870
871 // Try to fold constant mul into select arguments.
872 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
873 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
874 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000875
876 if (isa<PHINode>(Op0))
877 if (Instruction *NV = FoldOpIntoPhi(I))
878 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000879 }
880
Chris Lattner934a64cf2003-03-10 23:23:04 +0000881 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
882 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000883 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000884
Chris Lattner2635b522004-02-23 05:39:21 +0000885 // If one of the operands of the multiply is a cast from a boolean value, then
886 // we know the bool is either zero or one, so this is a 'masking' multiply.
887 // See if we can simplify things based on how the boolean was originally
888 // formed.
889 CastInst *BoolCast = 0;
890 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
891 if (CI->getOperand(0)->getType() == Type::BoolTy)
892 BoolCast = CI;
893 if (!BoolCast)
894 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
895 if (CI->getOperand(0)->getType() == Type::BoolTy)
896 BoolCast = CI;
897 if (BoolCast) {
898 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
899 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
900 const Type *SCOpTy = SCIOp0->getType();
901
Chris Lattnere79e8542004-02-23 06:38:22 +0000902 // If the setcc is true iff the sign bit of X is set, then convert this
903 // multiply into a shift/and combination.
904 if (isa<ConstantInt>(SCIOp1) &&
905 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000906 // Shift the X value right to turn it into "all signbits".
907 Constant *Amt = ConstantUInt::get(Type::UByteTy,
908 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000909 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000910 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000911 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
912 SCIOp0->getName()), I);
913 }
914
915 Value *V =
916 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
917 BoolCast->getOperand(0)->getName()+
918 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000919
920 // If the multiply type is not the same as the source type, sign extend
921 // or truncate to the multiply type.
922 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000923 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000924
925 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000926 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000927 }
928 }
929 }
930
Chris Lattner113f4f42002-06-25 16:13:24 +0000931 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000932}
933
Chris Lattner113f4f42002-06-25 16:13:24 +0000934Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000935 if (isa<UndefValue>(I.getOperand(0))) // undef / X -> 0
936 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
937 if (isa<UndefValue>(I.getOperand(1)))
938 return ReplaceInstUsesWith(I, I.getOperand(1)); // X / undef -> undef
939
Chris Lattner3082c5a2003-02-18 19:28:33 +0000940 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000941 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000942 if (RHS->equalsInt(1))
943 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000944
Chris Lattnere20c3342004-04-26 14:01:59 +0000945 // div X, -1 == -X
946 if (RHS->isAllOnesValue())
947 return BinaryOperator::createNeg(I.getOperand(0));
948
Chris Lattner272d5ca2004-09-28 18:22:15 +0000949 if (Instruction *LHS = dyn_cast<Instruction>(I.getOperand(0)))
950 if (LHS->getOpcode() == Instruction::Div)
951 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +0000952 // (X / C1) / C2 -> X / (C1*C2)
953 return BinaryOperator::createDiv(LHS->getOperand(0),
954 ConstantExpr::getMul(RHS, LHSRHS));
955 }
956
Chris Lattner3082c5a2003-02-18 19:28:33 +0000957 // Check to see if this is an unsigned division with an exact power of 2,
958 // if so, convert to a right shift.
959 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
960 if (uint64_t Val = C->getValue()) // Don't break X / 0
961 if (uint64_t C = Log2(Val))
962 return new ShiftInst(Instruction::Shr, I.getOperand(0),
963 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000964
Chris Lattner4ad08352004-10-09 02:50:40 +0000965 // -X/C -> X/-C
966 if (RHS->getType()->isSigned())
967 if (Value *LHSNeg = dyn_castNegVal(I.getOperand(0)))
968 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
969
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000970 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
971 if (Instruction *NV = FoldOpIntoPhi(I))
972 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000973 }
974
975 // 0 / X == 0, we don't need to preserve faults!
976 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
977 if (LHS->equalsInt(0))
978 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
979
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000980 return 0;
981}
982
983
Chris Lattner113f4f42002-06-25 16:13:24 +0000984Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000985 if (I.getType()->isSigned())
986 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner98c6bdf2004-07-06 07:11:42 +0000987 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +0000988 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000989 // X % -Y -> X % Y
990 AddUsesToWorkList(I);
991 I.setOperand(1, RHSNeg);
992 return &I;
993 }
994
Chris Lattner81a7a232004-10-16 18:11:37 +0000995 if (isa<UndefValue>(I.getOperand(0))) // undef % X -> 0
996 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
997 if (isa<UndefValue>(I.getOperand(1)))
998 return ReplaceInstUsesWith(I, I.getOperand(1)); // X % undef -> undef
999
Chris Lattner3082c5a2003-02-18 19:28:33 +00001000 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
1001 if (RHS->equalsInt(1)) // X % 1 == 0
1002 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1003
1004 // Check to see if this is an unsigned remainder with an exact power of 2,
1005 // if so, convert to a bitwise and.
1006 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1007 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001008 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001009 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattner3082c5a2003-02-18 19:28:33 +00001010 ConstantUInt::get(I.getType(), Val-1));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001011 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
1012 if (Instruction *NV = FoldOpIntoPhi(I))
1013 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +00001014 }
1015
1016 // 0 % X == 0, we don't need to preserve faults!
1017 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
1018 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001019 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1020
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001021 return 0;
1022}
1023
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001024// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001025static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001026 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1027 // Calculate -1 casted to the right type...
1028 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1029 uint64_t Val = ~0ULL; // All ones
1030 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1031 return CU->getValue() == Val-1;
1032 }
1033
1034 const ConstantSInt *CS = cast<ConstantSInt>(C);
1035
1036 // Calculate 0111111111..11111
1037 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1038 int64_t Val = INT64_MAX; // All ones
1039 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1040 return CS->getValue() == Val-1;
1041}
1042
1043// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001044static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001045 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1046 return CU->getValue() == 1;
1047
1048 const ConstantSInt *CS = cast<ConstantSInt>(C);
1049
1050 // Calculate 1111111111000000000000
1051 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1052 int64_t Val = -1; // All ones
1053 Val <<= TypeBits-1; // Shift over to the right spot
1054 return CS->getValue() == Val+1;
1055}
1056
Chris Lattner35167c32004-06-09 07:59:58 +00001057// isOneBitSet - Return true if there is exactly one bit set in the specified
1058// constant.
1059static bool isOneBitSet(const ConstantInt *CI) {
1060 uint64_t V = CI->getRawValue();
1061 return V && (V & (V-1)) == 0;
1062}
1063
Chris Lattner8fc5af42004-09-23 21:46:38 +00001064#if 0 // Currently unused
1065// isLowOnes - Return true if the constant is of the form 0+1+.
1066static bool isLowOnes(const ConstantInt *CI) {
1067 uint64_t V = CI->getRawValue();
1068
1069 // There won't be bits set in parts that the type doesn't contain.
1070 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1071
1072 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1073 return U && V && (U & V) == 0;
1074}
1075#endif
1076
1077// isHighOnes - Return true if the constant is of the form 1+0+.
1078// This is the same as lowones(~X).
1079static bool isHighOnes(const ConstantInt *CI) {
1080 uint64_t V = ~CI->getRawValue();
1081
1082 // There won't be bits set in parts that the type doesn't contain.
1083 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1084
1085 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1086 return U && V && (U & V) == 0;
1087}
1088
1089
Chris Lattner3ac7c262003-08-13 20:16:26 +00001090/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1091/// are carefully arranged to allow folding of expressions such as:
1092///
1093/// (A < B) | (A > B) --> (A != B)
1094///
1095/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1096/// represents that the comparison is true if A == B, and bit value '1' is true
1097/// if A < B.
1098///
1099static unsigned getSetCondCode(const SetCondInst *SCI) {
1100 switch (SCI->getOpcode()) {
1101 // False -> 0
1102 case Instruction::SetGT: return 1;
1103 case Instruction::SetEQ: return 2;
1104 case Instruction::SetGE: return 3;
1105 case Instruction::SetLT: return 4;
1106 case Instruction::SetNE: return 5;
1107 case Instruction::SetLE: return 6;
1108 // True -> 7
1109 default:
1110 assert(0 && "Invalid SetCC opcode!");
1111 return 0;
1112 }
1113}
1114
1115/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1116/// opcode and two operands into either a constant true or false, or a brand new
1117/// SetCC instruction.
1118static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1119 switch (Opcode) {
1120 case 0: return ConstantBool::False;
1121 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1122 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1123 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1124 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1125 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1126 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1127 case 7: return ConstantBool::True;
1128 default: assert(0 && "Illegal SetCCCode!"); return 0;
1129 }
1130}
1131
1132// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1133struct FoldSetCCLogical {
1134 InstCombiner &IC;
1135 Value *LHS, *RHS;
1136 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1137 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1138 bool shouldApply(Value *V) const {
1139 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1140 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1141 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1142 return false;
1143 }
1144 Instruction *apply(BinaryOperator &Log) const {
1145 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1146 if (SCI->getOperand(0) != LHS) {
1147 assert(SCI->getOperand(1) == LHS);
1148 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1149 }
1150
1151 unsigned LHSCode = getSetCondCode(SCI);
1152 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1153 unsigned Code;
1154 switch (Log.getOpcode()) {
1155 case Instruction::And: Code = LHSCode & RHSCode; break;
1156 case Instruction::Or: Code = LHSCode | RHSCode; break;
1157 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001158 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001159 }
1160
1161 Value *RV = getSetCCValue(Code, LHS, RHS);
1162 if (Instruction *I = dyn_cast<Instruction>(RV))
1163 return I;
1164 // Otherwise, it's a constant boolean value...
1165 return IC.ReplaceInstUsesWith(Log, RV);
1166 }
1167};
1168
1169
Chris Lattnerba1cb382003-09-19 17:17:26 +00001170// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1171// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1172// guaranteed to be either a shift instruction or a binary operator.
1173Instruction *InstCombiner::OptAndOp(Instruction *Op,
1174 ConstantIntegral *OpRHS,
1175 ConstantIntegral *AndRHS,
1176 BinaryOperator &TheAnd) {
1177 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001178 Constant *Together = 0;
1179 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001180 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001181
Chris Lattnerba1cb382003-09-19 17:17:26 +00001182 switch (Op->getOpcode()) {
1183 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001184 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001185 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001186 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001187 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001188 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1189 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001190 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001191 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001192 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001193 }
1194 break;
1195 case Instruction::Or:
1196 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001197 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001198 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001199 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001200 if (Together == AndRHS) // (X | C) & C --> C
1201 return ReplaceInstUsesWith(TheAnd, AndRHS);
1202
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001203 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001204 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1205 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001206 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001207 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001208 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001209 }
1210 }
1211 break;
1212 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001213 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001214 // Adding a one to a single bit bit-field should be turned into an XOR
1215 // of the bit. First thing to check is to see if this AND is with a
1216 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001217 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001218
1219 // Clear bits that are not part of the constant.
1220 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1221
1222 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001223 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001224 // Ok, at this point, we know that we are masking the result of the
1225 // ADD down to exactly one bit. If the constant we are adding has
1226 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001227 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001228
1229 // Check to see if any bits below the one bit set in AndRHSV are set.
1230 if ((AddRHS & (AndRHSV-1)) == 0) {
1231 // If not, the only thing that can effect the output of the AND is
1232 // the bit specified by AndRHSV. If that bit is set, the effect of
1233 // the XOR is to toggle the bit. If it is clear, then the ADD has
1234 // no effect.
1235 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1236 TheAnd.setOperand(0, X);
1237 return &TheAnd;
1238 } else {
1239 std::string Name = Op->getName(); Op->setName("");
1240 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001241 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001242 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001243 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001244 }
1245 }
1246 }
1247 }
1248 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001249
1250 case Instruction::Shl: {
1251 // We know that the AND will not produce any of the bits shifted in, so if
1252 // the anded constant includes them, clear them now!
1253 //
1254 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001255 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1256 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1257
1258 if (CI == ShlMask) { // Masking out bits that the shift already masks
1259 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1260 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001261 TheAnd.setOperand(1, CI);
1262 return &TheAnd;
1263 }
1264 break;
1265 }
1266 case Instruction::Shr:
1267 // We know that the AND will not produce any of the bits shifted in, so if
1268 // the anded constant includes them, clear them now! This only applies to
1269 // unsigned shifts, because a signed shr may bring in set bits!
1270 //
1271 if (AndRHS->getType()->isUnsigned()) {
1272 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001273 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1274 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1275
1276 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1277 return ReplaceInstUsesWith(TheAnd, Op);
1278 } else if (CI != AndRHS) {
1279 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001280 return &TheAnd;
1281 }
Chris Lattner7e794272004-09-24 15:21:34 +00001282 } else { // Signed shr.
1283 // See if this is shifting in some sign extension, then masking it out
1284 // with an and.
1285 if (Op->hasOneUse()) {
1286 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1287 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1288 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1289 if (CI == ShrMask) { // Masking out bits shifted in.
1290 // Make the argument unsigned.
1291 Value *ShVal = Op->getOperand(0);
1292 ShVal = InsertCastBefore(ShVal,
1293 ShVal->getType()->getUnsignedVersion(),
1294 TheAnd);
1295 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1296 OpRHS, Op->getName()),
1297 TheAnd);
1298 return new CastInst(ShVal, Op->getType());
1299 }
1300 }
Chris Lattner2da29172003-09-19 19:05:02 +00001301 }
1302 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001303 }
1304 return 0;
1305}
1306
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001307
Chris Lattner6862fbd2004-09-29 17:40:11 +00001308/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1309/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1310/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1311/// insert new instructions.
1312Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1313 bool Inside, Instruction &IB) {
1314 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1315 "Lo is not <= Hi in range emission code!");
1316 if (Inside) {
1317 if (Lo == Hi) // Trivially false.
1318 return new SetCondInst(Instruction::SetNE, V, V);
1319 if (cast<ConstantIntegral>(Lo)->isMinValue())
1320 return new SetCondInst(Instruction::SetLT, V, Hi);
1321
1322 Constant *AddCST = ConstantExpr::getNeg(Lo);
1323 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1324 InsertNewInstBefore(Add, IB);
1325 // Convert to unsigned for the comparison.
1326 const Type *UnsType = Add->getType()->getUnsignedVersion();
1327 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1328 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1329 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1330 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1331 }
1332
1333 if (Lo == Hi) // Trivially true.
1334 return new SetCondInst(Instruction::SetEQ, V, V);
1335
1336 Hi = SubOne(cast<ConstantInt>(Hi));
1337 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1338 return new SetCondInst(Instruction::SetGT, V, Hi);
1339
1340 // Emit X-Lo > Hi-Lo-1
1341 Constant *AddCST = ConstantExpr::getNeg(Lo);
1342 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1343 InsertNewInstBefore(Add, IB);
1344 // Convert to unsigned for the comparison.
1345 const Type *UnsType = Add->getType()->getUnsignedVersion();
1346 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1347 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1348 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1349 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1350}
1351
1352
Chris Lattner113f4f42002-06-25 16:13:24 +00001353Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001354 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001355 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001356
Chris Lattner81a7a232004-10-16 18:11:37 +00001357 if (isa<UndefValue>(Op1)) // X & undef -> 0
1358 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1359
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001360 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001361 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1362 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001363
1364 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001365 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001366 if (RHS->isAllOnesValue())
1367 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001368
Chris Lattnerba1cb382003-09-19 17:17:26 +00001369 // Optimize a variety of ((val OP C1) & C2) combinations...
1370 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1371 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001372 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001373 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001374 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1375 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001376 }
Chris Lattner183b3362004-04-09 19:05:30 +00001377
1378 // Try to fold constant and into select arguments.
1379 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1380 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1381 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001382 if (isa<PHINode>(Op0))
1383 if (Instruction *NV = FoldOpIntoPhi(I))
1384 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001385 }
1386
Chris Lattnerbb74e222003-03-10 23:06:50 +00001387 Value *Op0NotVal = dyn_castNotVal(Op0);
1388 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001389
Chris Lattner023a4832004-06-18 06:07:51 +00001390 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1391 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1392
Misha Brukman9c003d82004-07-30 12:50:08 +00001393 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001394 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001395 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1396 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001397 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001398 return BinaryOperator::createNot(Or);
1399 }
1400
Chris Lattner623826c2004-09-28 21:48:02 +00001401 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1402 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001403 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1404 return R;
1405
Chris Lattner623826c2004-09-28 21:48:02 +00001406 Value *LHSVal, *RHSVal;
1407 ConstantInt *LHSCst, *RHSCst;
1408 Instruction::BinaryOps LHSCC, RHSCC;
1409 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1410 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1411 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1412 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1413 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1414 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1415 // Ensure that the larger constant is on the RHS.
1416 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1417 SetCondInst *LHS = cast<SetCondInst>(Op0);
1418 if (cast<ConstantBool>(Cmp)->getValue()) {
1419 std::swap(LHS, RHS);
1420 std::swap(LHSCst, RHSCst);
1421 std::swap(LHSCC, RHSCC);
1422 }
1423
1424 // At this point, we know we have have two setcc instructions
1425 // comparing a value against two constants and and'ing the result
1426 // together. Because of the above check, we know that we only have
1427 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1428 // FoldSetCCLogical check above), that the two constants are not
1429 // equal.
1430 assert(LHSCst != RHSCst && "Compares not folded above?");
1431
1432 switch (LHSCC) {
1433 default: assert(0 && "Unknown integer condition code!");
1434 case Instruction::SetEQ:
1435 switch (RHSCC) {
1436 default: assert(0 && "Unknown integer condition code!");
1437 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1438 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1439 return ReplaceInstUsesWith(I, ConstantBool::False);
1440 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1441 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1442 return ReplaceInstUsesWith(I, LHS);
1443 }
1444 case Instruction::SetNE:
1445 switch (RHSCC) {
1446 default: assert(0 && "Unknown integer condition code!");
1447 case Instruction::SetLT:
1448 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1449 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1450 break; // (X != 13 & X < 15) -> no change
1451 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1452 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1453 return ReplaceInstUsesWith(I, RHS);
1454 case Instruction::SetNE:
1455 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1456 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1457 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1458 LHSVal->getName()+".off");
1459 InsertNewInstBefore(Add, I);
1460 const Type *UnsType = Add->getType()->getUnsignedVersion();
1461 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1462 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1463 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1464 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1465 }
1466 break; // (X != 13 & X != 15) -> no change
1467 }
1468 break;
1469 case Instruction::SetLT:
1470 switch (RHSCC) {
1471 default: assert(0 && "Unknown integer condition code!");
1472 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1473 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1474 return ReplaceInstUsesWith(I, ConstantBool::False);
1475 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1476 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1477 return ReplaceInstUsesWith(I, LHS);
1478 }
1479 case Instruction::SetGT:
1480 switch (RHSCC) {
1481 default: assert(0 && "Unknown integer condition code!");
1482 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1483 return ReplaceInstUsesWith(I, LHS);
1484 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1485 return ReplaceInstUsesWith(I, RHS);
1486 case Instruction::SetNE:
1487 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1488 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1489 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001490 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1491 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001492 }
1493 }
1494 }
1495 }
1496
Chris Lattner113f4f42002-06-25 16:13:24 +00001497 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001498}
1499
Chris Lattner113f4f42002-06-25 16:13:24 +00001500Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001501 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001502 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001503
Chris Lattner81a7a232004-10-16 18:11:37 +00001504 if (isa<UndefValue>(Op1))
1505 return ReplaceInstUsesWith(I, // X | undef -> -1
1506 ConstantIntegral::getAllOnesValue(I.getType()));
1507
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001508 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001509 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1510 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001511
1512 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001513 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001514 if (RHS->isAllOnesValue())
1515 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001516
Chris Lattnerd4252a72004-07-30 07:50:03 +00001517 ConstantInt *C1; Value *X;
1518 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1519 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1520 std::string Op0Name = Op0->getName(); Op0->setName("");
1521 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1522 InsertNewInstBefore(Or, I);
1523 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1524 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001525
Chris Lattnerd4252a72004-07-30 07:50:03 +00001526 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1527 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1528 std::string Op0Name = Op0->getName(); Op0->setName("");
1529 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1530 InsertNewInstBefore(Or, I);
1531 return BinaryOperator::createXor(Or,
1532 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001533 }
Chris Lattner183b3362004-04-09 19:05:30 +00001534
1535 // Try to fold constant and into select arguments.
1536 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1537 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1538 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001539 if (isa<PHINode>(Op0))
1540 if (Instruction *NV = FoldOpIntoPhi(I))
1541 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001542 }
1543
Chris Lattner812aab72003-08-12 19:11:07 +00001544 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001545 Value *A, *B; ConstantInt *C1, *C2;
1546 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1547 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1548 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001549
Chris Lattnerd4252a72004-07-30 07:50:03 +00001550 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1551 if (A == Op1) // ~A | A == -1
1552 return ReplaceInstUsesWith(I,
1553 ConstantIntegral::getAllOnesValue(I.getType()));
1554 } else {
1555 A = 0;
1556 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001557
Chris Lattnerd4252a72004-07-30 07:50:03 +00001558 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1559 if (Op0 == B)
1560 return ReplaceInstUsesWith(I,
1561 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001562
Misha Brukman9c003d82004-07-30 12:50:08 +00001563 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001564 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1565 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1566 I.getName()+".demorgan"), I);
1567 return BinaryOperator::createNot(And);
1568 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001569 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001570
Chris Lattner3ac7c262003-08-13 20:16:26 +00001571 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001572 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001573 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1574 return R;
1575
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001576 Value *LHSVal, *RHSVal;
1577 ConstantInt *LHSCst, *RHSCst;
1578 Instruction::BinaryOps LHSCC, RHSCC;
1579 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1580 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1581 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1582 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1583 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1584 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1585 // Ensure that the larger constant is on the RHS.
1586 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1587 SetCondInst *LHS = cast<SetCondInst>(Op0);
1588 if (cast<ConstantBool>(Cmp)->getValue()) {
1589 std::swap(LHS, RHS);
1590 std::swap(LHSCst, RHSCst);
1591 std::swap(LHSCC, RHSCC);
1592 }
1593
1594 // At this point, we know we have have two setcc instructions
1595 // comparing a value against two constants and or'ing the result
1596 // together. Because of the above check, we know that we only have
1597 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1598 // FoldSetCCLogical check above), that the two constants are not
1599 // equal.
1600 assert(LHSCst != RHSCst && "Compares not folded above?");
1601
1602 switch (LHSCC) {
1603 default: assert(0 && "Unknown integer condition code!");
1604 case Instruction::SetEQ:
1605 switch (RHSCC) {
1606 default: assert(0 && "Unknown integer condition code!");
1607 case Instruction::SetEQ:
1608 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1609 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1610 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1611 LHSVal->getName()+".off");
1612 InsertNewInstBefore(Add, I);
1613 const Type *UnsType = Add->getType()->getUnsignedVersion();
1614 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1615 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1616 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1617 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1618 }
1619 break; // (X == 13 | X == 15) -> no change
1620
1621 case Instruction::SetGT:
1622 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1623 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1624 break; // (X == 13 | X > 15) -> no change
1625 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1626 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1627 return ReplaceInstUsesWith(I, RHS);
1628 }
1629 break;
1630 case Instruction::SetNE:
1631 switch (RHSCC) {
1632 default: assert(0 && "Unknown integer condition code!");
1633 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1634 return ReplaceInstUsesWith(I, RHS);
1635 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1636 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1637 return ReplaceInstUsesWith(I, LHS);
1638 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1639 return ReplaceInstUsesWith(I, ConstantBool::True);
1640 }
1641 break;
1642 case Instruction::SetLT:
1643 switch (RHSCC) {
1644 default: assert(0 && "Unknown integer condition code!");
1645 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1646 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001647 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1648 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001649 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1650 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1651 return ReplaceInstUsesWith(I, RHS);
1652 }
1653 break;
1654 case Instruction::SetGT:
1655 switch (RHSCC) {
1656 default: assert(0 && "Unknown integer condition code!");
1657 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1658 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1659 return ReplaceInstUsesWith(I, LHS);
1660 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1661 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1662 return ReplaceInstUsesWith(I, ConstantBool::True);
1663 }
1664 }
1665 }
1666 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001667 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001668}
1669
Chris Lattnerc2076352004-02-16 01:20:27 +00001670// XorSelf - Implements: X ^ X --> 0
1671struct XorSelf {
1672 Value *RHS;
1673 XorSelf(Value *rhs) : RHS(rhs) {}
1674 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1675 Instruction *apply(BinaryOperator &Xor) const {
1676 return &Xor;
1677 }
1678};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001679
1680
Chris Lattner113f4f42002-06-25 16:13:24 +00001681Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001682 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001683 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001684
Chris Lattner81a7a232004-10-16 18:11:37 +00001685 if (isa<UndefValue>(Op1))
1686 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1687
Chris Lattnerc2076352004-02-16 01:20:27 +00001688 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1689 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1690 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001691 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001692 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001693
Chris Lattner97638592003-07-23 21:37:07 +00001694 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001695 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001696 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001697 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001698
Chris Lattner97638592003-07-23 21:37:07 +00001699 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001700 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001701 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001702 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001703 return new SetCondInst(SCI->getInverseCondition(),
1704 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001705
Chris Lattner8f2f5982003-11-05 01:06:05 +00001706 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001707 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1708 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001709 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1710 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001711 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001712 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001713 }
Chris Lattner023a4832004-06-18 06:07:51 +00001714
1715 // ~(~X & Y) --> (X | ~Y)
1716 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1717 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1718 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1719 Instruction *NotY =
1720 BinaryOperator::createNot(Op0I->getOperand(1),
1721 Op0I->getOperand(1)->getName()+".not");
1722 InsertNewInstBefore(NotY, I);
1723 return BinaryOperator::createOr(Op0NotVal, NotY);
1724 }
1725 }
Chris Lattner97638592003-07-23 21:37:07 +00001726
1727 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001728 switch (Op0I->getOpcode()) {
1729 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001730 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001731 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001732 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1733 return BinaryOperator::createSub(
1734 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001735 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001736 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001737 }
Chris Lattnere5806662003-11-04 23:50:51 +00001738 break;
1739 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001740 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001741 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1742 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001743 break;
1744 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001745 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001746 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001747 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001748 break;
1749 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001750 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001751 }
Chris Lattner183b3362004-04-09 19:05:30 +00001752
1753 // Try to fold constant and into select arguments.
1754 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1755 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1756 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001757 if (isa<PHINode>(Op0))
1758 if (Instruction *NV = FoldOpIntoPhi(I))
1759 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001760 }
1761
Chris Lattnerbb74e222003-03-10 23:06:50 +00001762 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001763 if (X == Op1)
1764 return ReplaceInstUsesWith(I,
1765 ConstantIntegral::getAllOnesValue(I.getType()));
1766
Chris Lattnerbb74e222003-03-10 23:06:50 +00001767 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001768 if (X == Op0)
1769 return ReplaceInstUsesWith(I,
1770 ConstantIntegral::getAllOnesValue(I.getType()));
1771
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001772 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001773 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001774 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1775 cast<BinaryOperator>(Op1I)->swapOperands();
1776 I.swapOperands();
1777 std::swap(Op0, Op1);
1778 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1779 I.swapOperands();
1780 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001781 }
1782 } else if (Op1I->getOpcode() == Instruction::Xor) {
1783 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1784 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1785 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1786 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1787 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001788
1789 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001790 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001791 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1792 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001793 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001794 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1795 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001796 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001797 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001798 } else if (Op0I->getOpcode() == Instruction::Xor) {
1799 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1800 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1801 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1802 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001803 }
1804
Chris Lattner7aa2d472004-08-01 19:42:59 +00001805 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001806 Value *A, *B; ConstantInt *C1, *C2;
1807 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1808 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00001809 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00001810 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001811
Chris Lattner3ac7c262003-08-13 20:16:26 +00001812 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1813 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1814 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1815 return R;
1816
Chris Lattner113f4f42002-06-25 16:13:24 +00001817 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001818}
1819
Chris Lattner6862fbd2004-09-29 17:40:11 +00001820/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1821/// overflowed for this type.
1822static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1823 ConstantInt *In2) {
1824 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1825 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1826}
1827
1828static bool isPositive(ConstantInt *C) {
1829 return cast<ConstantSInt>(C)->getValue() >= 0;
1830}
1831
1832/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1833/// overflowed for this type.
1834static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1835 ConstantInt *In2) {
1836 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1837
1838 if (In1->getType()->isUnsigned())
1839 return cast<ConstantUInt>(Result)->getValue() <
1840 cast<ConstantUInt>(In1)->getValue();
1841 if (isPositive(In1) != isPositive(In2))
1842 return false;
1843 if (isPositive(In1))
1844 return cast<ConstantSInt>(Result)->getValue() <
1845 cast<ConstantSInt>(In1)->getValue();
1846 return cast<ConstantSInt>(Result)->getValue() >
1847 cast<ConstantSInt>(In1)->getValue();
1848}
1849
Chris Lattner113f4f42002-06-25 16:13:24 +00001850Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001851 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001852 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1853 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001854
1855 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001856 if (Op0 == Op1)
1857 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001858
Chris Lattner81a7a232004-10-16 18:11:37 +00001859 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
1860 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
1861
Chris Lattnerd07283a2003-08-13 05:38:46 +00001862 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1863 if (isa<ConstantPointerNull>(Op1) &&
1864 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001865 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1866
Chris Lattnerd07283a2003-08-13 05:38:46 +00001867
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001868 // setcc's with boolean values can always be turned into bitwise operations
1869 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00001870 switch (I.getOpcode()) {
1871 default: assert(0 && "Invalid setcc instruction!");
1872 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001873 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001874 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001875 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001876 }
Chris Lattner4456da62004-08-11 00:50:51 +00001877 case Instruction::SetNE:
1878 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001879
Chris Lattner4456da62004-08-11 00:50:51 +00001880 case Instruction::SetGT:
1881 std::swap(Op0, Op1); // Change setgt -> setlt
1882 // FALL THROUGH
1883 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1884 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1885 InsertNewInstBefore(Not, I);
1886 return BinaryOperator::createAnd(Not, Op1);
1887 }
1888 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001889 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00001890 // FALL THROUGH
1891 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1892 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1893 InsertNewInstBefore(Not, I);
1894 return BinaryOperator::createOr(Not, Op1);
1895 }
1896 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001897 }
1898
Chris Lattner2dd01742004-06-09 04:24:29 +00001899 // See if we are doing a comparison between a constant and an instruction that
1900 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001901 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00001902 // Check to see if we are comparing against the minimum or maximum value...
1903 if (CI->isMinValue()) {
1904 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1905 return ReplaceInstUsesWith(I, ConstantBool::False);
1906 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1907 return ReplaceInstUsesWith(I, ConstantBool::True);
1908 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1909 return BinaryOperator::createSetEQ(Op0, Op1);
1910 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1911 return BinaryOperator::createSetNE(Op0, Op1);
1912
1913 } else if (CI->isMaxValue()) {
1914 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1915 return ReplaceInstUsesWith(I, ConstantBool::False);
1916 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1917 return ReplaceInstUsesWith(I, ConstantBool::True);
1918 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1919 return BinaryOperator::createSetEQ(Op0, Op1);
1920 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1921 return BinaryOperator::createSetNE(Op0, Op1);
1922
1923 // Comparing against a value really close to min or max?
1924 } else if (isMinValuePlusOne(CI)) {
1925 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1926 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
1927 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1928 return BinaryOperator::createSetNE(Op0, SubOne(CI));
1929
1930 } else if (isMaxValueMinusOne(CI)) {
1931 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1932 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
1933 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1934 return BinaryOperator::createSetNE(Op0, AddOne(CI));
1935 }
1936
1937 // If we still have a setle or setge instruction, turn it into the
1938 // appropriate setlt or setgt instruction. Since the border cases have
1939 // already been handled above, this requires little checking.
1940 //
1941 if (I.getOpcode() == Instruction::SetLE)
1942 return BinaryOperator::createSetLT(Op0, AddOne(CI));
1943 if (I.getOpcode() == Instruction::SetGE)
1944 return BinaryOperator::createSetGT(Op0, SubOne(CI));
1945
Chris Lattnere1e10e12004-05-25 06:32:08 +00001946 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001947 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001948 case Instruction::PHI:
1949 if (Instruction *NV = FoldOpIntoPhi(I))
1950 return NV;
1951 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001952 case Instruction::And:
1953 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1954 LHSI->getOperand(0)->hasOneUse()) {
1955 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1956 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1957 // happens a LOT in code produced by the C front-end, for bitfield
1958 // access.
1959 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1960 ConstantUInt *ShAmt;
1961 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1962 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1963 const Type *Ty = LHSI->getType();
1964
1965 // We can fold this as long as we can't shift unknown bits
1966 // into the mask. This can only happen with signed shift
1967 // rights, as they sign-extend.
1968 if (ShAmt) {
1969 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00001970 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001971 if (!CanFold) {
1972 // To test for the bad case of the signed shr, see if any
1973 // of the bits shifted in could be tested after the mask.
1974 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00001975 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001976 Constant *ShVal =
1977 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1978 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1979 CanFold = true;
1980 }
1981
1982 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00001983 Constant *NewCst;
1984 if (Shift->getOpcode() == Instruction::Shl)
1985 NewCst = ConstantExpr::getUShr(CI, ShAmt);
1986 else
1987 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00001988
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001989 // Check to see if we are shifting out any of the bits being
1990 // compared.
1991 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1992 // If we shifted bits out, the fold is not going to work out.
1993 // As a special case, check to see if this means that the
1994 // result is always true or false now.
1995 if (I.getOpcode() == Instruction::SetEQ)
1996 return ReplaceInstUsesWith(I, ConstantBool::False);
1997 if (I.getOpcode() == Instruction::SetNE)
1998 return ReplaceInstUsesWith(I, ConstantBool::True);
1999 } else {
2000 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002001 Constant *NewAndCST;
2002 if (Shift->getOpcode() == Instruction::Shl)
2003 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2004 else
2005 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2006 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002007 LHSI->setOperand(0, Shift->getOperand(0));
2008 WorkList.push_back(Shift); // Shift is dead.
2009 AddUsesToWorkList(I);
2010 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002011 }
2012 }
Chris Lattner35167c32004-06-09 07:59:58 +00002013 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002014 }
2015 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002016
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002017 case Instruction::Cast: { // (setcc (cast X to larger), CI)
2018 const Type *SrcTy = LHSI->getOperand(0)->getType();
2019 if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) {
Chris Lattnerc9491282004-09-29 03:16:24 +00002020 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002021 if (SrcTy == Type::BoolTy) SrcBits = 1;
Chris Lattnerc9491282004-09-29 03:16:24 +00002022 unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002023 if (LHSI->getType() == Type::BoolTy) DestBits = 1;
2024 if (SrcBits < DestBits) {
2025 // Check to see if the comparison is always true or false.
2026 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
2027 if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
2028 Constant *Min = ConstantIntegral::getMinValue(SrcTy);
2029 Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
2030 Min = ConstantExpr::getCast(Min, LHSI->getType());
2031 Max = ConstantExpr::getCast(Max, LHSI->getType());
2032 switch (I.getOpcode()) {
2033 default: assert(0 && "unknown integer comparison");
2034 case Instruction::SetEQ:
2035 return ReplaceInstUsesWith(I, ConstantBool::False);
2036 case Instruction::SetNE:
2037 return ReplaceInstUsesWith(I, ConstantBool::True);
2038 case Instruction::SetLT:
2039 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002040 case Instruction::SetGT:
2041 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002042 }
2043 }
2044
2045 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
2046 ConstantExpr::getCast(CI, SrcTy));
2047 }
2048 }
2049 break;
2050 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00002051 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2052 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2053 switch (I.getOpcode()) {
2054 default: break;
2055 case Instruction::SetEQ:
2056 case Instruction::SetNE: {
2057 // If we are comparing against bits always shifted out, the
2058 // comparison cannot succeed.
2059 Constant *Comp =
2060 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2061 if (Comp != CI) {// Comparing against a bit that we know is zero.
2062 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2063 Constant *Cst = ConstantBool::get(IsSetNE);
2064 return ReplaceInstUsesWith(I, Cst);
2065 }
2066
2067 if (LHSI->hasOneUse()) {
2068 // Otherwise strength reduce the shift into an and.
2069 unsigned ShAmtVal = ShAmt->getValue();
2070 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2071 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2072
2073 Constant *Mask;
2074 if (CI->getType()->isUnsigned()) {
2075 Mask = ConstantUInt::get(CI->getType(), Val);
2076 } else if (ShAmtVal != 0) {
2077 Mask = ConstantSInt::get(CI->getType(), Val);
2078 } else {
2079 Mask = ConstantInt::getAllOnesValue(CI->getType());
2080 }
2081
2082 Instruction *AndI =
2083 BinaryOperator::createAnd(LHSI->getOperand(0),
2084 Mask, LHSI->getName()+".mask");
2085 Value *And = InsertNewInstBefore(AndI, I);
2086 return new SetCondInst(I.getOpcode(), And,
2087 ConstantExpr::getUShr(CI, ShAmt));
2088 }
2089 }
2090 }
2091 }
2092 break;
2093
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002094 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002095 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002096 switch (I.getOpcode()) {
2097 default: break;
2098 case Instruction::SetEQ:
2099 case Instruction::SetNE: {
2100 // If we are comparing against bits always shifted out, the
2101 // comparison cannot succeed.
2102 Constant *Comp =
2103 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2104
2105 if (Comp != CI) {// Comparing against a bit that we know is zero.
2106 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2107 Constant *Cst = ConstantBool::get(IsSetNE);
2108 return ReplaceInstUsesWith(I, Cst);
2109 }
2110
2111 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00002112 unsigned ShAmtVal = ShAmt->getValue();
2113
Chris Lattner1023b872004-09-27 16:18:50 +00002114 // Otherwise strength reduce the shift into an and.
2115 uint64_t Val = ~0ULL; // All ones.
2116 Val <<= ShAmtVal; // Shift over to the right spot.
2117
2118 Constant *Mask;
2119 if (CI->getType()->isUnsigned()) {
2120 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2121 Val &= (1ULL << TypeBits)-1;
2122 Mask = ConstantUInt::get(CI->getType(), Val);
2123 } else {
2124 Mask = ConstantSInt::get(CI->getType(), Val);
2125 }
2126
2127 Instruction *AndI =
2128 BinaryOperator::createAnd(LHSI->getOperand(0),
2129 Mask, LHSI->getName()+".mask");
2130 Value *And = InsertNewInstBefore(AndI, I);
2131 return new SetCondInst(I.getOpcode(), And,
2132 ConstantExpr::getShl(CI, ShAmt));
2133 }
2134 break;
2135 }
2136 }
2137 }
2138 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002139
Chris Lattner6862fbd2004-09-29 17:40:11 +00002140 case Instruction::Div:
2141 // Fold: (div X, C1) op C2 -> range check
2142 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2143 // Fold this div into the comparison, producing a range check.
2144 // Determine, based on the divide type, what the range is being
2145 // checked. If there is an overflow on the low or high side, remember
2146 // it, otherwise compute the range [low, hi) bounding the new value.
2147 bool LoOverflow = false, HiOverflow = 0;
2148 ConstantInt *LoBound = 0, *HiBound = 0;
2149
2150 ConstantInt *Prod;
2151 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2152
Chris Lattnera92af962004-10-11 19:40:04 +00002153 Instruction::BinaryOps Opcode = I.getOpcode();
2154
Chris Lattner6862fbd2004-09-29 17:40:11 +00002155 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2156 } else if (LHSI->getType()->isUnsigned()) { // udiv
2157 LoBound = Prod;
2158 LoOverflow = ProdOV;
2159 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2160 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2161 if (CI->isNullValue()) { // (X / pos) op 0
2162 // Can't overflow.
2163 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2164 HiBound = DivRHS;
2165 } else if (isPositive(CI)) { // (X / pos) op pos
2166 LoBound = Prod;
2167 LoOverflow = ProdOV;
2168 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2169 } else { // (X / pos) op neg
2170 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2171 LoOverflow = AddWithOverflow(LoBound, Prod,
2172 cast<ConstantInt>(DivRHSH));
2173 HiBound = Prod;
2174 HiOverflow = ProdOV;
2175 }
2176 } else { // Divisor is < 0.
2177 if (CI->isNullValue()) { // (X / neg) op 0
2178 LoBound = AddOne(DivRHS);
2179 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2180 } else if (isPositive(CI)) { // (X / neg) op pos
2181 HiOverflow = LoOverflow = ProdOV;
2182 if (!LoOverflow)
2183 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2184 HiBound = AddOne(Prod);
2185 } else { // (X / neg) op neg
2186 LoBound = Prod;
2187 LoOverflow = HiOverflow = ProdOV;
2188 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2189 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002190
Chris Lattnera92af962004-10-11 19:40:04 +00002191 // Dividing by a negate swaps the condition.
2192 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002193 }
2194
2195 if (LoBound) {
2196 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002197 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002198 default: assert(0 && "Unhandled setcc opcode!");
2199 case Instruction::SetEQ:
2200 if (LoOverflow && HiOverflow)
2201 return ReplaceInstUsesWith(I, ConstantBool::False);
2202 else if (HiOverflow)
2203 return new SetCondInst(Instruction::SetGE, X, LoBound);
2204 else if (LoOverflow)
2205 return new SetCondInst(Instruction::SetLT, X, HiBound);
2206 else
2207 return InsertRangeTest(X, LoBound, HiBound, true, I);
2208 case Instruction::SetNE:
2209 if (LoOverflow && HiOverflow)
2210 return ReplaceInstUsesWith(I, ConstantBool::True);
2211 else if (HiOverflow)
2212 return new SetCondInst(Instruction::SetLT, X, LoBound);
2213 else if (LoOverflow)
2214 return new SetCondInst(Instruction::SetGE, X, HiBound);
2215 else
2216 return InsertRangeTest(X, LoBound, HiBound, false, I);
2217 case Instruction::SetLT:
2218 if (LoOverflow)
2219 return ReplaceInstUsesWith(I, ConstantBool::False);
2220 return new SetCondInst(Instruction::SetLT, X, LoBound);
2221 case Instruction::SetGT:
2222 if (HiOverflow)
2223 return ReplaceInstUsesWith(I, ConstantBool::False);
2224 return new SetCondInst(Instruction::SetGE, X, HiBound);
2225 }
2226 }
2227 }
2228 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002229 case Instruction::Select:
2230 // If either operand of the select is a constant, we can fold the
2231 // comparison into the select arms, which will cause one to be
2232 // constant folded and the select turned into a bitwise or.
2233 Value *Op1 = 0, *Op2 = 0;
2234 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00002235 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002236 // Fold the known value into the constant operand.
2237 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2238 // Insert a new SetCC of the other select operand.
2239 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002240 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002241 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00002242 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002243 // Fold the known value into the constant operand.
2244 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2245 // Insert a new SetCC of the other select operand.
2246 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002247 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002248 I.getName()), I);
2249 }
Chris Lattner2dd01742004-06-09 04:24:29 +00002250 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002251
2252 if (Op1)
2253 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2254 break;
2255 }
2256
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002257 // Simplify seteq and setne instructions...
2258 if (I.getOpcode() == Instruction::SetEQ ||
2259 I.getOpcode() == Instruction::SetNE) {
2260 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2261
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002262 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002263 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002264 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2265 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002266 case Instruction::Rem:
2267 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2268 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2269 BO->hasOneUse() &&
2270 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2271 if (unsigned L2 =
2272 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2273 const Type *UTy = BO->getType()->getUnsignedVersion();
2274 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2275 UTy, "tmp"), I);
2276 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2277 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2278 RHSCst, BO->getName()), I);
2279 return BinaryOperator::create(I.getOpcode(), NewRem,
2280 Constant::getNullValue(UTy));
2281 }
2282 break;
2283
Chris Lattnerc992add2003-08-13 05:33:12 +00002284 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002285 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2286 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002287 if (BO->hasOneUse())
2288 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2289 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002290 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002291 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2292 // efficiently invertible, or if the add has just this one use.
2293 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00002294
Chris Lattnerc992add2003-08-13 05:33:12 +00002295 if (Value *NegVal = dyn_castNegVal(BOp1))
2296 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2297 else if (Value *NegVal = dyn_castNegVal(BOp0))
2298 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002299 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002300 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2301 BO->setName("");
2302 InsertNewInstBefore(Neg, I);
2303 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2304 }
2305 }
2306 break;
2307 case Instruction::Xor:
2308 // For the xor case, we can xor two constants together, eliminating
2309 // the explicit xor.
2310 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2311 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002312 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002313
2314 // FALLTHROUGH
2315 case Instruction::Sub:
2316 // Replace (([sub|xor] A, B) != 0) with (A != B)
2317 if (CI->isNullValue())
2318 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2319 BO->getOperand(1));
2320 break;
2321
2322 case Instruction::Or:
2323 // If bits are being or'd in that are not present in the constant we
2324 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002325 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002326 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002327 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002328 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002329 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002330 break;
2331
2332 case Instruction::And:
2333 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002334 // If bits are being compared against that are and'd out, then the
2335 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002336 if (!ConstantExpr::getAnd(CI,
2337 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002338 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002339
Chris Lattner35167c32004-06-09 07:59:58 +00002340 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002341 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002342 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2343 Instruction::SetNE, Op0,
2344 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002345
Chris Lattnerc992add2003-08-13 05:33:12 +00002346 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2347 // to be a signed value as appropriate.
2348 if (isSignBit(BOC)) {
2349 Value *X = BO->getOperand(0);
2350 // If 'X' is not signed, insert a cast now...
2351 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002352 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002353 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002354 }
2355 return new SetCondInst(isSetNE ? Instruction::SetLT :
2356 Instruction::SetGE, X,
2357 Constant::getNullValue(X->getType()));
2358 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002359
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002360 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002361 if (CI->isNullValue() && isHighOnes(BOC)) {
2362 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002363 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002364
2365 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002366 if (NegX->getType()->isSigned()) {
2367 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2368 X = InsertCastBefore(X, DestTy, I);
2369 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002370 }
2371
2372 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002373 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002374 }
2375
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002376 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002377 default: break;
2378 }
2379 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002380 } else { // Not a SetEQ/SetNE
2381 // If the LHS is a cast from an integral value of the same size,
2382 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2383 Value *CastOp = Cast->getOperand(0);
2384 const Type *SrcTy = CastOp->getType();
2385 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2386 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2387 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2388 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2389 "Source and destination signednesses should differ!");
2390 if (Cast->getType()->isSigned()) {
2391 // If this is a signed comparison, check for comparisons in the
2392 // vicinity of zero.
2393 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2394 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002395 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002396 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2397 else if (I.getOpcode() == Instruction::SetGT &&
2398 cast<ConstantSInt>(CI)->getValue() == -1)
2399 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002400 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002401 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2402 } else {
2403 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2404 if (I.getOpcode() == Instruction::SetLT &&
2405 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2406 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002407 return BinaryOperator::createSetGT(CastOp,
2408 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002409 else if (I.getOpcode() == Instruction::SetGT &&
2410 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2411 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002412 return BinaryOperator::createSetLT(CastOp,
2413 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002414 }
2415 }
2416 }
Chris Lattnere967b342003-06-04 05:10:11 +00002417 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002418 }
2419
Chris Lattner16930792003-11-03 04:25:02 +00002420 // Test to see if the operands of the setcc are casted versions of other
2421 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002422 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2423 Value *CastOp0 = CI->getOperand(0);
2424 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002425 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002426 (I.getOpcode() == Instruction::SetEQ ||
2427 I.getOpcode() == Instruction::SetNE)) {
2428 // We keep moving the cast from the left operand over to the right
2429 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002430 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002431
2432 // If operand #1 is a cast instruction, see if we can eliminate it as
2433 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002434 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2435 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002436 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002437 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002438
2439 // If Op1 is a constant, we can fold the cast into the constant.
2440 if (Op1->getType() != Op0->getType())
2441 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2442 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2443 } else {
2444 // Otherwise, cast the RHS right before the setcc
2445 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2446 InsertNewInstBefore(cast<Instruction>(Op1), I);
2447 }
2448 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2449 }
2450
Chris Lattner6444c372003-11-03 05:17:03 +00002451 // Handle the special case of: setcc (cast bool to X), <cst>
2452 // This comes up when you have code like
2453 // int X = A < B;
2454 // if (X) ...
2455 // For generality, we handle any zero-extension of any operand comparison
2456 // with a constant.
2457 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2458 const Type *SrcTy = CastOp0->getType();
2459 const Type *DestTy = Op0->getType();
2460 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2461 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2462 // Ok, we have an expansion of operand 0 into a new type. Get the
2463 // constant value, masink off bits which are not set in the RHS. These
2464 // could be set if the destination value is signed.
2465 uint64_t ConstVal = ConstantRHS->getRawValue();
2466 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2467
2468 // If the constant we are comparing it with has high bits set, which
2469 // don't exist in the original value, the values could never be equal,
2470 // because the source would be zero extended.
2471 unsigned SrcBits =
2472 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002473 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2474 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002475 switch (I.getOpcode()) {
2476 default: assert(0 && "Unknown comparison type!");
2477 case Instruction::SetEQ:
2478 return ReplaceInstUsesWith(I, ConstantBool::False);
2479 case Instruction::SetNE:
2480 return ReplaceInstUsesWith(I, ConstantBool::True);
2481 case Instruction::SetLT:
2482 case Instruction::SetLE:
2483 if (DestTy->isSigned() && HasSignBit)
2484 return ReplaceInstUsesWith(I, ConstantBool::False);
2485 return ReplaceInstUsesWith(I, ConstantBool::True);
2486 case Instruction::SetGT:
2487 case Instruction::SetGE:
2488 if (DestTy->isSigned() && HasSignBit)
2489 return ReplaceInstUsesWith(I, ConstantBool::True);
2490 return ReplaceInstUsesWith(I, ConstantBool::False);
2491 }
2492 }
2493
2494 // Otherwise, we can replace the setcc with a setcc of the smaller
2495 // operand value.
2496 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2497 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2498 }
2499 }
2500 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002501 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002502}
2503
2504
2505
Chris Lattnere8d6c602003-03-10 19:16:08 +00002506Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002507 assert(I.getOperand(1)->getType() == Type::UByteTy);
2508 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002509 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002510
2511 // shl X, 0 == X and shr X, 0 == X
2512 // shl 0, X == 0 and shr 0, X == 0
2513 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00002514 Op0 == Constant::getNullValue(Op0->getType()))
2515 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002516
Chris Lattner81a7a232004-10-16 18:11:37 +00002517 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
2518 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00002519 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00002520 else // undef << X -> 0 AND undef >>u X -> 0
2521 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2522 }
2523 if (isa<UndefValue>(Op1)) {
2524 if (isLeftShift || I.getType()->isUnsigned())
2525 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2526 else
2527 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
2528 }
2529
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002530 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2531 if (!isLeftShift)
2532 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2533 if (CSI->isAllOnesValue())
2534 return ReplaceInstUsesWith(I, CSI);
2535
Chris Lattner183b3362004-04-09 19:05:30 +00002536 // Try to fold constant and into select arguments.
2537 if (isa<Constant>(Op0))
2538 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2539 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2540 return R;
2541
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002542 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002543 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2544 // of a signed value.
2545 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00002546 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002547 if (CUI->getValue() >= TypeBits) {
2548 if (!Op0->getType()->isSigned() || isLeftShift)
2549 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2550 else {
2551 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2552 return &I;
2553 }
2554 }
Chris Lattner55f3d942002-09-10 23:04:09 +00002555
Chris Lattnerede3fe02003-08-13 04:18:28 +00002556 // ((X*C1) << C2) == (X * (C1 << C2))
2557 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2558 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2559 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002560 return BinaryOperator::createMul(BO->getOperand(0),
2561 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00002562
Chris Lattner183b3362004-04-09 19:05:30 +00002563 // Try to fold constant and into select arguments.
2564 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2565 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2566 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002567 if (isa<PHINode>(Op0))
2568 if (Instruction *NV = FoldOpIntoPhi(I))
2569 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00002570
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002571 // If the operand is an bitwise operator with a constant RHS, and the
2572 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002573 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002574 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2575 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2576 bool isValid = true; // Valid only for And, Or, Xor
2577 bool highBitSet = false; // Transform if high bit of constant set?
2578
2579 switch (Op0BO->getOpcode()) {
2580 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00002581 case Instruction::Add:
2582 isValid = isLeftShift;
2583 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002584 case Instruction::Or:
2585 case Instruction::Xor:
2586 highBitSet = false;
2587 break;
2588 case Instruction::And:
2589 highBitSet = true;
2590 break;
2591 }
2592
2593 // If this is a signed shift right, and the high bit is modified
2594 // by the logical operation, do not perform the transformation.
2595 // The highBitSet boolean indicates the value of the high bit of
2596 // the constant which would cause it to be modified for this
2597 // operation.
2598 //
2599 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2600 uint64_t Val = Op0C->getRawValue();
2601 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2602 }
2603
2604 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002605 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002606
2607 Instruction *NewShift =
2608 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2609 Op0BO->getName());
2610 Op0BO->setName("");
2611 InsertNewInstBefore(NewShift, I);
2612
2613 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2614 NewRHS);
2615 }
2616 }
2617
Chris Lattner3204d4e2003-07-24 17:52:58 +00002618 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002619 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00002620 if (ConstantUInt *ShiftAmt1C =
2621 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002622 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2623 unsigned ShiftAmt2 = CUI->getValue();
2624
2625 // Check for (A << c1) << c2 and (A >> c1) >> c2
2626 if (I.getOpcode() == Op0SI->getOpcode()) {
2627 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002628 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2629 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00002630 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2631 ConstantUInt::get(Type::UByteTy, Amt));
2632 }
2633
Chris Lattnerab780df2003-07-24 18:38:56 +00002634 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2635 // signed types, we can only support the (A >> c1) << c2 configuration,
2636 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002637 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002638 // Calculate bitmask for what gets shifted off the edge...
2639 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002640 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002641 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002642 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002643 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00002644
2645 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002646 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2647 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00002648 InsertNewInstBefore(Mask, I);
2649
2650 // Figure out what flavor of shift we should use...
2651 if (ShiftAmt1 == ShiftAmt2)
2652 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2653 else if (ShiftAmt1 < ShiftAmt2) {
2654 return new ShiftInst(I.getOpcode(), Mask,
2655 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2656 } else {
2657 return new ShiftInst(Op0SI->getOpcode(), Mask,
2658 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2659 }
2660 }
2661 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002662 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00002663
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002664 return 0;
2665}
2666
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002667enum CastType {
2668 Noop = 0,
2669 Truncate = 1,
2670 Signext = 2,
2671 Zeroext = 3
2672};
2673
2674/// getCastType - In the future, we will split the cast instruction into these
2675/// various types. Until then, we have to do the analysis here.
2676static CastType getCastType(const Type *Src, const Type *Dest) {
2677 assert(Src->isIntegral() && Dest->isIntegral() &&
2678 "Only works on integral types!");
2679 unsigned SrcSize = Src->getPrimitiveSize()*8;
2680 if (Src == Type::BoolTy) SrcSize = 1;
2681 unsigned DestSize = Dest->getPrimitiveSize()*8;
2682 if (Dest == Type::BoolTy) DestSize = 1;
2683
2684 if (SrcSize == DestSize) return Noop;
2685 if (SrcSize > DestSize) return Truncate;
2686 if (Src->isSigned()) return Signext;
2687 return Zeroext;
2688}
2689
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002690
Chris Lattner48a44f72002-05-02 17:06:02 +00002691// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2692// instruction.
2693//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002694static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00002695 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002696
Chris Lattner650b6da2002-08-02 20:00:25 +00002697 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2698 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00002699 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00002700 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00002701 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00002702
Chris Lattner4fbad962004-07-21 04:27:24 +00002703 // If we are casting between pointer and integer types, treat pointers as
2704 // integers of the appropriate size for the code below.
2705 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2706 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2707 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00002708
Chris Lattner48a44f72002-05-02 17:06:02 +00002709 // Allow free casting and conversion of sizes as long as the sign doesn't
2710 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002711 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002712 CastType FirstCast = getCastType(SrcTy, MidTy);
2713 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00002714
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002715 // Capture the effect of these two casts. If the result is a legal cast,
2716 // the CastType is stored here, otherwise a special code is used.
2717 static const unsigned CastResult[] = {
2718 // First cast is noop
2719 0, 1, 2, 3,
2720 // First cast is a truncate
2721 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2722 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00002723 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002724 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00002725 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002726 };
2727
2728 unsigned Result = CastResult[FirstCast*4+SecondCast];
2729 switch (Result) {
2730 default: assert(0 && "Illegal table value!");
2731 case 0:
2732 case 1:
2733 case 2:
2734 case 3:
2735 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2736 // truncates, we could eliminate more casts.
2737 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2738 case 4:
2739 return false; // Not possible to eliminate this here.
2740 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00002741 // Sign or zero extend followed by truncate is always ok if the result
2742 // is a truncate or noop.
2743 CastType ResultCast = getCastType(SrcTy, DstTy);
2744 if (ResultCast == Noop || ResultCast == Truncate)
2745 return true;
2746 // Otherwise we are still growing the value, we are only safe if the
2747 // result will match the sign/zeroextendness of the result.
2748 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00002749 }
Chris Lattner650b6da2002-08-02 20:00:25 +00002750 }
Chris Lattner48a44f72002-05-02 17:06:02 +00002751 return false;
2752}
2753
Chris Lattner11ffd592004-07-20 05:21:00 +00002754static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002755 if (V->getType() == Ty || isa<Constant>(V)) return false;
2756 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00002757 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2758 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002759 return false;
2760 return true;
2761}
2762
2763/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2764/// InsertBefore instruction. This is specialized a bit to avoid inserting
2765/// casts that are known to not do anything...
2766///
2767Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2768 Instruction *InsertBefore) {
2769 if (V->getType() == DestTy) return V;
2770 if (Constant *C = dyn_cast<Constant>(V))
2771 return ConstantExpr::getCast(C, DestTy);
2772
2773 CastInst *CI = new CastInst(V, DestTy, V->getName());
2774 InsertNewInstBefore(CI, *InsertBefore);
2775 return CI;
2776}
Chris Lattner48a44f72002-05-02 17:06:02 +00002777
2778// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002779//
Chris Lattner113f4f42002-06-25 16:13:24 +00002780Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002781 Value *Src = CI.getOperand(0);
2782
Chris Lattner48a44f72002-05-02 17:06:02 +00002783 // If the user is casting a value to the same type, eliminate this cast
2784 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002785 if (CI.getType() == Src->getType())
2786 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002787
Chris Lattner81a7a232004-10-16 18:11:37 +00002788 if (isa<UndefValue>(Src)) // cast undef -> undef
2789 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
2790
Chris Lattner48a44f72002-05-02 17:06:02 +00002791 // If casting the result of another cast instruction, try to eliminate this
2792 // one!
2793 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002794 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002795 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner11ffd592004-07-20 05:21:00 +00002796 CSrc->getType(), CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002797 // This instruction now refers directly to the cast's src operand. This
2798 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002799 CI.setOperand(0, CSrc->getOperand(0));
2800 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002801 }
2802
Chris Lattner650b6da2002-08-02 20:00:25 +00002803 // If this is an A->B->A cast, and we are dealing with integral types, try
2804 // to convert this into a logical 'and' instruction.
2805 //
2806 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002807 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002808 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2809 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2810 assert(CSrc->getType() != Type::ULongTy &&
2811 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002812 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002813 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002814 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002815 }
2816 }
2817
Chris Lattner03841652004-05-25 04:29:21 +00002818 // If this is a cast to bool, turn it into the appropriate setne instruction.
2819 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002820 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002821 Constant::getNullValue(CI.getOperand(0)->getType()));
2822
Chris Lattnerd0d51602003-06-21 23:12:02 +00002823 // If casting the result of a getelementptr instruction with no offset, turn
2824 // this into a cast of the original pointer!
2825 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002826 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002827 bool AllZeroOperands = true;
2828 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2829 if (!isa<Constant>(GEP->getOperand(i)) ||
2830 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2831 AllZeroOperands = false;
2832 break;
2833 }
2834 if (AllZeroOperands) {
2835 CI.setOperand(0, GEP->getOperand(0));
2836 return &CI;
2837 }
2838 }
2839
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002840 // If we are casting a malloc or alloca to a pointer to a type of the same
2841 // size, rewrite the allocation instruction to allocate the "right" type.
2842 //
2843 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002844 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002845 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2846 // Get the type really allocated and the type casted to...
2847 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002848 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002849 if (AllocElTy->isSized() && CastElTy->isSized()) {
2850 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2851 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002852
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002853 // If the allocation is for an even multiple of the cast type size
2854 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2855 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002856 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002857 std::string Name = AI->getName(); AI->setName("");
2858 AllocationInst *New;
2859 if (isa<MallocInst>(AI))
2860 New = new MallocInst(CastElTy, Amt, Name);
2861 else
2862 New = new AllocaInst(CastElTy, Amt, Name);
2863 InsertNewInstBefore(New, *AI);
2864 return ReplaceInstUsesWith(CI, New);
2865 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002866 }
2867 }
2868
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002869 if (isa<PHINode>(Src))
2870 if (Instruction *NV = FoldOpIntoPhi(CI))
2871 return NV;
2872
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002873 // If the source value is an instruction with only this use, we can attempt to
2874 // propagate the cast into the instruction. Also, only handle integral types
2875 // for now.
2876 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002877 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002878 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2879 const Type *DestTy = CI.getType();
2880 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2881 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2882
2883 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2884 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2885
2886 switch (SrcI->getOpcode()) {
2887 case Instruction::Add:
2888 case Instruction::Mul:
2889 case Instruction::And:
2890 case Instruction::Or:
2891 case Instruction::Xor:
2892 // If we are discarding information, or just changing the sign, rewrite.
2893 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2894 // Don't insert two casts if they cannot be eliminated. We allow two
2895 // casts to be inserted if the sizes are the same. This could only be
2896 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00002897 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2898 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002899 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2900 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2901 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2902 ->getOpcode(), Op0c, Op1c);
2903 }
2904 }
2905 break;
2906 case Instruction::Shl:
2907 // Allow changing the sign of the source operand. Do not allow changing
2908 // the size of the shift, UNLESS the shift amount is a constant. We
2909 // mush not change variable sized shifts to a smaller size, because it
2910 // is undefined to shift more bits out than exist in the value.
2911 if (DestBitSize == SrcBitSize ||
2912 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2913 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2914 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2915 }
2916 break;
2917 }
2918 }
2919
Chris Lattner260ab202002-04-18 17:39:14 +00002920 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00002921}
2922
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002923/// GetSelectFoldableOperands - We want to turn code that looks like this:
2924/// %C = or %A, %B
2925/// %D = select %cond, %C, %A
2926/// into:
2927/// %C = select %cond, %B, 0
2928/// %D = or %A, %C
2929///
2930/// Assuming that the specified instruction is an operand to the select, return
2931/// a bitmask indicating which operands of this instruction are foldable if they
2932/// equal the other incoming value of the select.
2933///
2934static unsigned GetSelectFoldableOperands(Instruction *I) {
2935 switch (I->getOpcode()) {
2936 case Instruction::Add:
2937 case Instruction::Mul:
2938 case Instruction::And:
2939 case Instruction::Or:
2940 case Instruction::Xor:
2941 return 3; // Can fold through either operand.
2942 case Instruction::Sub: // Can only fold on the amount subtracted.
2943 case Instruction::Shl: // Can only fold on the shift amount.
2944 case Instruction::Shr:
2945 return 1;
2946 default:
2947 return 0; // Cannot fold
2948 }
2949}
2950
2951/// GetSelectFoldableConstant - For the same transformation as the previous
2952/// function, return the identity constant that goes into the select.
2953static Constant *GetSelectFoldableConstant(Instruction *I) {
2954 switch (I->getOpcode()) {
2955 default: assert(0 && "This cannot happen!"); abort();
2956 case Instruction::Add:
2957 case Instruction::Sub:
2958 case Instruction::Or:
2959 case Instruction::Xor:
2960 return Constant::getNullValue(I->getType());
2961 case Instruction::Shl:
2962 case Instruction::Shr:
2963 return Constant::getNullValue(Type::UByteTy);
2964 case Instruction::And:
2965 return ConstantInt::getAllOnesValue(I->getType());
2966 case Instruction::Mul:
2967 return ConstantInt::get(I->getType(), 1);
2968 }
2969}
2970
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002971Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00002972 Value *CondVal = SI.getCondition();
2973 Value *TrueVal = SI.getTrueValue();
2974 Value *FalseVal = SI.getFalseValue();
2975
2976 // select true, X, Y -> X
2977 // select false, X, Y -> Y
2978 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002979 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00002980 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002981 else {
2982 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00002983 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002984 }
Chris Lattner533bc492004-03-30 19:37:13 +00002985
2986 // select C, X, X -> X
2987 if (TrueVal == FalseVal)
2988 return ReplaceInstUsesWith(SI, TrueVal);
2989
Chris Lattner81a7a232004-10-16 18:11:37 +00002990 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2991 return ReplaceInstUsesWith(SI, FalseVal);
2992 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2993 return ReplaceInstUsesWith(SI, TrueVal);
2994 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2995 if (isa<Constant>(TrueVal))
2996 return ReplaceInstUsesWith(SI, TrueVal);
2997 else
2998 return ReplaceInstUsesWith(SI, FalseVal);
2999 }
3000
Chris Lattner1c631e82004-04-08 04:43:23 +00003001 if (SI.getType() == Type::BoolTy)
3002 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3003 if (C == ConstantBool::True) {
3004 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003005 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003006 } else {
3007 // Change: A = select B, false, C --> A = and !B, C
3008 Value *NotCond =
3009 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3010 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003011 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003012 }
3013 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3014 if (C == ConstantBool::False) {
3015 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003016 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003017 } else {
3018 // Change: A = select B, C, true --> A = or !B, C
3019 Value *NotCond =
3020 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3021 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003022 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003023 }
3024 }
3025
Chris Lattner183b3362004-04-09 19:05:30 +00003026 // Selecting between two integer constants?
3027 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3028 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3029 // select C, 1, 0 -> cast C to int
3030 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3031 return new CastInst(CondVal, SI.getType());
3032 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3033 // select C, 0, 1 -> cast !C to int
3034 Value *NotCond =
3035 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00003036 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00003037 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00003038 }
Chris Lattner35167c32004-06-09 07:59:58 +00003039
3040 // If one of the constants is zero (we know they can't both be) and we
3041 // have a setcc instruction with zero, and we have an 'and' with the
3042 // non-constant value, eliminate this whole mess. This corresponds to
3043 // cases like this: ((X & 27) ? 27 : 0)
3044 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3045 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3046 if ((IC->getOpcode() == Instruction::SetEQ ||
3047 IC->getOpcode() == Instruction::SetNE) &&
3048 isa<ConstantInt>(IC->getOperand(1)) &&
3049 cast<Constant>(IC->getOperand(1))->isNullValue())
3050 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3051 if (ICA->getOpcode() == Instruction::And &&
3052 isa<ConstantInt>(ICA->getOperand(1)) &&
3053 (ICA->getOperand(1) == TrueValC ||
3054 ICA->getOperand(1) == FalseValC) &&
3055 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3056 // Okay, now we know that everything is set up, we just don't
3057 // know whether we have a setne or seteq and whether the true or
3058 // false val is the zero.
3059 bool ShouldNotVal = !TrueValC->isNullValue();
3060 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3061 Value *V = ICA;
3062 if (ShouldNotVal)
3063 V = InsertNewInstBefore(BinaryOperator::create(
3064 Instruction::Xor, V, ICA->getOperand(1)), SI);
3065 return ReplaceInstUsesWith(SI, V);
3066 }
Chris Lattner533bc492004-03-30 19:37:13 +00003067 }
Chris Lattner623fba12004-04-10 22:21:27 +00003068
3069 // See if we are selecting two values based on a comparison of the two values.
3070 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3071 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3072 // Transform (X == Y) ? X : Y -> Y
3073 if (SCI->getOpcode() == Instruction::SetEQ)
3074 return ReplaceInstUsesWith(SI, FalseVal);
3075 // Transform (X != Y) ? X : Y -> X
3076 if (SCI->getOpcode() == Instruction::SetNE)
3077 return ReplaceInstUsesWith(SI, TrueVal);
3078 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3079
3080 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3081 // Transform (X == Y) ? Y : X -> X
3082 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003083 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003084 // Transform (X != Y) ? Y : X -> Y
3085 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003086 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003087 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3088 }
3089 }
Chris Lattner1c631e82004-04-08 04:43:23 +00003090
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003091 // See if we can fold the select into one of our operands.
3092 if (SI.getType()->isInteger()) {
3093 // See the comment above GetSelectFoldableOperands for a description of the
3094 // transformation we are doing here.
3095 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3096 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3097 !isa<Constant>(FalseVal))
3098 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3099 unsigned OpToFold = 0;
3100 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3101 OpToFold = 1;
3102 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3103 OpToFold = 2;
3104 }
3105
3106 if (OpToFold) {
3107 Constant *C = GetSelectFoldableConstant(TVI);
3108 std::string Name = TVI->getName(); TVI->setName("");
3109 Instruction *NewSel =
3110 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3111 Name);
3112 InsertNewInstBefore(NewSel, SI);
3113 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3114 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3115 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3116 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3117 else {
3118 assert(0 && "Unknown instruction!!");
3119 }
3120 }
3121 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003122
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003123 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3124 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3125 !isa<Constant>(TrueVal))
3126 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3127 unsigned OpToFold = 0;
3128 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3129 OpToFold = 1;
3130 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3131 OpToFold = 2;
3132 }
3133
3134 if (OpToFold) {
3135 Constant *C = GetSelectFoldableConstant(FVI);
3136 std::string Name = FVI->getName(); FVI->setName("");
3137 Instruction *NewSel =
3138 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3139 Name);
3140 InsertNewInstBefore(NewSel, SI);
3141 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3142 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3143 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3144 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3145 else {
3146 assert(0 && "Unknown instruction!!");
3147 }
3148 }
3149 }
3150 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003151 return 0;
3152}
3153
3154
Chris Lattner970c33a2003-06-19 17:00:31 +00003155// CallInst simplification
3156//
3157Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003158 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3159 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00003160 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3161 bool Changed = false;
3162
3163 // memmove/cpy/set of zero bytes is a noop.
3164 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3165 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3166
3167 // FIXME: Increase alignment here.
3168
3169 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3170 if (CI->getRawValue() == 1) {
3171 // Replace the instruction with just byte operations. We would
3172 // transform other cases to loads/stores, but we don't know if
3173 // alignment is sufficient.
3174 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003175 }
3176
Chris Lattner00648e12004-10-12 04:52:52 +00003177 // If we have a memmove and the source operation is a constant global,
3178 // then the source and dest pointers can't alias, so we can change this
3179 // into a call to memcpy.
3180 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3181 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3182 if (GVSrc->isConstant()) {
3183 Module *M = CI.getParent()->getParent()->getParent();
3184 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3185 CI.getCalledFunction()->getFunctionType());
3186 CI.setOperand(0, MemCpy);
3187 Changed = true;
3188 }
3189
3190 if (Changed) return &CI;
3191 }
3192
Chris Lattneraec3d942003-10-07 22:32:43 +00003193 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003194}
3195
3196// InvokeInst simplification
3197//
3198Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003199 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003200}
3201
Chris Lattneraec3d942003-10-07 22:32:43 +00003202// visitCallSite - Improvements for call and invoke instructions.
3203//
3204Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003205 bool Changed = false;
3206
3207 // If the callee is a constexpr cast of a function, attempt to move the cast
3208 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003209 if (transformConstExprCastCall(CS)) return 0;
3210
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003211 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00003212
3213 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee))
3214 // This instruction is not reachable, just remove it. Eventually, this
3215 // should get turned into an unreachable instruction.
3216 if (!isa<InvokeInst>(CS.getInstruction())) { // Don't hack the CFG!
3217 if (!CS.getInstruction()->use_empty())
3218 CS.getInstruction()->
3219 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3220 return EraseInstFromFunction(*CS.getInstruction());
3221 }
3222
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003223 const PointerType *PTy = cast<PointerType>(Callee->getType());
3224 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3225 if (FTy->isVarArg()) {
3226 // See if we can optimize any arguments passed through the varargs area of
3227 // the call.
3228 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3229 E = CS.arg_end(); I != E; ++I)
3230 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3231 // If this cast does not effect the value passed through the varargs
3232 // area, we can eliminate the use of the cast.
3233 Value *Op = CI->getOperand(0);
3234 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3235 *I = Op;
3236 Changed = true;
3237 }
3238 }
3239 }
Chris Lattneraec3d942003-10-07 22:32:43 +00003240
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003241 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00003242}
3243
Chris Lattner970c33a2003-06-19 17:00:31 +00003244// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3245// attempt to move the cast to the arguments of the call/invoke.
3246//
3247bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3248 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3249 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00003250 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00003251 return false;
Reid Spencer87436872004-07-18 00:38:32 +00003252 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00003253 Instruction *Caller = CS.getInstruction();
3254
3255 // Okay, this is a cast from a function to a different type. Unless doing so
3256 // would cause a type conversion of one of our arguments, change this call to
3257 // be a direct call with arguments casted to the appropriate types.
3258 //
3259 const FunctionType *FT = Callee->getFunctionType();
3260 const Type *OldRetTy = Caller->getType();
3261
Chris Lattner1f7942f2004-01-14 06:06:08 +00003262 // Check to see if we are changing the return type...
3263 if (OldRetTy != FT->getReturnType()) {
3264 if (Callee->isExternal() &&
3265 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3266 !Caller->use_empty())
3267 return false; // Cannot transform this return value...
3268
3269 // If the callsite is an invoke instruction, and the return value is used by
3270 // a PHI node in a successor, we cannot change the return type of the call
3271 // because there is no place to put the cast instruction (without breaking
3272 // the critical edge). Bail out in this case.
3273 if (!Caller->use_empty())
3274 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3275 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3276 UI != E; ++UI)
3277 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3278 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003279 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00003280 return false;
3281 }
Chris Lattner970c33a2003-06-19 17:00:31 +00003282
3283 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3284 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3285
3286 CallSite::arg_iterator AI = CS.arg_begin();
3287 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3288 const Type *ParamTy = FT->getParamType(i);
3289 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3290 if (Callee->isExternal() && !isConvertible) return false;
3291 }
3292
3293 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3294 Callee->isExternal())
3295 return false; // Do not delete arguments unless we have a function body...
3296
3297 // Okay, we decided that this is a safe thing to do: go ahead and start
3298 // inserting cast instructions as necessary...
3299 std::vector<Value*> Args;
3300 Args.reserve(NumActualArgs);
3301
3302 AI = CS.arg_begin();
3303 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3304 const Type *ParamTy = FT->getParamType(i);
3305 if ((*AI)->getType() == ParamTy) {
3306 Args.push_back(*AI);
3307 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00003308 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3309 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00003310 }
3311 }
3312
3313 // If the function takes more arguments than the call was taking, add them
3314 // now...
3315 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3316 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3317
3318 // If we are removing arguments to the function, emit an obnoxious warning...
3319 if (FT->getNumParams() < NumActualArgs)
3320 if (!FT->isVarArg()) {
3321 std::cerr << "WARNING: While resolving call to function '"
3322 << Callee->getName() << "' arguments were dropped!\n";
3323 } else {
3324 // Add all of the arguments in their promoted form to the arg list...
3325 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3326 const Type *PTy = getPromotedType((*AI)->getType());
3327 if (PTy != (*AI)->getType()) {
3328 // Must promote to pass through va_arg area!
3329 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3330 InsertNewInstBefore(Cast, *Caller);
3331 Args.push_back(Cast);
3332 } else {
3333 Args.push_back(*AI);
3334 }
3335 }
3336 }
3337
3338 if (FT->getReturnType() == Type::VoidTy)
3339 Caller->setName(""); // Void type should not have a name...
3340
3341 Instruction *NC;
3342 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003343 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00003344 Args, Caller->getName(), Caller);
3345 } else {
3346 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3347 }
3348
3349 // Insert a cast of the return type as necessary...
3350 Value *NV = NC;
3351 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3352 if (NV->getType() != Type::VoidTy) {
3353 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00003354
3355 // If this is an invoke instruction, we should insert it after the first
3356 // non-phi, instruction in the normal successor block.
3357 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3358 BasicBlock::iterator I = II->getNormalDest()->begin();
3359 while (isa<PHINode>(I)) ++I;
3360 InsertNewInstBefore(NC, *I);
3361 } else {
3362 // Otherwise, it's a call, just insert cast right after the call instr
3363 InsertNewInstBefore(NC, *Caller);
3364 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003365 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00003366 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00003367 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00003368 }
3369 }
3370
3371 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3372 Caller->replaceAllUsesWith(NV);
3373 Caller->getParent()->getInstList().erase(Caller);
3374 removeFromWorkList(Caller);
3375 return true;
3376}
3377
3378
Chris Lattner48a44f72002-05-02 17:06:02 +00003379
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003380// PHINode simplification
3381//
Chris Lattner113f4f42002-06-25 16:13:24 +00003382Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnere29d6342004-10-17 21:22:38 +00003383 if (Value *V = hasConstantValue(&PN)) {
3384 // If V is an instruction, we have to be certain that it dominates PN.
3385 // However, because we don't have dom info, we can't do a perfect job.
3386 if (Instruction *I = dyn_cast<Instruction>(V)) {
3387 // We know that the instruction dominates the PHI if there are no undef
3388 // values coming in.
Chris Lattner107c15c2004-10-17 21:31:34 +00003389 if (I->getParent() != &I->getParent()->getParent()->front())
3390 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3391 if (isa<UndefValue>(PN.getIncomingValue(i))) {
3392 V = 0;
3393 break;
3394 }
Chris Lattnere29d6342004-10-17 21:22:38 +00003395 }
3396
3397 if (V)
3398 return ReplaceInstUsesWith(PN, V);
3399 }
Chris Lattner4db2d222004-02-16 05:07:08 +00003400
3401 // If the only user of this instruction is a cast instruction, and all of the
3402 // incoming values are constants, change this PHI to merge together the casted
3403 // constants.
3404 if (PN.hasOneUse())
3405 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3406 if (CI->getType() != PN.getType()) { // noop casts will be folded
3407 bool AllConstant = true;
3408 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3409 if (!isa<Constant>(PN.getIncomingValue(i))) {
3410 AllConstant = false;
3411 break;
3412 }
3413 if (AllConstant) {
3414 // Make a new PHI with all casted values.
3415 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3416 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3417 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3418 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3419 PN.getIncomingBlock(i));
3420 }
3421
3422 // Update the cast instruction.
3423 CI->setOperand(0, New);
3424 WorkList.push_back(CI); // revisit the cast instruction to fold.
3425 WorkList.push_back(New); // Make sure to revisit the new Phi
3426 return &PN; // PN is now dead!
3427 }
3428 }
Chris Lattner91daeb52003-12-19 05:58:40 +00003429 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003430}
3431
Chris Lattner69193f92004-04-05 01:30:19 +00003432static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3433 Instruction *InsertPoint,
3434 InstCombiner *IC) {
3435 unsigned PS = IC->getTargetData().getPointerSize();
3436 const Type *VTy = V->getType();
3437 Instruction *Cast;
3438 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3439 // We must insert a cast to ensure we sign-extend.
3440 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3441 V->getName()), *InsertPoint);
3442 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3443 *InsertPoint);
3444}
3445
Chris Lattner48a44f72002-05-02 17:06:02 +00003446
Chris Lattner113f4f42002-06-25 16:13:24 +00003447Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003448 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00003449 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00003450 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003451 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00003452 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003453
Chris Lattner81a7a232004-10-16 18:11:37 +00003454 if (isa<UndefValue>(GEP.getOperand(0)))
3455 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
3456
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003457 bool HasZeroPointerIndex = false;
3458 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3459 HasZeroPointerIndex = C->isNullValue();
3460
3461 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00003462 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00003463
Chris Lattner69193f92004-04-05 01:30:19 +00003464 // Eliminate unneeded casts for indices.
3465 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00003466 gep_type_iterator GTI = gep_type_begin(GEP);
3467 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3468 if (isa<SequentialType>(*GTI)) {
3469 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3470 Value *Src = CI->getOperand(0);
3471 const Type *SrcTy = Src->getType();
3472 const Type *DestTy = CI->getType();
3473 if (Src->getType()->isInteger()) {
3474 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3475 // We can always eliminate a cast from ulong or long to the other.
3476 // We can always eliminate a cast from uint to int or the other on
3477 // 32-bit pointer platforms.
3478 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3479 MadeChange = true;
3480 GEP.setOperand(i, Src);
3481 }
3482 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3483 SrcTy->getPrimitiveSize() == 4) {
3484 // We can always eliminate a cast from int to [u]long. We can
3485 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3486 // pointer target.
3487 if (SrcTy->isSigned() ||
3488 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3489 MadeChange = true;
3490 GEP.setOperand(i, Src);
3491 }
Chris Lattner69193f92004-04-05 01:30:19 +00003492 }
3493 }
3494 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00003495 // If we are using a wider index than needed for this platform, shrink it
3496 // to what we need. If the incoming value needs a cast instruction,
3497 // insert it. This explicit cast can make subsequent optimizations more
3498 // obvious.
3499 Value *Op = GEP.getOperand(i);
3500 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003501 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00003502 GEP.setOperand(i, ConstantExpr::getCast(C,
3503 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003504 MadeChange = true;
3505 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00003506 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3507 Op->getName()), GEP);
3508 GEP.setOperand(i, Op);
3509 MadeChange = true;
3510 }
Chris Lattner44d0b952004-07-20 01:48:15 +00003511
3512 // If this is a constant idx, make sure to canonicalize it to be a signed
3513 // operand, otherwise CSE and other optimizations are pessimized.
3514 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3515 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3516 CUI->getType()->getSignedVersion()));
3517 MadeChange = true;
3518 }
Chris Lattner69193f92004-04-05 01:30:19 +00003519 }
3520 if (MadeChange) return &GEP;
3521
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003522 // Combine Indices - If the source pointer to this getelementptr instruction
3523 // is a getelementptr instruction, combine the indices of the two
3524 // getelementptr instructions into a single instruction.
3525 //
Chris Lattner57c67b02004-03-25 22:59:29 +00003526 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00003527 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003528 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00003529 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003530 if (CE->getOpcode() == Instruction::GetElementPtr)
3531 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3532 }
3533
3534 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003535 // Note that if our source is a gep chain itself that we wait for that
3536 // chain to be resolved before we perform this transformation. This
3537 // avoids us creating a TON of code in some cases.
3538 //
3539 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3540 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3541 return 0; // Wait until our source is folded to completion.
3542
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003543 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00003544
3545 // Find out whether the last index in the source GEP is a sequential idx.
3546 bool EndsWithSequential = false;
3547 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3548 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00003549 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00003550
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003551 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00003552 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00003553 // Replace: gep (gep %P, long B), long A, ...
3554 // With: T = long A+B; gep %P, T, ...
3555 //
Chris Lattner5f667a62004-05-07 22:09:22 +00003556 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00003557 if (SO1 == Constant::getNullValue(SO1->getType())) {
3558 Sum = GO1;
3559 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3560 Sum = SO1;
3561 } else {
3562 // If they aren't the same type, convert both to an integer of the
3563 // target's pointer size.
3564 if (SO1->getType() != GO1->getType()) {
3565 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3566 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3567 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3568 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3569 } else {
3570 unsigned PS = TD->getPointerSize();
3571 Instruction *Cast;
3572 if (SO1->getType()->getPrimitiveSize() == PS) {
3573 // Convert GO1 to SO1's type.
3574 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3575
3576 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3577 // Convert SO1 to GO1's type.
3578 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3579 } else {
3580 const Type *PT = TD->getIntPtrType();
3581 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3582 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3583 }
3584 }
3585 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003586 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3587 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3588 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003589 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3590 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00003591 }
Chris Lattner69193f92004-04-05 01:30:19 +00003592 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003593
3594 // Recycle the GEP we already have if possible.
3595 if (SrcGEPOperands.size() == 2) {
3596 GEP.setOperand(0, SrcGEPOperands[0]);
3597 GEP.setOperand(1, Sum);
3598 return &GEP;
3599 } else {
3600 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3601 SrcGEPOperands.end()-1);
3602 Indices.push_back(Sum);
3603 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3604 }
Chris Lattner69193f92004-04-05 01:30:19 +00003605 } else if (isa<Constant>(*GEP.idx_begin()) &&
3606 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00003607 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003608 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00003609 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3610 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003611 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3612 }
3613
3614 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00003615 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003616
Chris Lattner5f667a62004-05-07 22:09:22 +00003617 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003618 // GEP of global variable. If all of the indices for this GEP are
3619 // constants, we can promote this to a constexpr instead of an instruction.
3620
3621 // Scan for nonconstants...
3622 std::vector<Constant*> Indices;
3623 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3624 for (; I != E && isa<Constant>(*I); ++I)
3625 Indices.push_back(cast<Constant>(*I));
3626
3627 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00003628 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003629
3630 // Replace all uses of the GEP with the new constexpr...
3631 return ReplaceInstUsesWith(GEP, CE);
3632 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003633 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003634 if (CE->getOpcode() == Instruction::Cast) {
3635 if (HasZeroPointerIndex) {
3636 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3637 // into : GEP [10 x ubyte]* X, long 0, ...
3638 //
3639 // This occurs when the program declares an array extern like "int X[];"
3640 //
3641 Constant *X = CE->getOperand(0);
3642 const PointerType *CPTy = cast<PointerType>(CE->getType());
3643 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3644 if (const ArrayType *XATy =
3645 dyn_cast<ArrayType>(XTy->getElementType()))
3646 if (const ArrayType *CATy =
3647 dyn_cast<ArrayType>(CPTy->getElementType()))
3648 if (CATy->getElementType() == XATy->getElementType()) {
3649 // At this point, we know that the cast source type is a pointer
3650 // to an array of the same type as the destination pointer
3651 // array. Because the array type is never stepped over (there
3652 // is a leading zero) we can fold the cast into this GEP.
3653 GEP.setOperand(0, X);
3654 return &GEP;
3655 }
3656 }
3657 }
Chris Lattnerca081252001-12-14 16:52:21 +00003658 }
3659
Chris Lattnerca081252001-12-14 16:52:21 +00003660 return 0;
3661}
3662
Chris Lattner1085bdf2002-11-04 16:18:53 +00003663Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3664 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3665 if (AI.isArrayAllocation()) // Check C != 1
3666 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3667 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003668 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00003669
3670 // Create and insert the replacement instruction...
3671 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00003672 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003673 else {
3674 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00003675 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003676 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003677
3678 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003679
3680 // Scan to the end of the allocation instructions, to skip over a block of
3681 // allocas if possible...
3682 //
3683 BasicBlock::iterator It = New;
3684 while (isa<AllocationInst>(*It)) ++It;
3685
3686 // Now that I is pointing to the first non-allocation-inst in the block,
3687 // insert our getelementptr instruction...
3688 //
Chris Lattner69193f92004-04-05 01:30:19 +00003689 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003690 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3691
3692 // Now make everything use the getelementptr instead of the original
3693 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00003694 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00003695 } else if (isa<UndefValue>(AI.getArraySize())) {
3696 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003697 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003698
3699 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3700 // Note that we only do this for alloca's, because malloc should allocate and
3701 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00003702 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3703 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00003704 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3705
Chris Lattner1085bdf2002-11-04 16:18:53 +00003706 return 0;
3707}
3708
Chris Lattner8427bff2003-12-07 01:24:23 +00003709Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3710 Value *Op = FI.getOperand(0);
3711
3712 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3713 if (CastInst *CI = dyn_cast<CastInst>(Op))
3714 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3715 FI.setOperand(0, CI->getOperand(0));
3716 return &FI;
3717 }
3718
Chris Lattnerf3a36602004-02-28 04:57:37 +00003719 // If we have 'free null' delete the instruction. This can happen in stl code
3720 // when lots of inlining happens.
Chris Lattner81a7a232004-10-16 18:11:37 +00003721 // FIXME: free undef should be xformed into an 'unreachable' instruction.
3722 if (isa<ConstantPointerNull>(Op) || isa<UndefValue>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00003723 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00003724
Chris Lattner8427bff2003-12-07 01:24:23 +00003725 return 0;
3726}
3727
3728
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003729/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3730/// constantexpr, return the constant value being addressed by the constant
3731/// expression, or null if something is funny.
3732///
3733static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00003734 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003735 return 0; // Do not allow stepping over the value!
3736
3737 // Loop over all of the operands, tracking down which value we are
3738 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00003739 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3740 for (++I; I != E; ++I)
3741 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3742 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3743 assert(CU->getValue() < STy->getNumElements() &&
3744 "Struct index out of range!");
3745 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003746 C = CS->getOperand(CU->getValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003747 } else if (isa<ConstantAggregateZero>(C)) {
3748 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003749 } else if (isa<UndefValue>(C)) {
3750 C = UndefValue::get(STy->getElementType(CU->getValue()));
Chris Lattnered79d8a2004-05-27 17:30:27 +00003751 } else {
3752 return 0;
3753 }
3754 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3755 const ArrayType *ATy = cast<ArrayType>(*I);
3756 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3757 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003758 C = CA->getOperand(CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003759 else if (isa<ConstantAggregateZero>(C))
3760 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00003761 else if (isa<UndefValue>(C))
3762 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003763 else
3764 return 0;
3765 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003766 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00003767 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003768 return C;
3769}
3770
Chris Lattner35e24772004-07-13 01:49:43 +00003771static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3772 User *CI = cast<User>(LI.getOperand(0));
3773
3774 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3775 if (const PointerType *SrcTy =
3776 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3777 const Type *SrcPTy = SrcTy->getElementType();
3778 if (SrcPTy->isSized() && DestPTy->isSized() &&
3779 IC.getTargetData().getTypeSize(SrcPTy) ==
3780 IC.getTargetData().getTypeSize(DestPTy) &&
3781 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3782 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3783 // Okay, we are casting from one integer or pointer type to another of
3784 // the same size. Instead of casting the pointer before the load, cast
3785 // the result of the loaded value.
3786 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003787 CI->getName(),
3788 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00003789 // Now cast the result of the load.
3790 return new CastInst(NewLoad, LI.getType());
3791 }
3792 }
3793 return 0;
3794}
3795
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003796/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00003797/// from this value cannot trap. If it is not obviously safe to load from the
3798/// specified pointer, we do a quick local scan of the basic block containing
3799/// ScanFrom, to determine if the address is already accessed.
3800static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3801 // If it is an alloca or global variable, it is always safe to load from.
3802 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3803
3804 // Otherwise, be a little bit agressive by scanning the local block where we
3805 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003806 // from/to. If so, the previous load or store would have already trapped,
3807 // so there is no harm doing an extra load (also, CSE will later eliminate
3808 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00003809 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3810
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003811 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00003812 --BBI;
3813
3814 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3815 if (LI->getOperand(0) == V) return true;
3816 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3817 if (SI->getOperand(1) == V) return true;
3818
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003819 }
Chris Lattnere6f13092004-09-19 19:18:10 +00003820 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003821}
3822
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003823Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3824 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00003825
Chris Lattner81a7a232004-10-16 18:11:37 +00003826 if (Constant *C = dyn_cast<Constant>(Op)) {
3827 if ((C->isNullValue() || isa<UndefValue>(C)) &&
3828 !LI.isVolatile()) // load null -> undef
3829 // FIXME: this should become an unreachable instruction
3830 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003831
Chris Lattner81a7a232004-10-16 18:11:37 +00003832 // Instcombine load (constant global) into the value loaded.
3833 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
3834 if (GV->isConstant() && !GV->isExternal())
3835 return ReplaceInstUsesWith(LI, GV->getInitializer());
3836
3837 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
3838 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
3839 if (CE->getOpcode() == Instruction::GetElementPtr) {
3840 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3841 if (GV->isConstant() && !GV->isExternal())
3842 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3843 return ReplaceInstUsesWith(LI, V);
3844 } else if (CE->getOpcode() == Instruction::Cast) {
3845 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3846 return Res;
3847 }
3848 }
Chris Lattnere228ee52004-04-08 20:39:49 +00003849
3850 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00003851 if (CastInst *CI = dyn_cast<CastInst>(Op))
3852 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3853 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00003854
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003855 if (!LI.isVolatile() && Op->hasOneUse()) {
3856 // Change select and PHI nodes to select values instead of addresses: this
3857 // helps alias analysis out a lot, allows many others simplifications, and
3858 // exposes redundancy in the code.
3859 //
3860 // Note that we cannot do the transformation unless we know that the
3861 // introduced loads cannot trap! Something like this is valid as long as
3862 // the condition is always false: load (select bool %C, int* null, int* %G),
3863 // but it would not be valid if we transformed it to load from null
3864 // unconditionally.
3865 //
3866 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3867 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00003868 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3869 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003870 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00003871 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003872 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00003873 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003874 return new SelectInst(SI->getCondition(), V1, V2);
3875 }
3876
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00003877 // load (select (cond, null, P)) -> load P
3878 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3879 if (C->isNullValue()) {
3880 LI.setOperand(0, SI->getOperand(2));
3881 return &LI;
3882 }
3883
3884 // load (select (cond, P, null)) -> load P
3885 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3886 if (C->isNullValue()) {
3887 LI.setOperand(0, SI->getOperand(1));
3888 return &LI;
3889 }
3890
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003891 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3892 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00003893 bool Safe = PN->getParent() == LI.getParent();
3894
3895 // Scan all of the instructions between the PHI and the load to make
3896 // sure there are no instructions that might possibly alter the value
3897 // loaded from the PHI.
3898 if (Safe) {
3899 BasicBlock::iterator I = &LI;
3900 for (--I; !isa<PHINode>(I); --I)
3901 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3902 Safe = false;
3903 break;
3904 }
3905 }
3906
3907 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00003908 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00003909 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003910 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00003911
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003912 if (Safe) {
3913 // Create the PHI.
3914 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3915 InsertNewInstBefore(NewPN, *PN);
3916 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3917
3918 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3919 BasicBlock *BB = PN->getIncomingBlock(i);
3920 Value *&TheLoad = LoadMap[BB];
3921 if (TheLoad == 0) {
3922 Value *InVal = PN->getIncomingValue(i);
3923 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3924 InVal->getName()+".val"),
3925 *BB->getTerminator());
3926 }
3927 NewPN->addIncoming(TheLoad, BB);
3928 }
3929 return ReplaceInstUsesWith(LI, NewPN);
3930 }
3931 }
3932 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003933 return 0;
3934}
3935
Chris Lattner81a7a232004-10-16 18:11:37 +00003936Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
3937 if (isa<ConstantPointerNull>(SI.getOperand(1)) ||
3938 isa<UndefValue>(SI.getOperand(1))) {
3939 // FIXME: This should become an unreachable instruction.
3940 return EraseInstFromFunction(SI);
3941 }
3942
3943
3944 return 0;
3945}
3946
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003947
Chris Lattner9eef8a72003-06-04 04:46:00 +00003948Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3949 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00003950 Value *X;
3951 BasicBlock *TrueDest;
3952 BasicBlock *FalseDest;
3953 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3954 !isa<Constant>(X)) {
3955 // Swap Destinations and condition...
3956 BI.setCondition(X);
3957 BI.setSuccessor(0, FalseDest);
3958 BI.setSuccessor(1, TrueDest);
3959 return &BI;
3960 }
3961
3962 // Cannonicalize setne -> seteq
3963 Instruction::BinaryOps Op; Value *Y;
3964 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3965 TrueDest, FalseDest)))
3966 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3967 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3968 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3969 std::string Name = I->getName(); I->setName("");
3970 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3971 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00003972 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00003973 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00003974 BI.setSuccessor(0, FalseDest);
3975 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003976 removeFromWorkList(I);
3977 I->getParent()->getInstList().erase(I);
3978 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00003979 return &BI;
3980 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00003981
Chris Lattner9eef8a72003-06-04 04:46:00 +00003982 return 0;
3983}
Chris Lattner1085bdf2002-11-04 16:18:53 +00003984
Chris Lattner4c9c20a2004-07-03 00:26:11 +00003985Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3986 Value *Cond = SI.getCondition();
3987 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3988 if (I->getOpcode() == Instruction::Add)
3989 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3990 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3991 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00003992 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00003993 AddRHS));
3994 SI.setOperand(0, I->getOperand(0));
3995 WorkList.push_back(I);
3996 return &SI;
3997 }
3998 }
3999 return 0;
4000}
4001
Chris Lattnerca081252001-12-14 16:52:21 +00004002
Chris Lattner99f48c62002-09-02 04:59:56 +00004003void InstCombiner::removeFromWorkList(Instruction *I) {
4004 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4005 WorkList.end());
4006}
4007
Chris Lattner113f4f42002-06-25 16:13:24 +00004008bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00004009 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004010 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00004011
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004012 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
4013 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00004014
Chris Lattnerca081252001-12-14 16:52:21 +00004015
4016 while (!WorkList.empty()) {
4017 Instruction *I = WorkList.back(); // Get an instruction from the worklist
4018 WorkList.pop_back();
4019
Misha Brukman632df282002-10-29 23:06:16 +00004020 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00004021 // Check to see if we can DIE the instruction...
4022 if (isInstructionTriviallyDead(I)) {
4023 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004024 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00004025 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00004026 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004027
4028 I->getParent()->getInstList().erase(I);
4029 removeFromWorkList(I);
4030 continue;
4031 }
Chris Lattner99f48c62002-09-02 04:59:56 +00004032
Misha Brukman632df282002-10-29 23:06:16 +00004033 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00004034 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner6580e092004-10-16 19:44:59 +00004035 if (isa<GetElementPtrInst>(I) &&
4036 cast<Constant>(I->getOperand(0))->isNullValue() &&
4037 !isa<ConstantPointerNull>(C)) {
4038 // If this is a constant expr gep that is effectively computing an
4039 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
4040 bool isFoldableGEP = true;
4041 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
4042 if (!isa<ConstantInt>(I->getOperand(i)))
4043 isFoldableGEP = false;
4044 if (isFoldableGEP) {
4045 uint64_t Offset = TD->getIndexedOffset(I->getOperand(0)->getType(),
4046 std::vector<Value*>(I->op_begin()+1, I->op_end()));
4047 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00004048 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00004049 C = ConstantExpr::getCast(C, I->getType());
4050 }
4051 }
4052
Chris Lattner99f48c62002-09-02 04:59:56 +00004053 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00004054 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00004055 ReplaceInstUsesWith(*I, C);
4056
Chris Lattner99f48c62002-09-02 04:59:56 +00004057 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004058 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00004059 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004060 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00004061 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004062
Chris Lattnerca081252001-12-14 16:52:21 +00004063 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004064 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00004065 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00004066 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00004067 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004068 DEBUG(std::cerr << "IC: Old = " << *I
4069 << " New = " << *Result);
4070
Chris Lattner396dbfe2004-06-09 05:08:07 +00004071 // Everything uses the new instruction now.
4072 I->replaceAllUsesWith(Result);
4073
4074 // Push the new instruction and any users onto the worklist.
4075 WorkList.push_back(Result);
4076 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004077
4078 // Move the name to the new instruction first...
4079 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00004080 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004081
4082 // Insert the new instruction into the basic block...
4083 BasicBlock *InstParent = I->getParent();
4084 InstParent->getInstList().insert(I, Result);
4085
Chris Lattner63d75af2004-05-01 23:27:23 +00004086 // Make sure that we reprocess all operands now that we reduced their
4087 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004088 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4089 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4090 WorkList.push_back(OpI);
4091
Chris Lattner396dbfe2004-06-09 05:08:07 +00004092 // Instructions can end up on the worklist more than once. Make sure
4093 // we do not process an instruction that has been deleted.
4094 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004095
4096 // Erase the old instruction.
4097 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004098 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004099 DEBUG(std::cerr << "IC: MOD = " << *I);
4100
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004101 // If the instruction was modified, it's possible that it is now dead.
4102 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00004103 if (isInstructionTriviallyDead(I)) {
4104 // Make sure we process all operands now that we are reducing their
4105 // use counts.
4106 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4107 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4108 WorkList.push_back(OpI);
4109
4110 // Instructions may end up in the worklist more than once. Erase all
4111 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00004112 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00004113 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00004114 } else {
4115 WorkList.push_back(Result);
4116 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004117 }
Chris Lattner053c0932002-05-14 15:24:07 +00004118 }
Chris Lattner260ab202002-04-18 17:39:14 +00004119 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00004120 }
4121 }
4122
Chris Lattner260ab202002-04-18 17:39:14 +00004123 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00004124}
4125
Brian Gaeke38b79e82004-07-27 17:43:21 +00004126FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00004127 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00004128}
Brian Gaeke960707c2003-11-11 22:41:34 +00004129