blob: 1e4baf7db376937133782f14ce0b71a41e87370a [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000032// N. This list is incomplete
33//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner471bd762003-05-22 19:07:21 +000038#include "llvm/Instructions.h"
Chris Lattner51ea1272004-02-28 05:22:00 +000039#include "llvm/Intrinsics.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner34428442003-05-27 16:40:51 +000041#include "llvm/Constants.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000042#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000043#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
48#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner60a65912002-02-12 21:07:25 +000049#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/Support/Debug.h"
53#include "llvm/ADT/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000057
Chris Lattner260ab202002-04-18 17:39:14 +000058namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000059 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
62
Chris Lattnerc8e66542002-04-27 06:56:12 +000063 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000064 public InstVisitor<InstCombiner, Instruction*> {
65 // Worklist of all of the instructions that need to be simplified.
66 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000067 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000068
Chris Lattner51ea1272004-02-28 05:22:00 +000069 /// AddUsersToWorkList - When an instruction is simplified, add all users of
70 /// the instruction to the work lists because they might get more simplified
71 /// now.
72 ///
73 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000074 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000075 UI != UE; ++UI)
76 WorkList.push_back(cast<Instruction>(*UI));
77 }
78
Chris Lattner51ea1272004-02-28 05:22:00 +000079 /// AddUsesToWorkList - When an instruction is simplified, add operands to
80 /// the work lists because they might get more simplified now.
81 ///
82 void AddUsesToWorkList(Instruction &I) {
83 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
84 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
85 WorkList.push_back(Op);
86 }
87
Chris Lattner99f48c62002-09-02 04:59:56 +000088 // removeFromWorkList - remove all instances of I from the worklist.
89 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000090 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000091 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000092
Chris Lattnerf12cc842002-04-28 21:27:06 +000093 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000094 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000095 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000096 }
97
Chris Lattner69193f92004-04-05 01:30:19 +000098 TargetData &getTargetData() const { return *TD; }
99
Chris Lattner260ab202002-04-18 17:39:14 +0000100 // Visitation implementation - Implement instruction combining for different
101 // instruction types. The semantics are as follows:
102 // Return Value:
103 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000104 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000105 // otherwise - Change was made, replace I with returned instruction
106 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000107 Instruction *visitAdd(BinaryOperator &I);
108 Instruction *visitSub(BinaryOperator &I);
109 Instruction *visitMul(BinaryOperator &I);
110 Instruction *visitDiv(BinaryOperator &I);
111 Instruction *visitRem(BinaryOperator &I);
112 Instruction *visitAnd(BinaryOperator &I);
113 Instruction *visitOr (BinaryOperator &I);
114 Instruction *visitXor(BinaryOperator &I);
115 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000116 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000117 Instruction *visitCastInst(CastInst &CI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000118 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000119 Instruction *visitCallInst(CallInst &CI);
120 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000121 Instruction *visitPHINode(PHINode &PN);
122 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000123 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000124 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000125 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000126 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000127 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000128
129 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000130 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000131
Chris Lattner970c33a2003-06-19 17:00:31 +0000132 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000133 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000134 bool transformConstExprCastCall(CallSite CS);
135
Chris Lattner69193f92004-04-05 01:30:19 +0000136 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000137 // InsertNewInstBefore - insert an instruction New before instruction Old
138 // in the program. Add the new instruction to the worklist.
139 //
Chris Lattner623826c2004-09-28 21:48:02 +0000140 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000141 assert(New && New->getParent() == 0 &&
142 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000143 BasicBlock *BB = Old.getParent();
144 BB->getInstList().insert(&Old, New); // Insert inst
145 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000146 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000147 }
148
Chris Lattner7e794272004-09-24 15:21:34 +0000149 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
150 /// This also adds the cast to the worklist. Finally, this returns the
151 /// cast.
152 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
153 if (V->getType() == Ty) return V;
154
155 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
156 WorkList.push_back(C);
157 return C;
158 }
159
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000160 // ReplaceInstUsesWith - This method is to be used when an instruction is
161 // found to be dead, replacable with another preexisting expression. Here
162 // we add all uses of I to the worklist, replace all uses of I with the new
163 // value, then return I, so that the inst combiner will know that I was
164 // modified.
165 //
166 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000167 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000168 if (&I != V) {
169 I.replaceAllUsesWith(V);
170 return &I;
171 } else {
172 // If we are replacing the instruction with itself, this must be in a
173 // segment of unreachable code, so just clobber the instruction.
174 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
175 return &I;
176 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000177 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000178
179 // EraseInstFromFunction - When dealing with an instruction that has side
180 // effects or produces a void value, we can't rely on DCE to delete the
181 // instruction. Instead, visit methods should return the value returned by
182 // this function.
183 Instruction *EraseInstFromFunction(Instruction &I) {
184 assert(I.use_empty() && "Cannot erase instruction that is used!");
185 AddUsesToWorkList(I);
186 removeFromWorkList(&I);
187 I.getParent()->getInstList().erase(&I);
188 return 0; // Don't do anything with FI
189 }
190
191
Chris Lattner3ac7c262003-08-13 20:16:26 +0000192 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000193 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
194 /// InsertBefore instruction. This is specialized a bit to avoid inserting
195 /// casts that are known to not do anything...
196 ///
197 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
198 Instruction *InsertBefore);
199
Chris Lattner7fb29e12003-03-11 00:12:48 +0000200 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000201 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000202 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000203
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000204
205 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
206 // PHI node as operand #0, see if we can fold the instruction into the PHI
207 // (which is only possible if all operands to the PHI are constants).
208 Instruction *FoldOpIntoPhi(Instruction &I);
209
Chris Lattnerba1cb382003-09-19 17:17:26 +0000210 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
211 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000212
213 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
214 bool Inside, Instruction &IB);
Chris Lattner260ab202002-04-18 17:39:14 +0000215 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000216
Chris Lattnerc8b70922002-07-26 21:12:46 +0000217 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000218}
219
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000220// getComplexity: Assign a complexity or rank value to LLVM Values...
221// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
222static unsigned getComplexity(Value *V) {
223 if (isa<Instruction>(V)) {
224 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
225 return 2;
226 return 3;
227 }
228 if (isa<Argument>(V)) return 2;
229 return isa<Constant>(V) ? 0 : 1;
230}
Chris Lattner260ab202002-04-18 17:39:14 +0000231
Chris Lattner7fb29e12003-03-11 00:12:48 +0000232// isOnlyUse - Return true if this instruction will be deleted if we stop using
233// it.
234static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000235 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000236}
237
Chris Lattnere79e8542004-02-23 06:38:22 +0000238// getPromotedType - Return the specified type promoted as it would be to pass
239// though a va_arg area...
240static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000241 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000242 case Type::SByteTyID:
243 case Type::ShortTyID: return Type::IntTy;
244 case Type::UByteTyID:
245 case Type::UShortTyID: return Type::UIntTy;
246 case Type::FloatTyID: return Type::DoubleTy;
247 default: return Ty;
248 }
249}
250
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000251// SimplifyCommutative - This performs a few simplifications for commutative
252// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000253//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000254// 1. Order operands such that they are listed from right (least complex) to
255// left (most complex). This puts constants before unary operators before
256// binary operators.
257//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000258// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
259// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000260//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000261bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000262 bool Changed = false;
263 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
264 Changed = !I.swapOperands();
265
266 if (!I.isAssociative()) return Changed;
267 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000268 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
269 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
270 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000271 Constant *Folded = ConstantExpr::get(I.getOpcode(),
272 cast<Constant>(I.getOperand(1)),
273 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000274 I.setOperand(0, Op->getOperand(0));
275 I.setOperand(1, Folded);
276 return true;
277 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
278 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
279 isOnlyUse(Op) && isOnlyUse(Op1)) {
280 Constant *C1 = cast<Constant>(Op->getOperand(1));
281 Constant *C2 = cast<Constant>(Op1->getOperand(1));
282
283 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000284 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000285 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
286 Op1->getOperand(0),
287 Op1->getName(), &I);
288 WorkList.push_back(New);
289 I.setOperand(0, New);
290 I.setOperand(1, Folded);
291 return true;
292 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000293 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000294 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000295}
Chris Lattnerca081252001-12-14 16:52:21 +0000296
Chris Lattnerbb74e222003-03-10 23:06:50 +0000297// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
298// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000299//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000300static inline Value *dyn_castNegVal(Value *V) {
301 if (BinaryOperator::isNeg(V))
302 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
303
Chris Lattner9244df62003-04-30 22:19:10 +0000304 // Constants can be considered to be negated values if they can be folded...
305 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000306 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000307 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000308}
309
Chris Lattnerbb74e222003-03-10 23:06:50 +0000310static inline Value *dyn_castNotVal(Value *V) {
311 if (BinaryOperator::isNot(V))
312 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
313
314 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000315 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000316 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000317 return 0;
318}
319
Chris Lattner7fb29e12003-03-11 00:12:48 +0000320// dyn_castFoldableMul - If this value is a multiply that can be folded into
321// other computations (because it has a constant operand), return the
322// non-constant operand of the multiply.
323//
324static inline Value *dyn_castFoldableMul(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000325 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000326 if (Instruction *I = dyn_cast<Instruction>(V))
327 if (I->getOpcode() == Instruction::Mul)
328 if (isa<Constant>(I->getOperand(1)))
329 return I->getOperand(0);
330 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000331}
Chris Lattner31ae8632002-08-14 17:51:49 +0000332
Chris Lattner3082c5a2003-02-18 19:28:33 +0000333// Log2 - Calculate the log base 2 for the specified value if it is exactly a
334// power of 2.
335static unsigned Log2(uint64_t Val) {
336 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
337 unsigned Count = 0;
338 while (Val != 1) {
339 if (Val & 1) return 0; // Multiple bits set?
340 Val >>= 1;
341 ++Count;
342 }
343 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000344}
345
Chris Lattner623826c2004-09-28 21:48:02 +0000346// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000347static ConstantInt *AddOne(ConstantInt *C) {
348 return cast<ConstantInt>(ConstantExpr::getAdd(C,
349 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000350}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000351static ConstantInt *SubOne(ConstantInt *C) {
352 return cast<ConstantInt>(ConstantExpr::getSub(C,
353 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000354}
355
356// isTrueWhenEqual - Return true if the specified setcondinst instruction is
357// true when both operands are equal...
358//
359static bool isTrueWhenEqual(Instruction &I) {
360 return I.getOpcode() == Instruction::SetEQ ||
361 I.getOpcode() == Instruction::SetGE ||
362 I.getOpcode() == Instruction::SetLE;
363}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000364
365/// AssociativeOpt - Perform an optimization on an associative operator. This
366/// function is designed to check a chain of associative operators for a
367/// potential to apply a certain optimization. Since the optimization may be
368/// applicable if the expression was reassociated, this checks the chain, then
369/// reassociates the expression as necessary to expose the optimization
370/// opportunity. This makes use of a special Functor, which must define
371/// 'shouldApply' and 'apply' methods.
372///
373template<typename Functor>
374Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
375 unsigned Opcode = Root.getOpcode();
376 Value *LHS = Root.getOperand(0);
377
378 // Quick check, see if the immediate LHS matches...
379 if (F.shouldApply(LHS))
380 return F.apply(Root);
381
382 // Otherwise, if the LHS is not of the same opcode as the root, return.
383 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000384 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000385 // Should we apply this transform to the RHS?
386 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
387
388 // If not to the RHS, check to see if we should apply to the LHS...
389 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
390 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
391 ShouldApply = true;
392 }
393
394 // If the functor wants to apply the optimization to the RHS of LHSI,
395 // reassociate the expression from ((? op A) op B) to (? op (A op B))
396 if (ShouldApply) {
397 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000398
399 // Now all of the instructions are in the current basic block, go ahead
400 // and perform the reassociation.
401 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
402
403 // First move the selected RHS to the LHS of the root...
404 Root.setOperand(0, LHSI->getOperand(1));
405
406 // Make what used to be the LHS of the root be the user of the root...
407 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000408 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000409 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
410 return 0;
411 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000412 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000413 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000414 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
415 BasicBlock::iterator ARI = &Root; ++ARI;
416 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
417 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000418
419 // Now propagate the ExtraOperand down the chain of instructions until we
420 // get to LHSI.
421 while (TmpLHSI != LHSI) {
422 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000423 // Move the instruction to immediately before the chain we are
424 // constructing to avoid breaking dominance properties.
425 NextLHSI->getParent()->getInstList().remove(NextLHSI);
426 BB->getInstList().insert(ARI, NextLHSI);
427 ARI = NextLHSI;
428
Chris Lattnerb8b97502003-08-13 19:01:45 +0000429 Value *NextOp = NextLHSI->getOperand(1);
430 NextLHSI->setOperand(1, ExtraOperand);
431 TmpLHSI = NextLHSI;
432 ExtraOperand = NextOp;
433 }
434
435 // Now that the instructions are reassociated, have the functor perform
436 // the transformation...
437 return F.apply(Root);
438 }
439
440 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
441 }
442 return 0;
443}
444
445
446// AddRHS - Implements: X + X --> X << 1
447struct AddRHS {
448 Value *RHS;
449 AddRHS(Value *rhs) : RHS(rhs) {}
450 bool shouldApply(Value *LHS) const { return LHS == RHS; }
451 Instruction *apply(BinaryOperator &Add) const {
452 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
453 ConstantInt::get(Type::UByteTy, 1));
454 }
455};
456
457// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
458// iff C1&C2 == 0
459struct AddMaskingAnd {
460 Constant *C2;
461 AddMaskingAnd(Constant *c) : C2(c) {}
462 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000463 ConstantInt *C1;
464 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
465 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000466 }
467 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000468 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000469 }
470};
471
Chris Lattner183b3362004-04-09 19:05:30 +0000472static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
473 InstCombiner *IC) {
474 // Figure out if the constant is the left or the right argument.
475 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
476 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000477
Chris Lattner183b3362004-04-09 19:05:30 +0000478 if (Constant *SOC = dyn_cast<Constant>(SO)) {
479 if (ConstIsRHS)
480 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
481 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
482 }
483
484 Value *Op0 = SO, *Op1 = ConstOperand;
485 if (!ConstIsRHS)
486 std::swap(Op0, Op1);
487 Instruction *New;
488 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
489 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
490 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
491 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattnerf9d96652004-04-10 19:15:56 +0000492 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000493 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000494 abort();
495 }
Chris Lattner183b3362004-04-09 19:05:30 +0000496 return IC->InsertNewInstBefore(New, BI);
497}
498
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000499
500/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
501/// node as operand #0, see if we can fold the instruction into the PHI (which
502/// is only possible if all operands to the PHI are constants).
503Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
504 PHINode *PN = cast<PHINode>(I.getOperand(0));
505 if (!PN->hasOneUse()) return 0;
506
507 // Check to see if all of the operands of the PHI are constants. If not, we
508 // cannot do the transformation.
509 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
510 if (!isa<Constant>(PN->getIncomingValue(i)))
511 return 0;
512
513 // Okay, we can do the transformation: create the new PHI node.
514 PHINode *NewPN = new PHINode(I.getType(), I.getName());
515 I.setName("");
516 NewPN->op_reserve(PN->getNumOperands());
517 InsertNewInstBefore(NewPN, *PN);
518
519 // Next, add all of the operands to the PHI.
520 if (I.getNumOperands() == 2) {
521 Constant *C = cast<Constant>(I.getOperand(1));
522 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
523 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
524 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
525 PN->getIncomingBlock(i));
526 }
527 } else {
528 assert(isa<CastInst>(I) && "Unary op should be a cast!");
529 const Type *RetTy = I.getType();
530 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
531 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
532 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
533 PN->getIncomingBlock(i));
534 }
535 }
536 return ReplaceInstUsesWith(I, NewPN);
537}
538
Chris Lattner183b3362004-04-09 19:05:30 +0000539// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
540// constant as the other operand, try to fold the binary operator into the
541// select arguments.
542static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
543 InstCombiner *IC) {
544 // Don't modify shared select instructions
545 if (!SI->hasOneUse()) return 0;
546 Value *TV = SI->getOperand(1);
547 Value *FV = SI->getOperand(2);
548
549 if (isa<Constant>(TV) || isa<Constant>(FV)) {
550 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
551 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
552
553 return new SelectInst(SI->getCondition(), SelectTrueVal,
554 SelectFalseVal);
555 }
556 return 0;
557}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000558
Chris Lattner113f4f42002-06-25 16:13:24 +0000559Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000560 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000561 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000562
Chris Lattnercf4a9962004-04-10 22:01:55 +0000563 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
564 // X + 0 --> X
565 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
566 RHSC->isNullValue())
567 return ReplaceInstUsesWith(I, LHS);
568
569 // X + (signbit) --> X ^ signbit
570 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
571 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
572 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
573 if (Val == (1ULL << NumBits-1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000574 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000575 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000576
577 if (isa<PHINode>(LHS))
578 if (Instruction *NV = FoldOpIntoPhi(I))
579 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000580 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000581
Chris Lattnerb8b97502003-08-13 19:01:45 +0000582 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000583 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000584 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000585 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000586
Chris Lattner147e9752002-05-08 22:46:53 +0000587 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000588 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000589 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000590
591 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000592 if (!isa<Constant>(RHS))
593 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000594 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000595
Chris Lattner57c8d992003-02-18 19:57:07 +0000596 // X*C + X --> X * (C+1)
597 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000598 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000599 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000600 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
601 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000602 return BinaryOperator::createMul(RHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000603 }
604
605 // X + X*C --> X * (C+1)
606 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000607 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000608 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000609 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
610 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000611 return BinaryOperator::createMul(LHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000612 }
613
Chris Lattnerb8b97502003-08-13 19:01:45 +0000614 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000615 ConstantInt *C2;
616 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000617 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000618
Chris Lattnerb9cde762003-10-02 15:11:26 +0000619 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000620 Value *X;
621 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
622 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
623 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000624 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000625
Chris Lattnerbff91d92004-10-08 05:07:56 +0000626 // (X & FF00) + xx00 -> (X+xx00) & FF00
627 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
628 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
629 if (Anded == CRHS) {
630 // See if all bits from the first bit set in the Add RHS up are included
631 // in the mask. First, get the rightmost bit.
632 uint64_t AddRHSV = CRHS->getRawValue();
633
634 // Form a mask of all bits from the lowest bit added through the top.
635 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
636 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
637
638 // See if the and mask includes all of these bits.
639 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
640
641 if (AddRHSHighBits == AddRHSHighBitsAnd) {
642 // Okay, the xform is safe. Insert the new add pronto.
643 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
644 LHS->getName()), I);
645 return BinaryOperator::createAnd(NewAdd, C2);
646 }
647 }
648 }
649
650
Chris Lattnerd4252a72004-07-30 07:50:03 +0000651 // Try to fold constant add into select arguments.
652 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
653 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
654 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000655 }
656
Chris Lattner113f4f42002-06-25 16:13:24 +0000657 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000658}
659
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000660// isSignBit - Return true if the value represented by the constant only has the
661// highest order bit set.
662static bool isSignBit(ConstantInt *CI) {
663 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
664 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
665}
666
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000667static unsigned getTypeSizeInBits(const Type *Ty) {
668 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
669}
670
Chris Lattner022167f2004-03-13 00:11:49 +0000671/// RemoveNoopCast - Strip off nonconverting casts from the value.
672///
673static Value *RemoveNoopCast(Value *V) {
674 if (CastInst *CI = dyn_cast<CastInst>(V)) {
675 const Type *CTy = CI->getType();
676 const Type *OpTy = CI->getOperand(0)->getType();
677 if (CTy->isInteger() && OpTy->isInteger()) {
678 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
679 return RemoveNoopCast(CI->getOperand(0));
680 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
681 return RemoveNoopCast(CI->getOperand(0));
682 }
683 return V;
684}
685
Chris Lattner113f4f42002-06-25 16:13:24 +0000686Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000687 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000688
Chris Lattnere6794492002-08-12 21:17:25 +0000689 if (Op0 == Op1) // sub X, X -> 0
690 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000691
Chris Lattnere6794492002-08-12 21:17:25 +0000692 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000693 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000694 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000695
Chris Lattner8f2f5982003-11-05 01:06:05 +0000696 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
697 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000698 if (C->isAllOnesValue())
699 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000700
Chris Lattner8f2f5982003-11-05 01:06:05 +0000701 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000702 Value *X;
703 if (match(Op1, m_Not(m_Value(X))))
704 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000705 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000706 // -((uint)X >> 31) -> ((int)X >> 31)
707 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000708 if (C->isNullValue()) {
709 Value *NoopCastedRHS = RemoveNoopCast(Op1);
710 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000711 if (SI->getOpcode() == Instruction::Shr)
712 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
713 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000714 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000715 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000716 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000717 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000718 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000719 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000720 // Ok, the transformation is safe. Insert a cast of the incoming
721 // value, then the new shift, then the new cast.
722 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
723 SI->getOperand(0)->getName());
724 Value *InV = InsertNewInstBefore(FirstCast, I);
725 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
726 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000727 if (NewShift->getType() == I.getType())
728 return NewShift;
729 else {
730 InV = InsertNewInstBefore(NewShift, I);
731 return new CastInst(NewShift, I.getType());
732 }
Chris Lattner92295c52004-03-12 23:53:13 +0000733 }
734 }
Chris Lattner022167f2004-03-13 00:11:49 +0000735 }
Chris Lattner183b3362004-04-09 19:05:30 +0000736
737 // Try to fold constant sub into select arguments.
738 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
739 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
740 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000741
742 if (isa<PHINode>(Op0))
743 if (Instruction *NV = FoldOpIntoPhi(I))
744 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000745 }
746
Chris Lattner3082c5a2003-02-18 19:28:33 +0000747 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000748 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000749 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
750 // is not used by anyone else...
751 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000752 if (Op1I->getOpcode() == Instruction::Sub &&
753 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000754 // Swap the two operands of the subexpr...
755 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
756 Op1I->setOperand(0, IIOp1);
757 Op1I->setOperand(1, IIOp0);
758
759 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000760 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000761 }
762
763 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
764 //
765 if (Op1I->getOpcode() == Instruction::And &&
766 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
767 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
768
Chris Lattner396dbfe2004-06-09 05:08:07 +0000769 Value *NewNot =
770 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000771 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000772 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000773
Chris Lattner0aee4b72004-10-06 15:08:25 +0000774 // -(X sdiv C) -> (X sdiv -C)
775 if (Op1I->getOpcode() == Instruction::Div)
776 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
777 if (CSI->getValue() == 0)
778 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
779 return BinaryOperator::createDiv(Op1I->getOperand(0),
780 ConstantExpr::getNeg(DivRHS));
781
Chris Lattner57c8d992003-02-18 19:57:07 +0000782 // X - X*C --> X * (1-C)
783 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000784 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000785 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner34428442003-05-27 16:40:51 +0000786 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000787 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000788 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000789 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000790 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000791
Chris Lattner57c8d992003-02-18 19:57:07 +0000792 // X*C - X --> X * (C-1)
793 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000794 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000795 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner34428442003-05-27 16:40:51 +0000796 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000797 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000798 return BinaryOperator::createMul(Op1, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000799 }
800
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000801 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000802}
803
Chris Lattnere79e8542004-02-23 06:38:22 +0000804/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
805/// really just returns true if the most significant (sign) bit is set.
806static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
807 if (RHS->getType()->isSigned()) {
808 // True if source is LHS < 0 or LHS <= -1
809 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
810 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
811 } else {
812 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
813 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
814 // the size of the integer type.
815 if (Opcode == Instruction::SetGE)
816 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
817 if (Opcode == Instruction::SetGT)
818 return RHSC->getValue() ==
819 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
820 }
821 return false;
822}
823
Chris Lattner113f4f42002-06-25 16:13:24 +0000824Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000825 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000826 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000827
Chris Lattnere6794492002-08-12 21:17:25 +0000828 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000829 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
830 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000831
832 // ((X << C1)*C2) == (X * (C2 << C1))
833 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
834 if (SI->getOpcode() == Instruction::Shl)
835 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000836 return BinaryOperator::createMul(SI->getOperand(0),
837 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000838
Chris Lattnercce81be2003-09-11 22:24:54 +0000839 if (CI->isNullValue())
840 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
841 if (CI->equalsInt(1)) // X * 1 == X
842 return ReplaceInstUsesWith(I, Op0);
843 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000844 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000845
Chris Lattnercce81be2003-09-11 22:24:54 +0000846 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000847 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
848 return new ShiftInst(Instruction::Shl, Op0,
849 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000850 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000851 if (Op1F->isNullValue())
852 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000853
Chris Lattner3082c5a2003-02-18 19:28:33 +0000854 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
855 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
856 if (Op1F->getValue() == 1.0)
857 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
858 }
Chris Lattner183b3362004-04-09 19:05:30 +0000859
860 // Try to fold constant mul into select arguments.
861 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
862 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
863 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000864
865 if (isa<PHINode>(Op0))
866 if (Instruction *NV = FoldOpIntoPhi(I))
867 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000868 }
869
Chris Lattner934a64cf2003-03-10 23:23:04 +0000870 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
871 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000872 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000873
Chris Lattner2635b522004-02-23 05:39:21 +0000874 // If one of the operands of the multiply is a cast from a boolean value, then
875 // we know the bool is either zero or one, so this is a 'masking' multiply.
876 // See if we can simplify things based on how the boolean was originally
877 // formed.
878 CastInst *BoolCast = 0;
879 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
880 if (CI->getOperand(0)->getType() == Type::BoolTy)
881 BoolCast = CI;
882 if (!BoolCast)
883 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
884 if (CI->getOperand(0)->getType() == Type::BoolTy)
885 BoolCast = CI;
886 if (BoolCast) {
887 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
888 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
889 const Type *SCOpTy = SCIOp0->getType();
890
Chris Lattnere79e8542004-02-23 06:38:22 +0000891 // If the setcc is true iff the sign bit of X is set, then convert this
892 // multiply into a shift/and combination.
893 if (isa<ConstantInt>(SCIOp1) &&
894 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000895 // Shift the X value right to turn it into "all signbits".
896 Constant *Amt = ConstantUInt::get(Type::UByteTy,
897 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000898 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000899 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000900 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
901 SCIOp0->getName()), I);
902 }
903
904 Value *V =
905 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
906 BoolCast->getOperand(0)->getName()+
907 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000908
909 // If the multiply type is not the same as the source type, sign extend
910 // or truncate to the multiply type.
911 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000912 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000913
914 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000915 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000916 }
917 }
918 }
919
Chris Lattner113f4f42002-06-25 16:13:24 +0000920 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000921}
922
Chris Lattner113f4f42002-06-25 16:13:24 +0000923Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000924 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000925 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000926 if (RHS->equalsInt(1))
927 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000928
Chris Lattnere20c3342004-04-26 14:01:59 +0000929 // div X, -1 == -X
930 if (RHS->isAllOnesValue())
931 return BinaryOperator::createNeg(I.getOperand(0));
932
Chris Lattner272d5ca2004-09-28 18:22:15 +0000933 if (Instruction *LHS = dyn_cast<Instruction>(I.getOperand(0)))
934 if (LHS->getOpcode() == Instruction::Div)
935 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +0000936 // (X / C1) / C2 -> X / (C1*C2)
937 return BinaryOperator::createDiv(LHS->getOperand(0),
938 ConstantExpr::getMul(RHS, LHSRHS));
939 }
940
Chris Lattner3082c5a2003-02-18 19:28:33 +0000941 // Check to see if this is an unsigned division with an exact power of 2,
942 // if so, convert to a right shift.
943 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
944 if (uint64_t Val = C->getValue()) // Don't break X / 0
945 if (uint64_t C = Log2(Val))
946 return new ShiftInst(Instruction::Shr, I.getOperand(0),
947 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000948
949 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
950 if (Instruction *NV = FoldOpIntoPhi(I))
951 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000952 }
953
954 // 0 / X == 0, we don't need to preserve faults!
955 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
956 if (LHS->equalsInt(0))
957 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
958
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000959 return 0;
960}
961
962
Chris Lattner113f4f42002-06-25 16:13:24 +0000963Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000964 if (I.getType()->isSigned())
965 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner98c6bdf2004-07-06 07:11:42 +0000966 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +0000967 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000968 // X % -Y -> X % Y
969 AddUsesToWorkList(I);
970 I.setOperand(1, RHSNeg);
971 return &I;
972 }
973
Chris Lattner3082c5a2003-02-18 19:28:33 +0000974 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
975 if (RHS->equalsInt(1)) // X % 1 == 0
976 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
977
978 // Check to see if this is an unsigned remainder with an exact power of 2,
979 // if so, convert to a bitwise and.
980 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
981 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +0000982 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000983 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattner3082c5a2003-02-18 19:28:33 +0000984 ConstantUInt::get(I.getType(), Val-1));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000985 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
986 if (Instruction *NV = FoldOpIntoPhi(I))
987 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000988 }
989
990 // 0 % X == 0, we don't need to preserve faults!
991 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
992 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000993 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
994
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000995 return 0;
996}
997
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000998// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000999static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001000 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1001 // Calculate -1 casted to the right type...
1002 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1003 uint64_t Val = ~0ULL; // All ones
1004 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1005 return CU->getValue() == Val-1;
1006 }
1007
1008 const ConstantSInt *CS = cast<ConstantSInt>(C);
1009
1010 // Calculate 0111111111..11111
1011 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1012 int64_t Val = INT64_MAX; // All ones
1013 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1014 return CS->getValue() == Val-1;
1015}
1016
1017// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001018static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001019 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1020 return CU->getValue() == 1;
1021
1022 const ConstantSInt *CS = cast<ConstantSInt>(C);
1023
1024 // Calculate 1111111111000000000000
1025 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1026 int64_t Val = -1; // All ones
1027 Val <<= TypeBits-1; // Shift over to the right spot
1028 return CS->getValue() == Val+1;
1029}
1030
Chris Lattner35167c32004-06-09 07:59:58 +00001031// isOneBitSet - Return true if there is exactly one bit set in the specified
1032// constant.
1033static bool isOneBitSet(const ConstantInt *CI) {
1034 uint64_t V = CI->getRawValue();
1035 return V && (V & (V-1)) == 0;
1036}
1037
Chris Lattner8fc5af42004-09-23 21:46:38 +00001038#if 0 // Currently unused
1039// isLowOnes - Return true if the constant is of the form 0+1+.
1040static bool isLowOnes(const ConstantInt *CI) {
1041 uint64_t V = CI->getRawValue();
1042
1043 // There won't be bits set in parts that the type doesn't contain.
1044 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1045
1046 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1047 return U && V && (U & V) == 0;
1048}
1049#endif
1050
1051// isHighOnes - Return true if the constant is of the form 1+0+.
1052// This is the same as lowones(~X).
1053static bool isHighOnes(const ConstantInt *CI) {
1054 uint64_t V = ~CI->getRawValue();
1055
1056 // There won't be bits set in parts that the type doesn't contain.
1057 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1058
1059 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1060 return U && V && (U & V) == 0;
1061}
1062
1063
Chris Lattner3ac7c262003-08-13 20:16:26 +00001064/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1065/// are carefully arranged to allow folding of expressions such as:
1066///
1067/// (A < B) | (A > B) --> (A != B)
1068///
1069/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1070/// represents that the comparison is true if A == B, and bit value '1' is true
1071/// if A < B.
1072///
1073static unsigned getSetCondCode(const SetCondInst *SCI) {
1074 switch (SCI->getOpcode()) {
1075 // False -> 0
1076 case Instruction::SetGT: return 1;
1077 case Instruction::SetEQ: return 2;
1078 case Instruction::SetGE: return 3;
1079 case Instruction::SetLT: return 4;
1080 case Instruction::SetNE: return 5;
1081 case Instruction::SetLE: return 6;
1082 // True -> 7
1083 default:
1084 assert(0 && "Invalid SetCC opcode!");
1085 return 0;
1086 }
1087}
1088
1089/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1090/// opcode and two operands into either a constant true or false, or a brand new
1091/// SetCC instruction.
1092static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1093 switch (Opcode) {
1094 case 0: return ConstantBool::False;
1095 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1096 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1097 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1098 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1099 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1100 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1101 case 7: return ConstantBool::True;
1102 default: assert(0 && "Illegal SetCCCode!"); return 0;
1103 }
1104}
1105
1106// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1107struct FoldSetCCLogical {
1108 InstCombiner &IC;
1109 Value *LHS, *RHS;
1110 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1111 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1112 bool shouldApply(Value *V) const {
1113 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1114 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1115 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1116 return false;
1117 }
1118 Instruction *apply(BinaryOperator &Log) const {
1119 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1120 if (SCI->getOperand(0) != LHS) {
1121 assert(SCI->getOperand(1) == LHS);
1122 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1123 }
1124
1125 unsigned LHSCode = getSetCondCode(SCI);
1126 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1127 unsigned Code;
1128 switch (Log.getOpcode()) {
1129 case Instruction::And: Code = LHSCode & RHSCode; break;
1130 case Instruction::Or: Code = LHSCode | RHSCode; break;
1131 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001132 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001133 }
1134
1135 Value *RV = getSetCCValue(Code, LHS, RHS);
1136 if (Instruction *I = dyn_cast<Instruction>(RV))
1137 return I;
1138 // Otherwise, it's a constant boolean value...
1139 return IC.ReplaceInstUsesWith(Log, RV);
1140 }
1141};
1142
1143
Chris Lattnerba1cb382003-09-19 17:17:26 +00001144// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1145// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1146// guaranteed to be either a shift instruction or a binary operator.
1147Instruction *InstCombiner::OptAndOp(Instruction *Op,
1148 ConstantIntegral *OpRHS,
1149 ConstantIntegral *AndRHS,
1150 BinaryOperator &TheAnd) {
1151 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001152 Constant *Together = 0;
1153 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001154 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001155
Chris Lattnerba1cb382003-09-19 17:17:26 +00001156 switch (Op->getOpcode()) {
1157 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001158 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001159 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001160 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001161 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001162 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1163 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001164 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001165 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001166 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001167 }
1168 break;
1169 case Instruction::Or:
1170 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001171 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001172 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001173 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001174 if (Together == AndRHS) // (X | C) & C --> C
1175 return ReplaceInstUsesWith(TheAnd, AndRHS);
1176
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001177 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001178 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1179 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001180 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001181 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001182 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001183 }
1184 }
1185 break;
1186 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001187 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001188 // Adding a one to a single bit bit-field should be turned into an XOR
1189 // of the bit. First thing to check is to see if this AND is with a
1190 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001191 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001192
1193 // Clear bits that are not part of the constant.
1194 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1195
1196 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001197 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001198 // Ok, at this point, we know that we are masking the result of the
1199 // ADD down to exactly one bit. If the constant we are adding has
1200 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001201 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001202
1203 // Check to see if any bits below the one bit set in AndRHSV are set.
1204 if ((AddRHS & (AndRHSV-1)) == 0) {
1205 // If not, the only thing that can effect the output of the AND is
1206 // the bit specified by AndRHSV. If that bit is set, the effect of
1207 // the XOR is to toggle the bit. If it is clear, then the ADD has
1208 // no effect.
1209 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1210 TheAnd.setOperand(0, X);
1211 return &TheAnd;
1212 } else {
1213 std::string Name = Op->getName(); Op->setName("");
1214 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001215 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001216 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001217 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001218 }
1219 }
1220 }
1221 }
1222 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001223
1224 case Instruction::Shl: {
1225 // We know that the AND will not produce any of the bits shifted in, so if
1226 // the anded constant includes them, clear them now!
1227 //
1228 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001229 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1230 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1231
1232 if (CI == ShlMask) { // Masking out bits that the shift already masks
1233 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1234 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001235 TheAnd.setOperand(1, CI);
1236 return &TheAnd;
1237 }
1238 break;
1239 }
1240 case Instruction::Shr:
1241 // We know that the AND will not produce any of the bits shifted in, so if
1242 // the anded constant includes them, clear them now! This only applies to
1243 // unsigned shifts, because a signed shr may bring in set bits!
1244 //
1245 if (AndRHS->getType()->isUnsigned()) {
1246 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001247 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1248 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1249
1250 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1251 return ReplaceInstUsesWith(TheAnd, Op);
1252 } else if (CI != AndRHS) {
1253 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001254 return &TheAnd;
1255 }
Chris Lattner7e794272004-09-24 15:21:34 +00001256 } else { // Signed shr.
1257 // See if this is shifting in some sign extension, then masking it out
1258 // with an and.
1259 if (Op->hasOneUse()) {
1260 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1261 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1262 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1263 if (CI == ShrMask) { // Masking out bits shifted in.
1264 // Make the argument unsigned.
1265 Value *ShVal = Op->getOperand(0);
1266 ShVal = InsertCastBefore(ShVal,
1267 ShVal->getType()->getUnsignedVersion(),
1268 TheAnd);
1269 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1270 OpRHS, Op->getName()),
1271 TheAnd);
1272 return new CastInst(ShVal, Op->getType());
1273 }
1274 }
Chris Lattner2da29172003-09-19 19:05:02 +00001275 }
1276 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001277 }
1278 return 0;
1279}
1280
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001281
Chris Lattner6862fbd2004-09-29 17:40:11 +00001282/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1283/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1284/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1285/// insert new instructions.
1286Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1287 bool Inside, Instruction &IB) {
1288 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1289 "Lo is not <= Hi in range emission code!");
1290 if (Inside) {
1291 if (Lo == Hi) // Trivially false.
1292 return new SetCondInst(Instruction::SetNE, V, V);
1293 if (cast<ConstantIntegral>(Lo)->isMinValue())
1294 return new SetCondInst(Instruction::SetLT, V, Hi);
1295
1296 Constant *AddCST = ConstantExpr::getNeg(Lo);
1297 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1298 InsertNewInstBefore(Add, IB);
1299 // Convert to unsigned for the comparison.
1300 const Type *UnsType = Add->getType()->getUnsignedVersion();
1301 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1302 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1303 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1304 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1305 }
1306
1307 if (Lo == Hi) // Trivially true.
1308 return new SetCondInst(Instruction::SetEQ, V, V);
1309
1310 Hi = SubOne(cast<ConstantInt>(Hi));
1311 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1312 return new SetCondInst(Instruction::SetGT, V, Hi);
1313
1314 // Emit X-Lo > Hi-Lo-1
1315 Constant *AddCST = ConstantExpr::getNeg(Lo);
1316 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1317 InsertNewInstBefore(Add, IB);
1318 // Convert to unsigned for the comparison.
1319 const Type *UnsType = Add->getType()->getUnsignedVersion();
1320 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1321 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1322 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1323 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1324}
1325
1326
Chris Lattner113f4f42002-06-25 16:13:24 +00001327Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001328 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001329 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001330
1331 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001332 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1333 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001334
1335 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001336 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001337 if (RHS->isAllOnesValue())
1338 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001339
Chris Lattnerba1cb382003-09-19 17:17:26 +00001340 // Optimize a variety of ((val OP C1) & C2) combinations...
1341 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1342 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001343 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001344 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001345 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1346 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001347 }
Chris Lattner183b3362004-04-09 19:05:30 +00001348
1349 // Try to fold constant and into select arguments.
1350 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1351 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1352 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001353 if (isa<PHINode>(Op0))
1354 if (Instruction *NV = FoldOpIntoPhi(I))
1355 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001356 }
1357
Chris Lattnerbb74e222003-03-10 23:06:50 +00001358 Value *Op0NotVal = dyn_castNotVal(Op0);
1359 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001360
Chris Lattner023a4832004-06-18 06:07:51 +00001361 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1362 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1363
Misha Brukman9c003d82004-07-30 12:50:08 +00001364 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001365 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001366 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1367 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001368 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001369 return BinaryOperator::createNot(Or);
1370 }
1371
Chris Lattner623826c2004-09-28 21:48:02 +00001372 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1373 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001374 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1375 return R;
1376
Chris Lattner623826c2004-09-28 21:48:02 +00001377 Value *LHSVal, *RHSVal;
1378 ConstantInt *LHSCst, *RHSCst;
1379 Instruction::BinaryOps LHSCC, RHSCC;
1380 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1381 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1382 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1383 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1384 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1385 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1386 // Ensure that the larger constant is on the RHS.
1387 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1388 SetCondInst *LHS = cast<SetCondInst>(Op0);
1389 if (cast<ConstantBool>(Cmp)->getValue()) {
1390 std::swap(LHS, RHS);
1391 std::swap(LHSCst, RHSCst);
1392 std::swap(LHSCC, RHSCC);
1393 }
1394
1395 // At this point, we know we have have two setcc instructions
1396 // comparing a value against two constants and and'ing the result
1397 // together. Because of the above check, we know that we only have
1398 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1399 // FoldSetCCLogical check above), that the two constants are not
1400 // equal.
1401 assert(LHSCst != RHSCst && "Compares not folded above?");
1402
1403 switch (LHSCC) {
1404 default: assert(0 && "Unknown integer condition code!");
1405 case Instruction::SetEQ:
1406 switch (RHSCC) {
1407 default: assert(0 && "Unknown integer condition code!");
1408 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1409 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1410 return ReplaceInstUsesWith(I, ConstantBool::False);
1411 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1412 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1413 return ReplaceInstUsesWith(I, LHS);
1414 }
1415 case Instruction::SetNE:
1416 switch (RHSCC) {
1417 default: assert(0 && "Unknown integer condition code!");
1418 case Instruction::SetLT:
1419 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1420 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1421 break; // (X != 13 & X < 15) -> no change
1422 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1423 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1424 return ReplaceInstUsesWith(I, RHS);
1425 case Instruction::SetNE:
1426 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1427 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1428 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1429 LHSVal->getName()+".off");
1430 InsertNewInstBefore(Add, I);
1431 const Type *UnsType = Add->getType()->getUnsignedVersion();
1432 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1433 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1434 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1435 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1436 }
1437 break; // (X != 13 & X != 15) -> no change
1438 }
1439 break;
1440 case Instruction::SetLT:
1441 switch (RHSCC) {
1442 default: assert(0 && "Unknown integer condition code!");
1443 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1444 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1445 return ReplaceInstUsesWith(I, ConstantBool::False);
1446 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1447 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1448 return ReplaceInstUsesWith(I, LHS);
1449 }
1450 case Instruction::SetGT:
1451 switch (RHSCC) {
1452 default: assert(0 && "Unknown integer condition code!");
1453 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1454 return ReplaceInstUsesWith(I, LHS);
1455 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1456 return ReplaceInstUsesWith(I, RHS);
1457 case Instruction::SetNE:
1458 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1459 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1460 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001461 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1462 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001463 }
1464 }
1465 }
1466 }
1467
Chris Lattner113f4f42002-06-25 16:13:24 +00001468 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001469}
1470
Chris Lattner113f4f42002-06-25 16:13:24 +00001471Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001472 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001473 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001474
1475 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001476 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1477 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001478
1479 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001480 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001481 if (RHS->isAllOnesValue())
1482 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001483
Chris Lattnerd4252a72004-07-30 07:50:03 +00001484 ConstantInt *C1; Value *X;
1485 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1486 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1487 std::string Op0Name = Op0->getName(); Op0->setName("");
1488 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1489 InsertNewInstBefore(Or, I);
1490 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1491 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001492
Chris Lattnerd4252a72004-07-30 07:50:03 +00001493 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1494 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1495 std::string Op0Name = Op0->getName(); Op0->setName("");
1496 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1497 InsertNewInstBefore(Or, I);
1498 return BinaryOperator::createXor(Or,
1499 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001500 }
Chris Lattner183b3362004-04-09 19:05:30 +00001501
1502 // Try to fold constant and into select arguments.
1503 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1504 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1505 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001506 if (isa<PHINode>(Op0))
1507 if (Instruction *NV = FoldOpIntoPhi(I))
1508 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001509 }
1510
Chris Lattner812aab72003-08-12 19:11:07 +00001511 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001512 Value *A, *B; ConstantInt *C1, *C2;
1513 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1514 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1515 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001516
Chris Lattnerd4252a72004-07-30 07:50:03 +00001517 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1518 if (A == Op1) // ~A | A == -1
1519 return ReplaceInstUsesWith(I,
1520 ConstantIntegral::getAllOnesValue(I.getType()));
1521 } else {
1522 A = 0;
1523 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001524
Chris Lattnerd4252a72004-07-30 07:50:03 +00001525 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1526 if (Op0 == B)
1527 return ReplaceInstUsesWith(I,
1528 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001529
Misha Brukman9c003d82004-07-30 12:50:08 +00001530 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001531 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1532 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1533 I.getName()+".demorgan"), I);
1534 return BinaryOperator::createNot(And);
1535 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001536 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001537
Chris Lattner3ac7c262003-08-13 20:16:26 +00001538 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001539 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001540 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1541 return R;
1542
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001543 Value *LHSVal, *RHSVal;
1544 ConstantInt *LHSCst, *RHSCst;
1545 Instruction::BinaryOps LHSCC, RHSCC;
1546 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1547 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1548 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1549 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1550 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1551 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1552 // Ensure that the larger constant is on the RHS.
1553 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1554 SetCondInst *LHS = cast<SetCondInst>(Op0);
1555 if (cast<ConstantBool>(Cmp)->getValue()) {
1556 std::swap(LHS, RHS);
1557 std::swap(LHSCst, RHSCst);
1558 std::swap(LHSCC, RHSCC);
1559 }
1560
1561 // At this point, we know we have have two setcc instructions
1562 // comparing a value against two constants and or'ing the result
1563 // together. Because of the above check, we know that we only have
1564 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1565 // FoldSetCCLogical check above), that the two constants are not
1566 // equal.
1567 assert(LHSCst != RHSCst && "Compares not folded above?");
1568
1569 switch (LHSCC) {
1570 default: assert(0 && "Unknown integer condition code!");
1571 case Instruction::SetEQ:
1572 switch (RHSCC) {
1573 default: assert(0 && "Unknown integer condition code!");
1574 case Instruction::SetEQ:
1575 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1576 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1577 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1578 LHSVal->getName()+".off");
1579 InsertNewInstBefore(Add, I);
1580 const Type *UnsType = Add->getType()->getUnsignedVersion();
1581 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1582 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1583 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1584 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1585 }
1586 break; // (X == 13 | X == 15) -> no change
1587
1588 case Instruction::SetGT:
1589 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1590 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1591 break; // (X == 13 | X > 15) -> no change
1592 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1593 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1594 return ReplaceInstUsesWith(I, RHS);
1595 }
1596 break;
1597 case Instruction::SetNE:
1598 switch (RHSCC) {
1599 default: assert(0 && "Unknown integer condition code!");
1600 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1601 return ReplaceInstUsesWith(I, RHS);
1602 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1603 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1604 return ReplaceInstUsesWith(I, LHS);
1605 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1606 return ReplaceInstUsesWith(I, ConstantBool::True);
1607 }
1608 break;
1609 case Instruction::SetLT:
1610 switch (RHSCC) {
1611 default: assert(0 && "Unknown integer condition code!");
1612 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1613 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001614 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1615 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001616 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1617 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1618 return ReplaceInstUsesWith(I, RHS);
1619 }
1620 break;
1621 case Instruction::SetGT:
1622 switch (RHSCC) {
1623 default: assert(0 && "Unknown integer condition code!");
1624 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1625 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1626 return ReplaceInstUsesWith(I, LHS);
1627 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1628 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1629 return ReplaceInstUsesWith(I, ConstantBool::True);
1630 }
1631 }
1632 }
1633 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001634 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001635}
1636
Chris Lattnerc2076352004-02-16 01:20:27 +00001637// XorSelf - Implements: X ^ X --> 0
1638struct XorSelf {
1639 Value *RHS;
1640 XorSelf(Value *rhs) : RHS(rhs) {}
1641 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1642 Instruction *apply(BinaryOperator &Xor) const {
1643 return &Xor;
1644 }
1645};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001646
1647
Chris Lattner113f4f42002-06-25 16:13:24 +00001648Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001649 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001650 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001651
Chris Lattnerc2076352004-02-16 01:20:27 +00001652 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1653 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1654 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001655 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001656 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001657
Chris Lattner97638592003-07-23 21:37:07 +00001658 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001659 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001660 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001661 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001662
Chris Lattner97638592003-07-23 21:37:07 +00001663 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001664 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001665 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001666 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001667 return new SetCondInst(SCI->getInverseCondition(),
1668 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001669
Chris Lattner8f2f5982003-11-05 01:06:05 +00001670 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001671 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1672 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001673 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1674 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001675 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001676 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001677 }
Chris Lattner023a4832004-06-18 06:07:51 +00001678
1679 // ~(~X & Y) --> (X | ~Y)
1680 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1681 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1682 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1683 Instruction *NotY =
1684 BinaryOperator::createNot(Op0I->getOperand(1),
1685 Op0I->getOperand(1)->getName()+".not");
1686 InsertNewInstBefore(NotY, I);
1687 return BinaryOperator::createOr(Op0NotVal, NotY);
1688 }
1689 }
Chris Lattner97638592003-07-23 21:37:07 +00001690
1691 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001692 switch (Op0I->getOpcode()) {
1693 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001694 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001695 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001696 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1697 return BinaryOperator::createSub(
1698 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001699 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001700 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001701 }
Chris Lattnere5806662003-11-04 23:50:51 +00001702 break;
1703 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001704 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001705 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1706 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001707 break;
1708 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001709 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001710 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001711 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001712 break;
1713 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001714 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001715 }
Chris Lattner183b3362004-04-09 19:05:30 +00001716
1717 // Try to fold constant and into select arguments.
1718 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1719 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1720 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001721 if (isa<PHINode>(Op0))
1722 if (Instruction *NV = FoldOpIntoPhi(I))
1723 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001724 }
1725
Chris Lattnerbb74e222003-03-10 23:06:50 +00001726 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001727 if (X == Op1)
1728 return ReplaceInstUsesWith(I,
1729 ConstantIntegral::getAllOnesValue(I.getType()));
1730
Chris Lattnerbb74e222003-03-10 23:06:50 +00001731 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001732 if (X == Op0)
1733 return ReplaceInstUsesWith(I,
1734 ConstantIntegral::getAllOnesValue(I.getType()));
1735
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001736 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001737 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001738 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1739 cast<BinaryOperator>(Op1I)->swapOperands();
1740 I.swapOperands();
1741 std::swap(Op0, Op1);
1742 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1743 I.swapOperands();
1744 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001745 }
1746 } else if (Op1I->getOpcode() == Instruction::Xor) {
1747 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1748 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1749 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1750 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1751 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001752
1753 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001754 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001755 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1756 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001757 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001758 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1759 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001760 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001761 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001762 } else if (Op0I->getOpcode() == Instruction::Xor) {
1763 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1764 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1765 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1766 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001767 }
1768
Chris Lattner7aa2d472004-08-01 19:42:59 +00001769 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001770 Value *A, *B; ConstantInt *C1, *C2;
1771 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1772 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00001773 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00001774 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001775
Chris Lattner3ac7c262003-08-13 20:16:26 +00001776 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1777 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1778 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1779 return R;
1780
Chris Lattner113f4f42002-06-25 16:13:24 +00001781 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001782}
1783
Chris Lattner6862fbd2004-09-29 17:40:11 +00001784/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1785/// overflowed for this type.
1786static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1787 ConstantInt *In2) {
1788 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1789 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1790}
1791
1792static bool isPositive(ConstantInt *C) {
1793 return cast<ConstantSInt>(C)->getValue() >= 0;
1794}
1795
1796/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1797/// overflowed for this type.
1798static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1799 ConstantInt *In2) {
1800 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1801
1802 if (In1->getType()->isUnsigned())
1803 return cast<ConstantUInt>(Result)->getValue() <
1804 cast<ConstantUInt>(In1)->getValue();
1805 if (isPositive(In1) != isPositive(In2))
1806 return false;
1807 if (isPositive(In1))
1808 return cast<ConstantSInt>(Result)->getValue() <
1809 cast<ConstantSInt>(In1)->getValue();
1810 return cast<ConstantSInt>(Result)->getValue() >
1811 cast<ConstantSInt>(In1)->getValue();
1812}
1813
Chris Lattner113f4f42002-06-25 16:13:24 +00001814Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001815 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001816 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1817 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001818
1819 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001820 if (Op0 == Op1)
1821 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001822
Chris Lattnerd07283a2003-08-13 05:38:46 +00001823 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1824 if (isa<ConstantPointerNull>(Op1) &&
1825 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001826 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1827
Chris Lattnerd07283a2003-08-13 05:38:46 +00001828
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001829 // setcc's with boolean values can always be turned into bitwise operations
1830 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00001831 switch (I.getOpcode()) {
1832 default: assert(0 && "Invalid setcc instruction!");
1833 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001834 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001835 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001836 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001837 }
Chris Lattner4456da62004-08-11 00:50:51 +00001838 case Instruction::SetNE:
1839 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001840
Chris Lattner4456da62004-08-11 00:50:51 +00001841 case Instruction::SetGT:
1842 std::swap(Op0, Op1); // Change setgt -> setlt
1843 // FALL THROUGH
1844 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1845 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1846 InsertNewInstBefore(Not, I);
1847 return BinaryOperator::createAnd(Not, Op1);
1848 }
1849 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001850 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00001851 // FALL THROUGH
1852 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1853 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1854 InsertNewInstBefore(Not, I);
1855 return BinaryOperator::createOr(Not, Op1);
1856 }
1857 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001858 }
1859
Chris Lattner2dd01742004-06-09 04:24:29 +00001860 // See if we are doing a comparison between a constant and an instruction that
1861 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001862 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00001863 // Check to see if we are comparing against the minimum or maximum value...
1864 if (CI->isMinValue()) {
1865 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1866 return ReplaceInstUsesWith(I, ConstantBool::False);
1867 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1868 return ReplaceInstUsesWith(I, ConstantBool::True);
1869 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1870 return BinaryOperator::createSetEQ(Op0, Op1);
1871 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1872 return BinaryOperator::createSetNE(Op0, Op1);
1873
1874 } else if (CI->isMaxValue()) {
1875 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1876 return ReplaceInstUsesWith(I, ConstantBool::False);
1877 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1878 return ReplaceInstUsesWith(I, ConstantBool::True);
1879 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1880 return BinaryOperator::createSetEQ(Op0, Op1);
1881 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1882 return BinaryOperator::createSetNE(Op0, Op1);
1883
1884 // Comparing against a value really close to min or max?
1885 } else if (isMinValuePlusOne(CI)) {
1886 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1887 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
1888 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1889 return BinaryOperator::createSetNE(Op0, SubOne(CI));
1890
1891 } else if (isMaxValueMinusOne(CI)) {
1892 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1893 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
1894 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1895 return BinaryOperator::createSetNE(Op0, AddOne(CI));
1896 }
1897
1898 // If we still have a setle or setge instruction, turn it into the
1899 // appropriate setlt or setgt instruction. Since the border cases have
1900 // already been handled above, this requires little checking.
1901 //
1902 if (I.getOpcode() == Instruction::SetLE)
1903 return BinaryOperator::createSetLT(Op0, AddOne(CI));
1904 if (I.getOpcode() == Instruction::SetGE)
1905 return BinaryOperator::createSetGT(Op0, SubOne(CI));
1906
Chris Lattnere1e10e12004-05-25 06:32:08 +00001907 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001908 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001909 case Instruction::PHI:
1910 if (Instruction *NV = FoldOpIntoPhi(I))
1911 return NV;
1912 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001913 case Instruction::And:
1914 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1915 LHSI->getOperand(0)->hasOneUse()) {
1916 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1917 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1918 // happens a LOT in code produced by the C front-end, for bitfield
1919 // access.
1920 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1921 ConstantUInt *ShAmt;
1922 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1923 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1924 const Type *Ty = LHSI->getType();
1925
1926 // We can fold this as long as we can't shift unknown bits
1927 // into the mask. This can only happen with signed shift
1928 // rights, as they sign-extend.
1929 if (ShAmt) {
1930 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00001931 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001932 if (!CanFold) {
1933 // To test for the bad case of the signed shr, see if any
1934 // of the bits shifted in could be tested after the mask.
1935 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00001936 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001937 Constant *ShVal =
1938 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1939 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1940 CanFold = true;
1941 }
1942
1943 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00001944 Constant *NewCst;
1945 if (Shift->getOpcode() == Instruction::Shl)
1946 NewCst = ConstantExpr::getUShr(CI, ShAmt);
1947 else
1948 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00001949
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001950 // Check to see if we are shifting out any of the bits being
1951 // compared.
1952 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1953 // If we shifted bits out, the fold is not going to work out.
1954 // As a special case, check to see if this means that the
1955 // result is always true or false now.
1956 if (I.getOpcode() == Instruction::SetEQ)
1957 return ReplaceInstUsesWith(I, ConstantBool::False);
1958 if (I.getOpcode() == Instruction::SetNE)
1959 return ReplaceInstUsesWith(I, ConstantBool::True);
1960 } else {
1961 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00001962 Constant *NewAndCST;
1963 if (Shift->getOpcode() == Instruction::Shl)
1964 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
1965 else
1966 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1967 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001968 LHSI->setOperand(0, Shift->getOperand(0));
1969 WorkList.push_back(Shift); // Shift is dead.
1970 AddUsesToWorkList(I);
1971 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00001972 }
1973 }
Chris Lattner35167c32004-06-09 07:59:58 +00001974 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001975 }
1976 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00001977
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001978 case Instruction::Cast: { // (setcc (cast X to larger), CI)
1979 const Type *SrcTy = LHSI->getOperand(0)->getType();
1980 if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) {
Chris Lattnerc9491282004-09-29 03:16:24 +00001981 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001982 if (SrcTy == Type::BoolTy) SrcBits = 1;
Chris Lattnerc9491282004-09-29 03:16:24 +00001983 unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001984 if (LHSI->getType() == Type::BoolTy) DestBits = 1;
1985 if (SrcBits < DestBits) {
1986 // Check to see if the comparison is always true or false.
1987 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
1988 if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
1989 Constant *Min = ConstantIntegral::getMinValue(SrcTy);
1990 Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
1991 Min = ConstantExpr::getCast(Min, LHSI->getType());
1992 Max = ConstantExpr::getCast(Max, LHSI->getType());
1993 switch (I.getOpcode()) {
1994 default: assert(0 && "unknown integer comparison");
1995 case Instruction::SetEQ:
1996 return ReplaceInstUsesWith(I, ConstantBool::False);
1997 case Instruction::SetNE:
1998 return ReplaceInstUsesWith(I, ConstantBool::True);
1999 case Instruction::SetLT:
2000 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002001 case Instruction::SetGT:
2002 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002003 }
2004 }
2005
2006 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
2007 ConstantExpr::getCast(CI, SrcTy));
2008 }
2009 }
2010 break;
2011 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00002012 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2013 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2014 switch (I.getOpcode()) {
2015 default: break;
2016 case Instruction::SetEQ:
2017 case Instruction::SetNE: {
2018 // If we are comparing against bits always shifted out, the
2019 // comparison cannot succeed.
2020 Constant *Comp =
2021 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2022 if (Comp != CI) {// Comparing against a bit that we know is zero.
2023 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2024 Constant *Cst = ConstantBool::get(IsSetNE);
2025 return ReplaceInstUsesWith(I, Cst);
2026 }
2027
2028 if (LHSI->hasOneUse()) {
2029 // Otherwise strength reduce the shift into an and.
2030 unsigned ShAmtVal = ShAmt->getValue();
2031 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2032 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2033
2034 Constant *Mask;
2035 if (CI->getType()->isUnsigned()) {
2036 Mask = ConstantUInt::get(CI->getType(), Val);
2037 } else if (ShAmtVal != 0) {
2038 Mask = ConstantSInt::get(CI->getType(), Val);
2039 } else {
2040 Mask = ConstantInt::getAllOnesValue(CI->getType());
2041 }
2042
2043 Instruction *AndI =
2044 BinaryOperator::createAnd(LHSI->getOperand(0),
2045 Mask, LHSI->getName()+".mask");
2046 Value *And = InsertNewInstBefore(AndI, I);
2047 return new SetCondInst(I.getOpcode(), And,
2048 ConstantExpr::getUShr(CI, ShAmt));
2049 }
2050 }
2051 }
2052 }
2053 break;
2054
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002055 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002056 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002057 switch (I.getOpcode()) {
2058 default: break;
2059 case Instruction::SetEQ:
2060 case Instruction::SetNE: {
2061 // If we are comparing against bits always shifted out, the
2062 // comparison cannot succeed.
2063 Constant *Comp =
2064 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2065
2066 if (Comp != CI) {// Comparing against a bit that we know is zero.
2067 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2068 Constant *Cst = ConstantBool::get(IsSetNE);
2069 return ReplaceInstUsesWith(I, Cst);
2070 }
2071
2072 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00002073 unsigned ShAmtVal = ShAmt->getValue();
2074
Chris Lattner1023b872004-09-27 16:18:50 +00002075 // Otherwise strength reduce the shift into an and.
2076 uint64_t Val = ~0ULL; // All ones.
2077 Val <<= ShAmtVal; // Shift over to the right spot.
2078
2079 Constant *Mask;
2080 if (CI->getType()->isUnsigned()) {
2081 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2082 Val &= (1ULL << TypeBits)-1;
2083 Mask = ConstantUInt::get(CI->getType(), Val);
2084 } else {
2085 Mask = ConstantSInt::get(CI->getType(), Val);
2086 }
2087
2088 Instruction *AndI =
2089 BinaryOperator::createAnd(LHSI->getOperand(0),
2090 Mask, LHSI->getName()+".mask");
2091 Value *And = InsertNewInstBefore(AndI, I);
2092 return new SetCondInst(I.getOpcode(), And,
2093 ConstantExpr::getShl(CI, ShAmt));
2094 }
2095 break;
2096 }
2097 }
2098 }
2099 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002100
Chris Lattner6862fbd2004-09-29 17:40:11 +00002101 case Instruction::Div:
2102 // Fold: (div X, C1) op C2 -> range check
2103 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2104 // Fold this div into the comparison, producing a range check.
2105 // Determine, based on the divide type, what the range is being
2106 // checked. If there is an overflow on the low or high side, remember
2107 // it, otherwise compute the range [low, hi) bounding the new value.
2108 bool LoOverflow = false, HiOverflow = 0;
2109 ConstantInt *LoBound = 0, *HiBound = 0;
2110
2111 ConstantInt *Prod;
2112 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2113
2114 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2115 } else if (LHSI->getType()->isUnsigned()) { // udiv
2116 LoBound = Prod;
2117 LoOverflow = ProdOV;
2118 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2119 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2120 if (CI->isNullValue()) { // (X / pos) op 0
2121 // Can't overflow.
2122 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2123 HiBound = DivRHS;
2124 } else if (isPositive(CI)) { // (X / pos) op pos
2125 LoBound = Prod;
2126 LoOverflow = ProdOV;
2127 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2128 } else { // (X / pos) op neg
2129 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2130 LoOverflow = AddWithOverflow(LoBound, Prod,
2131 cast<ConstantInt>(DivRHSH));
2132 HiBound = Prod;
2133 HiOverflow = ProdOV;
2134 }
2135 } else { // Divisor is < 0.
2136 if (CI->isNullValue()) { // (X / neg) op 0
2137 LoBound = AddOne(DivRHS);
2138 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2139 } else if (isPositive(CI)) { // (X / neg) op pos
2140 HiOverflow = LoOverflow = ProdOV;
2141 if (!LoOverflow)
2142 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2143 HiBound = AddOne(Prod);
2144 } else { // (X / neg) op neg
2145 LoBound = Prod;
2146 LoOverflow = HiOverflow = ProdOV;
2147 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2148 }
2149 }
2150
2151 if (LoBound) {
2152 Value *X = LHSI->getOperand(0);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002153 switch (I.getOpcode()) {
2154 default: assert(0 && "Unhandled setcc opcode!");
2155 case Instruction::SetEQ:
2156 if (LoOverflow && HiOverflow)
2157 return ReplaceInstUsesWith(I, ConstantBool::False);
2158 else if (HiOverflow)
2159 return new SetCondInst(Instruction::SetGE, X, LoBound);
2160 else if (LoOverflow)
2161 return new SetCondInst(Instruction::SetLT, X, HiBound);
2162 else
2163 return InsertRangeTest(X, LoBound, HiBound, true, I);
2164 case Instruction::SetNE:
2165 if (LoOverflow && HiOverflow)
2166 return ReplaceInstUsesWith(I, ConstantBool::True);
2167 else if (HiOverflow)
2168 return new SetCondInst(Instruction::SetLT, X, LoBound);
2169 else if (LoOverflow)
2170 return new SetCondInst(Instruction::SetGE, X, HiBound);
2171 else
2172 return InsertRangeTest(X, LoBound, HiBound, false, I);
2173 case Instruction::SetLT:
2174 if (LoOverflow)
2175 return ReplaceInstUsesWith(I, ConstantBool::False);
2176 return new SetCondInst(Instruction::SetLT, X, LoBound);
2177 case Instruction::SetGT:
2178 if (HiOverflow)
2179 return ReplaceInstUsesWith(I, ConstantBool::False);
2180 return new SetCondInst(Instruction::SetGE, X, HiBound);
2181 }
2182 }
2183 }
2184 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002185 case Instruction::Select:
2186 // If either operand of the select is a constant, we can fold the
2187 // comparison into the select arms, which will cause one to be
2188 // constant folded and the select turned into a bitwise or.
2189 Value *Op1 = 0, *Op2 = 0;
2190 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00002191 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002192 // Fold the known value into the constant operand.
2193 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2194 // Insert a new SetCC of the other select operand.
2195 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002196 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002197 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00002198 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002199 // Fold the known value into the constant operand.
2200 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2201 // Insert a new SetCC of the other select operand.
2202 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002203 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002204 I.getName()), I);
2205 }
Chris Lattner2dd01742004-06-09 04:24:29 +00002206 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002207
2208 if (Op1)
2209 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2210 break;
2211 }
2212
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002213 // Simplify seteq and setne instructions...
2214 if (I.getOpcode() == Instruction::SetEQ ||
2215 I.getOpcode() == Instruction::SetNE) {
2216 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2217
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002218 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002219 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002220 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2221 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002222 case Instruction::Rem:
2223 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2224 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2225 BO->hasOneUse() &&
2226 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2227 if (unsigned L2 =
2228 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2229 const Type *UTy = BO->getType()->getUnsignedVersion();
2230 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2231 UTy, "tmp"), I);
2232 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2233 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2234 RHSCst, BO->getName()), I);
2235 return BinaryOperator::create(I.getOpcode(), NewRem,
2236 Constant::getNullValue(UTy));
2237 }
2238 break;
2239
Chris Lattnerc992add2003-08-13 05:33:12 +00002240 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002241 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2242 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002243 if (BO->hasOneUse())
2244 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2245 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002246 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002247 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2248 // efficiently invertible, or if the add has just this one use.
2249 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00002250
Chris Lattnerc992add2003-08-13 05:33:12 +00002251 if (Value *NegVal = dyn_castNegVal(BOp1))
2252 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2253 else if (Value *NegVal = dyn_castNegVal(BOp0))
2254 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002255 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002256 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2257 BO->setName("");
2258 InsertNewInstBefore(Neg, I);
2259 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2260 }
2261 }
2262 break;
2263 case Instruction::Xor:
2264 // For the xor case, we can xor two constants together, eliminating
2265 // the explicit xor.
2266 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2267 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002268 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002269
2270 // FALLTHROUGH
2271 case Instruction::Sub:
2272 // Replace (([sub|xor] A, B) != 0) with (A != B)
2273 if (CI->isNullValue())
2274 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2275 BO->getOperand(1));
2276 break;
2277
2278 case Instruction::Or:
2279 // If bits are being or'd in that are not present in the constant we
2280 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002281 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002282 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002283 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002284 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002285 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002286 break;
2287
2288 case Instruction::And:
2289 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002290 // If bits are being compared against that are and'd out, then the
2291 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002292 if (!ConstantExpr::getAnd(CI,
2293 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002294 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002295
Chris Lattner35167c32004-06-09 07:59:58 +00002296 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002297 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002298 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2299 Instruction::SetNE, Op0,
2300 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002301
Chris Lattnerc992add2003-08-13 05:33:12 +00002302 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2303 // to be a signed value as appropriate.
2304 if (isSignBit(BOC)) {
2305 Value *X = BO->getOperand(0);
2306 // If 'X' is not signed, insert a cast now...
2307 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002308 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002309 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002310 }
2311 return new SetCondInst(isSetNE ? Instruction::SetLT :
2312 Instruction::SetGE, X,
2313 Constant::getNullValue(X->getType()));
2314 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002315
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002316 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002317 if (CI->isNullValue() && isHighOnes(BOC)) {
2318 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002319 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002320
2321 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002322 if (NegX->getType()->isSigned()) {
2323 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2324 X = InsertCastBefore(X, DestTy, I);
2325 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002326 }
2327
2328 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002329 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002330 }
2331
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002332 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002333 default: break;
2334 }
2335 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002336 } else { // Not a SetEQ/SetNE
2337 // If the LHS is a cast from an integral value of the same size,
2338 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2339 Value *CastOp = Cast->getOperand(0);
2340 const Type *SrcTy = CastOp->getType();
2341 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2342 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2343 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2344 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2345 "Source and destination signednesses should differ!");
2346 if (Cast->getType()->isSigned()) {
2347 // If this is a signed comparison, check for comparisons in the
2348 // vicinity of zero.
2349 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2350 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002351 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002352 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2353 else if (I.getOpcode() == Instruction::SetGT &&
2354 cast<ConstantSInt>(CI)->getValue() == -1)
2355 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002356 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002357 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2358 } else {
2359 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2360 if (I.getOpcode() == Instruction::SetLT &&
2361 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2362 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002363 return BinaryOperator::createSetGT(CastOp,
2364 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002365 else if (I.getOpcode() == Instruction::SetGT &&
2366 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2367 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002368 return BinaryOperator::createSetLT(CastOp,
2369 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002370 }
2371 }
2372 }
Chris Lattnere967b342003-06-04 05:10:11 +00002373 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002374 }
2375
Chris Lattner16930792003-11-03 04:25:02 +00002376 // Test to see if the operands of the setcc are casted versions of other
2377 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002378 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2379 Value *CastOp0 = CI->getOperand(0);
2380 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002381 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002382 (I.getOpcode() == Instruction::SetEQ ||
2383 I.getOpcode() == Instruction::SetNE)) {
2384 // We keep moving the cast from the left operand over to the right
2385 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002386 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002387
2388 // If operand #1 is a cast instruction, see if we can eliminate it as
2389 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002390 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2391 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002392 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002393 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002394
2395 // If Op1 is a constant, we can fold the cast into the constant.
2396 if (Op1->getType() != Op0->getType())
2397 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2398 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2399 } else {
2400 // Otherwise, cast the RHS right before the setcc
2401 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2402 InsertNewInstBefore(cast<Instruction>(Op1), I);
2403 }
2404 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2405 }
2406
Chris Lattner6444c372003-11-03 05:17:03 +00002407 // Handle the special case of: setcc (cast bool to X), <cst>
2408 // This comes up when you have code like
2409 // int X = A < B;
2410 // if (X) ...
2411 // For generality, we handle any zero-extension of any operand comparison
2412 // with a constant.
2413 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2414 const Type *SrcTy = CastOp0->getType();
2415 const Type *DestTy = Op0->getType();
2416 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2417 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2418 // Ok, we have an expansion of operand 0 into a new type. Get the
2419 // constant value, masink off bits which are not set in the RHS. These
2420 // could be set if the destination value is signed.
2421 uint64_t ConstVal = ConstantRHS->getRawValue();
2422 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2423
2424 // If the constant we are comparing it with has high bits set, which
2425 // don't exist in the original value, the values could never be equal,
2426 // because the source would be zero extended.
2427 unsigned SrcBits =
2428 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002429 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2430 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002431 switch (I.getOpcode()) {
2432 default: assert(0 && "Unknown comparison type!");
2433 case Instruction::SetEQ:
2434 return ReplaceInstUsesWith(I, ConstantBool::False);
2435 case Instruction::SetNE:
2436 return ReplaceInstUsesWith(I, ConstantBool::True);
2437 case Instruction::SetLT:
2438 case Instruction::SetLE:
2439 if (DestTy->isSigned() && HasSignBit)
2440 return ReplaceInstUsesWith(I, ConstantBool::False);
2441 return ReplaceInstUsesWith(I, ConstantBool::True);
2442 case Instruction::SetGT:
2443 case Instruction::SetGE:
2444 if (DestTy->isSigned() && HasSignBit)
2445 return ReplaceInstUsesWith(I, ConstantBool::True);
2446 return ReplaceInstUsesWith(I, ConstantBool::False);
2447 }
2448 }
2449
2450 // Otherwise, we can replace the setcc with a setcc of the smaller
2451 // operand value.
2452 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2453 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2454 }
2455 }
2456 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002457 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002458}
2459
2460
2461
Chris Lattnere8d6c602003-03-10 19:16:08 +00002462Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002463 assert(I.getOperand(1)->getType() == Type::UByteTy);
2464 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002465 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002466
2467 // shl X, 0 == X and shr X, 0 == X
2468 // shl 0, X == 0 and shr 0, X == 0
2469 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00002470 Op0 == Constant::getNullValue(Op0->getType()))
2471 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002472
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002473 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2474 if (!isLeftShift)
2475 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2476 if (CSI->isAllOnesValue())
2477 return ReplaceInstUsesWith(I, CSI);
2478
Chris Lattner183b3362004-04-09 19:05:30 +00002479 // Try to fold constant and into select arguments.
2480 if (isa<Constant>(Op0))
2481 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2482 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2483 return R;
2484
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002485 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002486 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2487 // of a signed value.
2488 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00002489 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002490 if (CUI->getValue() >= TypeBits) {
2491 if (!Op0->getType()->isSigned() || isLeftShift)
2492 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2493 else {
2494 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2495 return &I;
2496 }
2497 }
Chris Lattner55f3d942002-09-10 23:04:09 +00002498
Chris Lattnerede3fe02003-08-13 04:18:28 +00002499 // ((X*C1) << C2) == (X * (C1 << C2))
2500 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2501 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2502 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002503 return BinaryOperator::createMul(BO->getOperand(0),
2504 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00002505
Chris Lattner183b3362004-04-09 19:05:30 +00002506 // Try to fold constant and into select arguments.
2507 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2508 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2509 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002510 if (isa<PHINode>(Op0))
2511 if (Instruction *NV = FoldOpIntoPhi(I))
2512 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00002513
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002514 // If the operand is an bitwise operator with a constant RHS, and the
2515 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002516 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002517 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2518 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2519 bool isValid = true; // Valid only for And, Or, Xor
2520 bool highBitSet = false; // Transform if high bit of constant set?
2521
2522 switch (Op0BO->getOpcode()) {
2523 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00002524 case Instruction::Add:
2525 isValid = isLeftShift;
2526 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002527 case Instruction::Or:
2528 case Instruction::Xor:
2529 highBitSet = false;
2530 break;
2531 case Instruction::And:
2532 highBitSet = true;
2533 break;
2534 }
2535
2536 // If this is a signed shift right, and the high bit is modified
2537 // by the logical operation, do not perform the transformation.
2538 // The highBitSet boolean indicates the value of the high bit of
2539 // the constant which would cause it to be modified for this
2540 // operation.
2541 //
2542 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2543 uint64_t Val = Op0C->getRawValue();
2544 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2545 }
2546
2547 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002548 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002549
2550 Instruction *NewShift =
2551 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2552 Op0BO->getName());
2553 Op0BO->setName("");
2554 InsertNewInstBefore(NewShift, I);
2555
2556 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2557 NewRHS);
2558 }
2559 }
2560
Chris Lattner3204d4e2003-07-24 17:52:58 +00002561 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002562 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00002563 if (ConstantUInt *ShiftAmt1C =
2564 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002565 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2566 unsigned ShiftAmt2 = CUI->getValue();
2567
2568 // Check for (A << c1) << c2 and (A >> c1) >> c2
2569 if (I.getOpcode() == Op0SI->getOpcode()) {
2570 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002571 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2572 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00002573 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2574 ConstantUInt::get(Type::UByteTy, Amt));
2575 }
2576
Chris Lattnerab780df2003-07-24 18:38:56 +00002577 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2578 // signed types, we can only support the (A >> c1) << c2 configuration,
2579 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002580 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002581 // Calculate bitmask for what gets shifted off the edge...
2582 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002583 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002584 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002585 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002586 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00002587
2588 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002589 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2590 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00002591 InsertNewInstBefore(Mask, I);
2592
2593 // Figure out what flavor of shift we should use...
2594 if (ShiftAmt1 == ShiftAmt2)
2595 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2596 else if (ShiftAmt1 < ShiftAmt2) {
2597 return new ShiftInst(I.getOpcode(), Mask,
2598 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2599 } else {
2600 return new ShiftInst(Op0SI->getOpcode(), Mask,
2601 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2602 }
2603 }
2604 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002605 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00002606
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002607 return 0;
2608}
2609
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002610enum CastType {
2611 Noop = 0,
2612 Truncate = 1,
2613 Signext = 2,
2614 Zeroext = 3
2615};
2616
2617/// getCastType - In the future, we will split the cast instruction into these
2618/// various types. Until then, we have to do the analysis here.
2619static CastType getCastType(const Type *Src, const Type *Dest) {
2620 assert(Src->isIntegral() && Dest->isIntegral() &&
2621 "Only works on integral types!");
2622 unsigned SrcSize = Src->getPrimitiveSize()*8;
2623 if (Src == Type::BoolTy) SrcSize = 1;
2624 unsigned DestSize = Dest->getPrimitiveSize()*8;
2625 if (Dest == Type::BoolTy) DestSize = 1;
2626
2627 if (SrcSize == DestSize) return Noop;
2628 if (SrcSize > DestSize) return Truncate;
2629 if (Src->isSigned()) return Signext;
2630 return Zeroext;
2631}
2632
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002633
Chris Lattner48a44f72002-05-02 17:06:02 +00002634// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2635// instruction.
2636//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002637static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00002638 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002639
Chris Lattner650b6da2002-08-02 20:00:25 +00002640 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2641 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00002642 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00002643 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00002644 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00002645
Chris Lattner4fbad962004-07-21 04:27:24 +00002646 // If we are casting between pointer and integer types, treat pointers as
2647 // integers of the appropriate size for the code below.
2648 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2649 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2650 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00002651
Chris Lattner48a44f72002-05-02 17:06:02 +00002652 // Allow free casting and conversion of sizes as long as the sign doesn't
2653 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002654 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002655 CastType FirstCast = getCastType(SrcTy, MidTy);
2656 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00002657
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002658 // Capture the effect of these two casts. If the result is a legal cast,
2659 // the CastType is stored here, otherwise a special code is used.
2660 static const unsigned CastResult[] = {
2661 // First cast is noop
2662 0, 1, 2, 3,
2663 // First cast is a truncate
2664 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2665 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00002666 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002667 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00002668 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002669 };
2670
2671 unsigned Result = CastResult[FirstCast*4+SecondCast];
2672 switch (Result) {
2673 default: assert(0 && "Illegal table value!");
2674 case 0:
2675 case 1:
2676 case 2:
2677 case 3:
2678 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2679 // truncates, we could eliminate more casts.
2680 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2681 case 4:
2682 return false; // Not possible to eliminate this here.
2683 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00002684 // Sign or zero extend followed by truncate is always ok if the result
2685 // is a truncate or noop.
2686 CastType ResultCast = getCastType(SrcTy, DstTy);
2687 if (ResultCast == Noop || ResultCast == Truncate)
2688 return true;
2689 // Otherwise we are still growing the value, we are only safe if the
2690 // result will match the sign/zeroextendness of the result.
2691 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00002692 }
Chris Lattner650b6da2002-08-02 20:00:25 +00002693 }
Chris Lattner48a44f72002-05-02 17:06:02 +00002694 return false;
2695}
2696
Chris Lattner11ffd592004-07-20 05:21:00 +00002697static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002698 if (V->getType() == Ty || isa<Constant>(V)) return false;
2699 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00002700 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2701 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002702 return false;
2703 return true;
2704}
2705
2706/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2707/// InsertBefore instruction. This is specialized a bit to avoid inserting
2708/// casts that are known to not do anything...
2709///
2710Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2711 Instruction *InsertBefore) {
2712 if (V->getType() == DestTy) return V;
2713 if (Constant *C = dyn_cast<Constant>(V))
2714 return ConstantExpr::getCast(C, DestTy);
2715
2716 CastInst *CI = new CastInst(V, DestTy, V->getName());
2717 InsertNewInstBefore(CI, *InsertBefore);
2718 return CI;
2719}
Chris Lattner48a44f72002-05-02 17:06:02 +00002720
2721// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002722//
Chris Lattner113f4f42002-06-25 16:13:24 +00002723Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002724 Value *Src = CI.getOperand(0);
2725
Chris Lattner48a44f72002-05-02 17:06:02 +00002726 // If the user is casting a value to the same type, eliminate this cast
2727 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002728 if (CI.getType() == Src->getType())
2729 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002730
Chris Lattner48a44f72002-05-02 17:06:02 +00002731 // If casting the result of another cast instruction, try to eliminate this
2732 // one!
2733 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002734 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002735 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner11ffd592004-07-20 05:21:00 +00002736 CSrc->getType(), CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002737 // This instruction now refers directly to the cast's src operand. This
2738 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002739 CI.setOperand(0, CSrc->getOperand(0));
2740 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002741 }
2742
Chris Lattner650b6da2002-08-02 20:00:25 +00002743 // If this is an A->B->A cast, and we are dealing with integral types, try
2744 // to convert this into a logical 'and' instruction.
2745 //
2746 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002747 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002748 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2749 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2750 assert(CSrc->getType() != Type::ULongTy &&
2751 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002752 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002753 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002754 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002755 }
2756 }
2757
Chris Lattner03841652004-05-25 04:29:21 +00002758 // If this is a cast to bool, turn it into the appropriate setne instruction.
2759 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002760 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002761 Constant::getNullValue(CI.getOperand(0)->getType()));
2762
Chris Lattnerd0d51602003-06-21 23:12:02 +00002763 // If casting the result of a getelementptr instruction with no offset, turn
2764 // this into a cast of the original pointer!
2765 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002766 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002767 bool AllZeroOperands = true;
2768 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2769 if (!isa<Constant>(GEP->getOperand(i)) ||
2770 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2771 AllZeroOperands = false;
2772 break;
2773 }
2774 if (AllZeroOperands) {
2775 CI.setOperand(0, GEP->getOperand(0));
2776 return &CI;
2777 }
2778 }
2779
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002780 // If we are casting a malloc or alloca to a pointer to a type of the same
2781 // size, rewrite the allocation instruction to allocate the "right" type.
2782 //
2783 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002784 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002785 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2786 // Get the type really allocated and the type casted to...
2787 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002788 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002789 if (AllocElTy->isSized() && CastElTy->isSized()) {
2790 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2791 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002792
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002793 // If the allocation is for an even multiple of the cast type size
2794 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2795 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002796 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002797 std::string Name = AI->getName(); AI->setName("");
2798 AllocationInst *New;
2799 if (isa<MallocInst>(AI))
2800 New = new MallocInst(CastElTy, Amt, Name);
2801 else
2802 New = new AllocaInst(CastElTy, Amt, Name);
2803 InsertNewInstBefore(New, *AI);
2804 return ReplaceInstUsesWith(CI, New);
2805 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002806 }
2807 }
2808
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002809 if (isa<PHINode>(Src))
2810 if (Instruction *NV = FoldOpIntoPhi(CI))
2811 return NV;
2812
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002813 // If the source value is an instruction with only this use, we can attempt to
2814 // propagate the cast into the instruction. Also, only handle integral types
2815 // for now.
2816 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002817 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002818 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2819 const Type *DestTy = CI.getType();
2820 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2821 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2822
2823 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2824 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2825
2826 switch (SrcI->getOpcode()) {
2827 case Instruction::Add:
2828 case Instruction::Mul:
2829 case Instruction::And:
2830 case Instruction::Or:
2831 case Instruction::Xor:
2832 // If we are discarding information, or just changing the sign, rewrite.
2833 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2834 // Don't insert two casts if they cannot be eliminated. We allow two
2835 // casts to be inserted if the sizes are the same. This could only be
2836 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00002837 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2838 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002839 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2840 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2841 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2842 ->getOpcode(), Op0c, Op1c);
2843 }
2844 }
2845 break;
2846 case Instruction::Shl:
2847 // Allow changing the sign of the source operand. Do not allow changing
2848 // the size of the shift, UNLESS the shift amount is a constant. We
2849 // mush not change variable sized shifts to a smaller size, because it
2850 // is undefined to shift more bits out than exist in the value.
2851 if (DestBitSize == SrcBitSize ||
2852 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2853 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2854 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2855 }
2856 break;
2857 }
2858 }
2859
Chris Lattner260ab202002-04-18 17:39:14 +00002860 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00002861}
2862
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002863/// GetSelectFoldableOperands - We want to turn code that looks like this:
2864/// %C = or %A, %B
2865/// %D = select %cond, %C, %A
2866/// into:
2867/// %C = select %cond, %B, 0
2868/// %D = or %A, %C
2869///
2870/// Assuming that the specified instruction is an operand to the select, return
2871/// a bitmask indicating which operands of this instruction are foldable if they
2872/// equal the other incoming value of the select.
2873///
2874static unsigned GetSelectFoldableOperands(Instruction *I) {
2875 switch (I->getOpcode()) {
2876 case Instruction::Add:
2877 case Instruction::Mul:
2878 case Instruction::And:
2879 case Instruction::Or:
2880 case Instruction::Xor:
2881 return 3; // Can fold through either operand.
2882 case Instruction::Sub: // Can only fold on the amount subtracted.
2883 case Instruction::Shl: // Can only fold on the shift amount.
2884 case Instruction::Shr:
2885 return 1;
2886 default:
2887 return 0; // Cannot fold
2888 }
2889}
2890
2891/// GetSelectFoldableConstant - For the same transformation as the previous
2892/// function, return the identity constant that goes into the select.
2893static Constant *GetSelectFoldableConstant(Instruction *I) {
2894 switch (I->getOpcode()) {
2895 default: assert(0 && "This cannot happen!"); abort();
2896 case Instruction::Add:
2897 case Instruction::Sub:
2898 case Instruction::Or:
2899 case Instruction::Xor:
2900 return Constant::getNullValue(I->getType());
2901 case Instruction::Shl:
2902 case Instruction::Shr:
2903 return Constant::getNullValue(Type::UByteTy);
2904 case Instruction::And:
2905 return ConstantInt::getAllOnesValue(I->getType());
2906 case Instruction::Mul:
2907 return ConstantInt::get(I->getType(), 1);
2908 }
2909}
2910
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002911Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00002912 Value *CondVal = SI.getCondition();
2913 Value *TrueVal = SI.getTrueValue();
2914 Value *FalseVal = SI.getFalseValue();
2915
2916 // select true, X, Y -> X
2917 // select false, X, Y -> Y
2918 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002919 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00002920 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002921 else {
2922 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00002923 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002924 }
Chris Lattner533bc492004-03-30 19:37:13 +00002925
2926 // select C, X, X -> X
2927 if (TrueVal == FalseVal)
2928 return ReplaceInstUsesWith(SI, TrueVal);
2929
Chris Lattner1c631e82004-04-08 04:43:23 +00002930 if (SI.getType() == Type::BoolTy)
2931 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2932 if (C == ConstantBool::True) {
2933 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002934 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002935 } else {
2936 // Change: A = select B, false, C --> A = and !B, C
2937 Value *NotCond =
2938 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2939 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002940 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002941 }
2942 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2943 if (C == ConstantBool::False) {
2944 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002945 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002946 } else {
2947 // Change: A = select B, C, true --> A = or !B, C
2948 Value *NotCond =
2949 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2950 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002951 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002952 }
2953 }
2954
Chris Lattner183b3362004-04-09 19:05:30 +00002955 // Selecting between two integer constants?
2956 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2957 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2958 // select C, 1, 0 -> cast C to int
2959 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2960 return new CastInst(CondVal, SI.getType());
2961 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2962 // select C, 0, 1 -> cast !C to int
2963 Value *NotCond =
2964 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00002965 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00002966 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00002967 }
Chris Lattner35167c32004-06-09 07:59:58 +00002968
2969 // If one of the constants is zero (we know they can't both be) and we
2970 // have a setcc instruction with zero, and we have an 'and' with the
2971 // non-constant value, eliminate this whole mess. This corresponds to
2972 // cases like this: ((X & 27) ? 27 : 0)
2973 if (TrueValC->isNullValue() || FalseValC->isNullValue())
2974 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
2975 if ((IC->getOpcode() == Instruction::SetEQ ||
2976 IC->getOpcode() == Instruction::SetNE) &&
2977 isa<ConstantInt>(IC->getOperand(1)) &&
2978 cast<Constant>(IC->getOperand(1))->isNullValue())
2979 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
2980 if (ICA->getOpcode() == Instruction::And &&
2981 isa<ConstantInt>(ICA->getOperand(1)) &&
2982 (ICA->getOperand(1) == TrueValC ||
2983 ICA->getOperand(1) == FalseValC) &&
2984 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
2985 // Okay, now we know that everything is set up, we just don't
2986 // know whether we have a setne or seteq and whether the true or
2987 // false val is the zero.
2988 bool ShouldNotVal = !TrueValC->isNullValue();
2989 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
2990 Value *V = ICA;
2991 if (ShouldNotVal)
2992 V = InsertNewInstBefore(BinaryOperator::create(
2993 Instruction::Xor, V, ICA->getOperand(1)), SI);
2994 return ReplaceInstUsesWith(SI, V);
2995 }
Chris Lattner533bc492004-03-30 19:37:13 +00002996 }
Chris Lattner623fba12004-04-10 22:21:27 +00002997
2998 // See if we are selecting two values based on a comparison of the two values.
2999 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3000 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3001 // Transform (X == Y) ? X : Y -> Y
3002 if (SCI->getOpcode() == Instruction::SetEQ)
3003 return ReplaceInstUsesWith(SI, FalseVal);
3004 // Transform (X != Y) ? X : Y -> X
3005 if (SCI->getOpcode() == Instruction::SetNE)
3006 return ReplaceInstUsesWith(SI, TrueVal);
3007 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3008
3009 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3010 // Transform (X == Y) ? Y : X -> X
3011 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003012 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003013 // Transform (X != Y) ? Y : X -> Y
3014 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003015 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003016 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3017 }
3018 }
Chris Lattner1c631e82004-04-08 04:43:23 +00003019
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003020 // See if we can fold the select into one of our operands.
3021 if (SI.getType()->isInteger()) {
3022 // See the comment above GetSelectFoldableOperands for a description of the
3023 // transformation we are doing here.
3024 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3025 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3026 !isa<Constant>(FalseVal))
3027 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3028 unsigned OpToFold = 0;
3029 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3030 OpToFold = 1;
3031 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3032 OpToFold = 2;
3033 }
3034
3035 if (OpToFold) {
3036 Constant *C = GetSelectFoldableConstant(TVI);
3037 std::string Name = TVI->getName(); TVI->setName("");
3038 Instruction *NewSel =
3039 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3040 Name);
3041 InsertNewInstBefore(NewSel, SI);
3042 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3043 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3044 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3045 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3046 else {
3047 assert(0 && "Unknown instruction!!");
3048 }
3049 }
3050 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003051
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003052 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3053 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3054 !isa<Constant>(TrueVal))
3055 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3056 unsigned OpToFold = 0;
3057 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3058 OpToFold = 1;
3059 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3060 OpToFold = 2;
3061 }
3062
3063 if (OpToFold) {
3064 Constant *C = GetSelectFoldableConstant(FVI);
3065 std::string Name = FVI->getName(); FVI->setName("");
3066 Instruction *NewSel =
3067 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3068 Name);
3069 InsertNewInstBefore(NewSel, SI);
3070 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3071 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3072 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3073 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3074 else {
3075 assert(0 && "Unknown instruction!!");
3076 }
3077 }
3078 }
3079 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003080 return 0;
3081}
3082
3083
Chris Lattner970c33a2003-06-19 17:00:31 +00003084// CallInst simplification
3085//
3086Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003087 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3088 // visitCallSite.
3089 if (Function *F = CI.getCalledFunction())
3090 switch (F->getIntrinsicID()) {
3091 case Intrinsic::memmove:
3092 case Intrinsic::memcpy:
3093 case Intrinsic::memset:
3094 // memmove/cpy/set of zero bytes is a noop.
3095 if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
3096 if (NumBytes->isNullValue())
3097 return EraseInstFromFunction(CI);
3098 }
3099 break;
3100 default:
3101 break;
3102 }
3103
Chris Lattneraec3d942003-10-07 22:32:43 +00003104 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003105}
3106
3107// InvokeInst simplification
3108//
3109Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003110 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003111}
3112
Chris Lattneraec3d942003-10-07 22:32:43 +00003113// visitCallSite - Improvements for call and invoke instructions.
3114//
3115Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003116 bool Changed = false;
3117
3118 // If the callee is a constexpr cast of a function, attempt to move the cast
3119 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003120 if (transformConstExprCastCall(CS)) return 0;
3121
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003122 Value *Callee = CS.getCalledValue();
3123 const PointerType *PTy = cast<PointerType>(Callee->getType());
3124 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3125 if (FTy->isVarArg()) {
3126 // See if we can optimize any arguments passed through the varargs area of
3127 // the call.
3128 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3129 E = CS.arg_end(); I != E; ++I)
3130 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3131 // If this cast does not effect the value passed through the varargs
3132 // area, we can eliminate the use of the cast.
3133 Value *Op = CI->getOperand(0);
3134 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3135 *I = Op;
3136 Changed = true;
3137 }
3138 }
3139 }
Chris Lattneraec3d942003-10-07 22:32:43 +00003140
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003141 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00003142}
3143
Chris Lattner970c33a2003-06-19 17:00:31 +00003144// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3145// attempt to move the cast to the arguments of the call/invoke.
3146//
3147bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3148 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3149 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00003150 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00003151 return false;
Reid Spencer87436872004-07-18 00:38:32 +00003152 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00003153 Instruction *Caller = CS.getInstruction();
3154
3155 // Okay, this is a cast from a function to a different type. Unless doing so
3156 // would cause a type conversion of one of our arguments, change this call to
3157 // be a direct call with arguments casted to the appropriate types.
3158 //
3159 const FunctionType *FT = Callee->getFunctionType();
3160 const Type *OldRetTy = Caller->getType();
3161
Chris Lattner1f7942f2004-01-14 06:06:08 +00003162 // Check to see if we are changing the return type...
3163 if (OldRetTy != FT->getReturnType()) {
3164 if (Callee->isExternal() &&
3165 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3166 !Caller->use_empty())
3167 return false; // Cannot transform this return value...
3168
3169 // If the callsite is an invoke instruction, and the return value is used by
3170 // a PHI node in a successor, we cannot change the return type of the call
3171 // because there is no place to put the cast instruction (without breaking
3172 // the critical edge). Bail out in this case.
3173 if (!Caller->use_empty())
3174 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3175 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3176 UI != E; ++UI)
3177 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3178 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003179 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00003180 return false;
3181 }
Chris Lattner970c33a2003-06-19 17:00:31 +00003182
3183 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3184 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3185
3186 CallSite::arg_iterator AI = CS.arg_begin();
3187 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3188 const Type *ParamTy = FT->getParamType(i);
3189 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3190 if (Callee->isExternal() && !isConvertible) return false;
3191 }
3192
3193 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3194 Callee->isExternal())
3195 return false; // Do not delete arguments unless we have a function body...
3196
3197 // Okay, we decided that this is a safe thing to do: go ahead and start
3198 // inserting cast instructions as necessary...
3199 std::vector<Value*> Args;
3200 Args.reserve(NumActualArgs);
3201
3202 AI = CS.arg_begin();
3203 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3204 const Type *ParamTy = FT->getParamType(i);
3205 if ((*AI)->getType() == ParamTy) {
3206 Args.push_back(*AI);
3207 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00003208 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3209 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00003210 }
3211 }
3212
3213 // If the function takes more arguments than the call was taking, add them
3214 // now...
3215 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3216 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3217
3218 // If we are removing arguments to the function, emit an obnoxious warning...
3219 if (FT->getNumParams() < NumActualArgs)
3220 if (!FT->isVarArg()) {
3221 std::cerr << "WARNING: While resolving call to function '"
3222 << Callee->getName() << "' arguments were dropped!\n";
3223 } else {
3224 // Add all of the arguments in their promoted form to the arg list...
3225 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3226 const Type *PTy = getPromotedType((*AI)->getType());
3227 if (PTy != (*AI)->getType()) {
3228 // Must promote to pass through va_arg area!
3229 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3230 InsertNewInstBefore(Cast, *Caller);
3231 Args.push_back(Cast);
3232 } else {
3233 Args.push_back(*AI);
3234 }
3235 }
3236 }
3237
3238 if (FT->getReturnType() == Type::VoidTy)
3239 Caller->setName(""); // Void type should not have a name...
3240
3241 Instruction *NC;
3242 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003243 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00003244 Args, Caller->getName(), Caller);
3245 } else {
3246 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3247 }
3248
3249 // Insert a cast of the return type as necessary...
3250 Value *NV = NC;
3251 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3252 if (NV->getType() != Type::VoidTy) {
3253 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00003254
3255 // If this is an invoke instruction, we should insert it after the first
3256 // non-phi, instruction in the normal successor block.
3257 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3258 BasicBlock::iterator I = II->getNormalDest()->begin();
3259 while (isa<PHINode>(I)) ++I;
3260 InsertNewInstBefore(NC, *I);
3261 } else {
3262 // Otherwise, it's a call, just insert cast right after the call instr
3263 InsertNewInstBefore(NC, *Caller);
3264 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003265 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00003266 } else {
3267 NV = Constant::getNullValue(Caller->getType());
3268 }
3269 }
3270
3271 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3272 Caller->replaceAllUsesWith(NV);
3273 Caller->getParent()->getInstList().erase(Caller);
3274 removeFromWorkList(Caller);
3275 return true;
3276}
3277
3278
Chris Lattner48a44f72002-05-02 17:06:02 +00003279
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003280// PHINode simplification
3281//
Chris Lattner113f4f42002-06-25 16:13:24 +00003282Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner91daeb52003-12-19 05:58:40 +00003283 if (Value *V = hasConstantValue(&PN))
3284 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00003285
3286 // If the only user of this instruction is a cast instruction, and all of the
3287 // incoming values are constants, change this PHI to merge together the casted
3288 // constants.
3289 if (PN.hasOneUse())
3290 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3291 if (CI->getType() != PN.getType()) { // noop casts will be folded
3292 bool AllConstant = true;
3293 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3294 if (!isa<Constant>(PN.getIncomingValue(i))) {
3295 AllConstant = false;
3296 break;
3297 }
3298 if (AllConstant) {
3299 // Make a new PHI with all casted values.
3300 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3301 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3302 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3303 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3304 PN.getIncomingBlock(i));
3305 }
3306
3307 // Update the cast instruction.
3308 CI->setOperand(0, New);
3309 WorkList.push_back(CI); // revisit the cast instruction to fold.
3310 WorkList.push_back(New); // Make sure to revisit the new Phi
3311 return &PN; // PN is now dead!
3312 }
3313 }
Chris Lattner91daeb52003-12-19 05:58:40 +00003314 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003315}
3316
Chris Lattner69193f92004-04-05 01:30:19 +00003317static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3318 Instruction *InsertPoint,
3319 InstCombiner *IC) {
3320 unsigned PS = IC->getTargetData().getPointerSize();
3321 const Type *VTy = V->getType();
3322 Instruction *Cast;
3323 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3324 // We must insert a cast to ensure we sign-extend.
3325 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3326 V->getName()), *InsertPoint);
3327 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3328 *InsertPoint);
3329}
3330
Chris Lattner48a44f72002-05-02 17:06:02 +00003331
Chris Lattner113f4f42002-06-25 16:13:24 +00003332Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003333 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00003334 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00003335 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003336 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00003337 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003338
3339 bool HasZeroPointerIndex = false;
3340 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3341 HasZeroPointerIndex = C->isNullValue();
3342
3343 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00003344 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00003345
Chris Lattner69193f92004-04-05 01:30:19 +00003346 // Eliminate unneeded casts for indices.
3347 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00003348 gep_type_iterator GTI = gep_type_begin(GEP);
3349 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3350 if (isa<SequentialType>(*GTI)) {
3351 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3352 Value *Src = CI->getOperand(0);
3353 const Type *SrcTy = Src->getType();
3354 const Type *DestTy = CI->getType();
3355 if (Src->getType()->isInteger()) {
3356 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3357 // We can always eliminate a cast from ulong or long to the other.
3358 // We can always eliminate a cast from uint to int or the other on
3359 // 32-bit pointer platforms.
3360 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3361 MadeChange = true;
3362 GEP.setOperand(i, Src);
3363 }
3364 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3365 SrcTy->getPrimitiveSize() == 4) {
3366 // We can always eliminate a cast from int to [u]long. We can
3367 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3368 // pointer target.
3369 if (SrcTy->isSigned() ||
3370 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3371 MadeChange = true;
3372 GEP.setOperand(i, Src);
3373 }
Chris Lattner69193f92004-04-05 01:30:19 +00003374 }
3375 }
3376 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00003377 // If we are using a wider index than needed for this platform, shrink it
3378 // to what we need. If the incoming value needs a cast instruction,
3379 // insert it. This explicit cast can make subsequent optimizations more
3380 // obvious.
3381 Value *Op = GEP.getOperand(i);
3382 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003383 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00003384 GEP.setOperand(i, ConstantExpr::getCast(C,
3385 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003386 MadeChange = true;
3387 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00003388 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3389 Op->getName()), GEP);
3390 GEP.setOperand(i, Op);
3391 MadeChange = true;
3392 }
Chris Lattner44d0b952004-07-20 01:48:15 +00003393
3394 // If this is a constant idx, make sure to canonicalize it to be a signed
3395 // operand, otherwise CSE and other optimizations are pessimized.
3396 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3397 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3398 CUI->getType()->getSignedVersion()));
3399 MadeChange = true;
3400 }
Chris Lattner69193f92004-04-05 01:30:19 +00003401 }
3402 if (MadeChange) return &GEP;
3403
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003404 // Combine Indices - If the source pointer to this getelementptr instruction
3405 // is a getelementptr instruction, combine the indices of the two
3406 // getelementptr instructions into a single instruction.
3407 //
Chris Lattner57c67b02004-03-25 22:59:29 +00003408 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00003409 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003410 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00003411 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003412 if (CE->getOpcode() == Instruction::GetElementPtr)
3413 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3414 }
3415
3416 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003417 // Note that if our source is a gep chain itself that we wait for that
3418 // chain to be resolved before we perform this transformation. This
3419 // avoids us creating a TON of code in some cases.
3420 //
3421 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3422 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3423 return 0; // Wait until our source is folded to completion.
3424
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003425 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00003426
3427 // Find out whether the last index in the source GEP is a sequential idx.
3428 bool EndsWithSequential = false;
3429 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3430 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00003431 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00003432
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003433 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00003434 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00003435 // Replace: gep (gep %P, long B), long A, ...
3436 // With: T = long A+B; gep %P, T, ...
3437 //
Chris Lattner5f667a62004-05-07 22:09:22 +00003438 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00003439 if (SO1 == Constant::getNullValue(SO1->getType())) {
3440 Sum = GO1;
3441 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3442 Sum = SO1;
3443 } else {
3444 // If they aren't the same type, convert both to an integer of the
3445 // target's pointer size.
3446 if (SO1->getType() != GO1->getType()) {
3447 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3448 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3449 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3450 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3451 } else {
3452 unsigned PS = TD->getPointerSize();
3453 Instruction *Cast;
3454 if (SO1->getType()->getPrimitiveSize() == PS) {
3455 // Convert GO1 to SO1's type.
3456 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3457
3458 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3459 // Convert SO1 to GO1's type.
3460 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3461 } else {
3462 const Type *PT = TD->getIntPtrType();
3463 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3464 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3465 }
3466 }
3467 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003468 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3469 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3470 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003471 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3472 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00003473 }
Chris Lattner69193f92004-04-05 01:30:19 +00003474 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003475
3476 // Recycle the GEP we already have if possible.
3477 if (SrcGEPOperands.size() == 2) {
3478 GEP.setOperand(0, SrcGEPOperands[0]);
3479 GEP.setOperand(1, Sum);
3480 return &GEP;
3481 } else {
3482 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3483 SrcGEPOperands.end()-1);
3484 Indices.push_back(Sum);
3485 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3486 }
Chris Lattner69193f92004-04-05 01:30:19 +00003487 } else if (isa<Constant>(*GEP.idx_begin()) &&
3488 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00003489 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003490 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00003491 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3492 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003493 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3494 }
3495
3496 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00003497 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003498
Chris Lattner5f667a62004-05-07 22:09:22 +00003499 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003500 // GEP of global variable. If all of the indices for this GEP are
3501 // constants, we can promote this to a constexpr instead of an instruction.
3502
3503 // Scan for nonconstants...
3504 std::vector<Constant*> Indices;
3505 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3506 for (; I != E && isa<Constant>(*I); ++I)
3507 Indices.push_back(cast<Constant>(*I));
3508
3509 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00003510 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003511
3512 // Replace all uses of the GEP with the new constexpr...
3513 return ReplaceInstUsesWith(GEP, CE);
3514 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003515 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003516 if (CE->getOpcode() == Instruction::Cast) {
3517 if (HasZeroPointerIndex) {
3518 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3519 // into : GEP [10 x ubyte]* X, long 0, ...
3520 //
3521 // This occurs when the program declares an array extern like "int X[];"
3522 //
3523 Constant *X = CE->getOperand(0);
3524 const PointerType *CPTy = cast<PointerType>(CE->getType());
3525 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3526 if (const ArrayType *XATy =
3527 dyn_cast<ArrayType>(XTy->getElementType()))
3528 if (const ArrayType *CATy =
3529 dyn_cast<ArrayType>(CPTy->getElementType()))
3530 if (CATy->getElementType() == XATy->getElementType()) {
3531 // At this point, we know that the cast source type is a pointer
3532 // to an array of the same type as the destination pointer
3533 // array. Because the array type is never stepped over (there
3534 // is a leading zero) we can fold the cast into this GEP.
3535 GEP.setOperand(0, X);
3536 return &GEP;
3537 }
3538 }
3539 }
Chris Lattnerca081252001-12-14 16:52:21 +00003540 }
3541
Chris Lattnerca081252001-12-14 16:52:21 +00003542 return 0;
3543}
3544
Chris Lattner1085bdf2002-11-04 16:18:53 +00003545Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3546 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3547 if (AI.isArrayAllocation()) // Check C != 1
3548 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3549 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003550 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00003551
3552 // Create and insert the replacement instruction...
3553 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00003554 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003555 else {
3556 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00003557 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003558 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003559
3560 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003561
3562 // Scan to the end of the allocation instructions, to skip over a block of
3563 // allocas if possible...
3564 //
3565 BasicBlock::iterator It = New;
3566 while (isa<AllocationInst>(*It)) ++It;
3567
3568 // Now that I is pointing to the first non-allocation-inst in the block,
3569 // insert our getelementptr instruction...
3570 //
Chris Lattner69193f92004-04-05 01:30:19 +00003571 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003572 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3573
3574 // Now make everything use the getelementptr instead of the original
3575 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00003576 return ReplaceInstUsesWith(AI, V);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003577 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003578
3579 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3580 // Note that we only do this for alloca's, because malloc should allocate and
3581 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00003582 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3583 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00003584 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3585
Chris Lattner1085bdf2002-11-04 16:18:53 +00003586 return 0;
3587}
3588
Chris Lattner8427bff2003-12-07 01:24:23 +00003589Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3590 Value *Op = FI.getOperand(0);
3591
3592 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3593 if (CastInst *CI = dyn_cast<CastInst>(Op))
3594 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3595 FI.setOperand(0, CI->getOperand(0));
3596 return &FI;
3597 }
3598
Chris Lattnerf3a36602004-02-28 04:57:37 +00003599 // If we have 'free null' delete the instruction. This can happen in stl code
3600 // when lots of inlining happens.
Chris Lattner51ea1272004-02-28 05:22:00 +00003601 if (isa<ConstantPointerNull>(Op))
3602 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00003603
Chris Lattner8427bff2003-12-07 01:24:23 +00003604 return 0;
3605}
3606
3607
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003608/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3609/// constantexpr, return the constant value being addressed by the constant
3610/// expression, or null if something is funny.
3611///
3612static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00003613 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003614 return 0; // Do not allow stepping over the value!
3615
3616 // Loop over all of the operands, tracking down which value we are
3617 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00003618 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3619 for (++I; I != E; ++I)
3620 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3621 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3622 assert(CU->getValue() < STy->getNumElements() &&
3623 "Struct index out of range!");
3624 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003625 C = CS->getOperand(CU->getValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003626 } else if (isa<ConstantAggregateZero>(C)) {
3627 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
3628 } else {
3629 return 0;
3630 }
3631 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3632 const ArrayType *ATy = cast<ArrayType>(*I);
3633 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3634 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003635 C = CA->getOperand(CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003636 else if (isa<ConstantAggregateZero>(C))
3637 C = Constant::getNullValue(ATy->getElementType());
3638 else
3639 return 0;
3640 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003641 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00003642 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003643 return C;
3644}
3645
Chris Lattner35e24772004-07-13 01:49:43 +00003646static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3647 User *CI = cast<User>(LI.getOperand(0));
3648
3649 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3650 if (const PointerType *SrcTy =
3651 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3652 const Type *SrcPTy = SrcTy->getElementType();
3653 if (SrcPTy->isSized() && DestPTy->isSized() &&
3654 IC.getTargetData().getTypeSize(SrcPTy) ==
3655 IC.getTargetData().getTypeSize(DestPTy) &&
3656 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3657 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3658 // Okay, we are casting from one integer or pointer type to another of
3659 // the same size. Instead of casting the pointer before the load, cast
3660 // the result of the loaded value.
3661 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003662 CI->getName(),
3663 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00003664 // Now cast the result of the load.
3665 return new CastInst(NewLoad, LI.getType());
3666 }
3667 }
3668 return 0;
3669}
3670
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003671/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00003672/// from this value cannot trap. If it is not obviously safe to load from the
3673/// specified pointer, we do a quick local scan of the basic block containing
3674/// ScanFrom, to determine if the address is already accessed.
3675static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3676 // If it is an alloca or global variable, it is always safe to load from.
3677 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3678
3679 // Otherwise, be a little bit agressive by scanning the local block where we
3680 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003681 // from/to. If so, the previous load or store would have already trapped,
3682 // so there is no harm doing an extra load (also, CSE will later eliminate
3683 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00003684 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3685
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003686 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00003687 --BBI;
3688
3689 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3690 if (LI->getOperand(0) == V) return true;
3691 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3692 if (SI->getOperand(1) == V) return true;
3693
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003694 }
Chris Lattnere6f13092004-09-19 19:18:10 +00003695 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003696}
3697
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003698Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3699 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00003700
Chris Lattner6679e462004-04-14 03:28:36 +00003701 if (Constant *C = dyn_cast<Constant>(Op))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003702 if (C->isNullValue() && !LI.isVolatile()) // load null -> 0
Chris Lattner6679e462004-04-14 03:28:36 +00003703 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003704
3705 // Instcombine load (constant global) into the value loaded...
3706 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00003707 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003708 return ReplaceInstUsesWith(LI, GV->getInitializer());
3709
3710 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
3711 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
Chris Lattner35e24772004-07-13 01:49:43 +00003712 if (CE->getOpcode() == Instruction::GetElementPtr) {
Reid Spencer87436872004-07-18 00:38:32 +00003713 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3714 if (GV->isConstant() && !GV->isExternal())
3715 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3716 return ReplaceInstUsesWith(LI, V);
Chris Lattner35e24772004-07-13 01:49:43 +00003717 } else if (CE->getOpcode() == Instruction::Cast) {
3718 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3719 return Res;
3720 }
Chris Lattnere228ee52004-04-08 20:39:49 +00003721
3722 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00003723 if (CastInst *CI = dyn_cast<CastInst>(Op))
3724 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3725 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00003726
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003727 if (!LI.isVolatile() && Op->hasOneUse()) {
3728 // Change select and PHI nodes to select values instead of addresses: this
3729 // helps alias analysis out a lot, allows many others simplifications, and
3730 // exposes redundancy in the code.
3731 //
3732 // Note that we cannot do the transformation unless we know that the
3733 // introduced loads cannot trap! Something like this is valid as long as
3734 // the condition is always false: load (select bool %C, int* null, int* %G),
3735 // but it would not be valid if we transformed it to load from null
3736 // unconditionally.
3737 //
3738 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3739 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00003740 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3741 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003742 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00003743 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003744 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00003745 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003746 return new SelectInst(SI->getCondition(), V1, V2);
3747 }
3748
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00003749 // load (select (cond, null, P)) -> load P
3750 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3751 if (C->isNullValue()) {
3752 LI.setOperand(0, SI->getOperand(2));
3753 return &LI;
3754 }
3755
3756 // load (select (cond, P, null)) -> load P
3757 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3758 if (C->isNullValue()) {
3759 LI.setOperand(0, SI->getOperand(1));
3760 return &LI;
3761 }
3762
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003763 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3764 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00003765 bool Safe = PN->getParent() == LI.getParent();
3766
3767 // Scan all of the instructions between the PHI and the load to make
3768 // sure there are no instructions that might possibly alter the value
3769 // loaded from the PHI.
3770 if (Safe) {
3771 BasicBlock::iterator I = &LI;
3772 for (--I; !isa<PHINode>(I); --I)
3773 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3774 Safe = false;
3775 break;
3776 }
3777 }
3778
3779 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00003780 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00003781 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003782 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00003783
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003784 if (Safe) {
3785 // Create the PHI.
3786 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3787 InsertNewInstBefore(NewPN, *PN);
3788 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3789
3790 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3791 BasicBlock *BB = PN->getIncomingBlock(i);
3792 Value *&TheLoad = LoadMap[BB];
3793 if (TheLoad == 0) {
3794 Value *InVal = PN->getIncomingValue(i);
3795 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3796 InVal->getName()+".val"),
3797 *BB->getTerminator());
3798 }
3799 NewPN->addIncoming(TheLoad, BB);
3800 }
3801 return ReplaceInstUsesWith(LI, NewPN);
3802 }
3803 }
3804 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003805 return 0;
3806}
3807
3808
Chris Lattner9eef8a72003-06-04 04:46:00 +00003809Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3810 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00003811 Value *X;
3812 BasicBlock *TrueDest;
3813 BasicBlock *FalseDest;
3814 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3815 !isa<Constant>(X)) {
3816 // Swap Destinations and condition...
3817 BI.setCondition(X);
3818 BI.setSuccessor(0, FalseDest);
3819 BI.setSuccessor(1, TrueDest);
3820 return &BI;
3821 }
3822
3823 // Cannonicalize setne -> seteq
3824 Instruction::BinaryOps Op; Value *Y;
3825 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3826 TrueDest, FalseDest)))
3827 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3828 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3829 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3830 std::string Name = I->getName(); I->setName("");
3831 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3832 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00003833 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00003834 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00003835 BI.setSuccessor(0, FalseDest);
3836 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003837 removeFromWorkList(I);
3838 I->getParent()->getInstList().erase(I);
3839 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00003840 return &BI;
3841 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00003842
Chris Lattner9eef8a72003-06-04 04:46:00 +00003843 return 0;
3844}
Chris Lattner1085bdf2002-11-04 16:18:53 +00003845
Chris Lattner4c9c20a2004-07-03 00:26:11 +00003846Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3847 Value *Cond = SI.getCondition();
3848 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3849 if (I->getOpcode() == Instruction::Add)
3850 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3851 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3852 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
3853 SI.setOperand(i, ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
3854 AddRHS));
3855 SI.setOperand(0, I->getOperand(0));
3856 WorkList.push_back(I);
3857 return &SI;
3858 }
3859 }
3860 return 0;
3861}
3862
Chris Lattnerca081252001-12-14 16:52:21 +00003863
Chris Lattner99f48c62002-09-02 04:59:56 +00003864void InstCombiner::removeFromWorkList(Instruction *I) {
3865 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3866 WorkList.end());
3867}
3868
Chris Lattner113f4f42002-06-25 16:13:24 +00003869bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00003870 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003871 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00003872
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003873 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3874 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00003875
Chris Lattnerca081252001-12-14 16:52:21 +00003876
3877 while (!WorkList.empty()) {
3878 Instruction *I = WorkList.back(); // Get an instruction from the worklist
3879 WorkList.pop_back();
3880
Misha Brukman632df282002-10-29 23:06:16 +00003881 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00003882 // Check to see if we can DIE the instruction...
3883 if (isInstructionTriviallyDead(I)) {
3884 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003885 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00003886 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00003887 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003888
3889 I->getParent()->getInstList().erase(I);
3890 removeFromWorkList(I);
3891 continue;
3892 }
Chris Lattner99f48c62002-09-02 04:59:56 +00003893
Misha Brukman632df282002-10-29 23:06:16 +00003894 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00003895 if (Constant *C = ConstantFoldInstruction(I)) {
3896 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00003897 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00003898 ReplaceInstUsesWith(*I, C);
3899
Chris Lattner99f48c62002-09-02 04:59:56 +00003900 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003901 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00003902 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003903 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00003904 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003905
Chris Lattnerca081252001-12-14 16:52:21 +00003906 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003907 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00003908 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00003909 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00003910 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003911 DEBUG(std::cerr << "IC: Old = " << *I
3912 << " New = " << *Result);
3913
Chris Lattner396dbfe2004-06-09 05:08:07 +00003914 // Everything uses the new instruction now.
3915 I->replaceAllUsesWith(Result);
3916
3917 // Push the new instruction and any users onto the worklist.
3918 WorkList.push_back(Result);
3919 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003920
3921 // Move the name to the new instruction first...
3922 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00003923 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003924
3925 // Insert the new instruction into the basic block...
3926 BasicBlock *InstParent = I->getParent();
3927 InstParent->getInstList().insert(I, Result);
3928
Chris Lattner63d75af2004-05-01 23:27:23 +00003929 // Make sure that we reprocess all operands now that we reduced their
3930 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003931 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3932 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3933 WorkList.push_back(OpI);
3934
Chris Lattner396dbfe2004-06-09 05:08:07 +00003935 // Instructions can end up on the worklist more than once. Make sure
3936 // we do not process an instruction that has been deleted.
3937 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003938
3939 // Erase the old instruction.
3940 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003941 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003942 DEBUG(std::cerr << "IC: MOD = " << *I);
3943
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003944 // If the instruction was modified, it's possible that it is now dead.
3945 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00003946 if (isInstructionTriviallyDead(I)) {
3947 // Make sure we process all operands now that we are reducing their
3948 // use counts.
3949 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3950 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3951 WorkList.push_back(OpI);
3952
3953 // Instructions may end up in the worklist more than once. Erase all
3954 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00003955 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00003956 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00003957 } else {
3958 WorkList.push_back(Result);
3959 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003960 }
Chris Lattner053c0932002-05-14 15:24:07 +00003961 }
Chris Lattner260ab202002-04-18 17:39:14 +00003962 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00003963 }
3964 }
3965
Chris Lattner260ab202002-04-18 17:39:14 +00003966 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00003967}
3968
Brian Gaeke38b79e82004-07-27 17:43:21 +00003969FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00003970 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00003971}
Brian Gaeke960707c2003-11-11 22:41:34 +00003972