blob: 3f746a59ee345d48c7c3596a26172e1da7831bb0 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000032// N. This list is incomplete
33//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
46#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner60a65912002-02-12 21:07:25 +000047#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000049#include "llvm/Support/PatternMatch.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000050#include "llvm/Support/Debug.h"
51#include "llvm/ADT/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000052#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000053using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000054using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000055
Chris Lattner260ab202002-04-18 17:39:14 +000056namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000057 Statistic<> NumCombined ("instcombine", "Number of insts combined");
58 Statistic<> NumConstProp("instcombine", "Number of constant folds");
59 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
60
Chris Lattnerc8e66542002-04-27 06:56:12 +000061 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000062 public InstVisitor<InstCombiner, Instruction*> {
63 // Worklist of all of the instructions that need to be simplified.
64 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000065 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000066
Chris Lattner51ea1272004-02-28 05:22:00 +000067 /// AddUsersToWorkList - When an instruction is simplified, add all users of
68 /// the instruction to the work lists because they might get more simplified
69 /// now.
70 ///
71 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000072 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000073 UI != UE; ++UI)
74 WorkList.push_back(cast<Instruction>(*UI));
75 }
76
Chris Lattner51ea1272004-02-28 05:22:00 +000077 /// AddUsesToWorkList - When an instruction is simplified, add operands to
78 /// the work lists because they might get more simplified now.
79 ///
80 void AddUsesToWorkList(Instruction &I) {
81 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
82 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
83 WorkList.push_back(Op);
84 }
85
Chris Lattner99f48c62002-09-02 04:59:56 +000086 // removeFromWorkList - remove all instances of I from the worklist.
87 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000088 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000089 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000090
Chris Lattnerf12cc842002-04-28 21:27:06 +000091 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000092 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000093 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000094 }
95
Chris Lattner69193f92004-04-05 01:30:19 +000096 TargetData &getTargetData() const { return *TD; }
97
Chris Lattner260ab202002-04-18 17:39:14 +000098 // Visitation implementation - Implement instruction combining for different
99 // instruction types. The semantics are as follows:
100 // Return Value:
101 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000102 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000103 // otherwise - Change was made, replace I with returned instruction
104 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000105 Instruction *visitAdd(BinaryOperator &I);
106 Instruction *visitSub(BinaryOperator &I);
107 Instruction *visitMul(BinaryOperator &I);
108 Instruction *visitDiv(BinaryOperator &I);
109 Instruction *visitRem(BinaryOperator &I);
110 Instruction *visitAnd(BinaryOperator &I);
111 Instruction *visitOr (BinaryOperator &I);
112 Instruction *visitXor(BinaryOperator &I);
113 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000114 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000115 Instruction *visitCastInst(CastInst &CI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000116 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000117 Instruction *visitCallInst(CallInst &CI);
118 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000119 Instruction *visitPHINode(PHINode &PN);
120 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000121 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000122 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000123 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000124 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000125 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000126
127 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000128 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000129
Chris Lattner970c33a2003-06-19 17:00:31 +0000130 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000131 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000132 bool transformConstExprCastCall(CallSite CS);
133
Chris Lattner69193f92004-04-05 01:30:19 +0000134 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000135 // InsertNewInstBefore - insert an instruction New before instruction Old
136 // in the program. Add the new instruction to the worklist.
137 //
Chris Lattner623826c2004-09-28 21:48:02 +0000138 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000139 assert(New && New->getParent() == 0 &&
140 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000141 BasicBlock *BB = Old.getParent();
142 BB->getInstList().insert(&Old, New); // Insert inst
143 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000144 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000145 }
146
Chris Lattner7e794272004-09-24 15:21:34 +0000147 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
148 /// This also adds the cast to the worklist. Finally, this returns the
149 /// cast.
150 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
151 if (V->getType() == Ty) return V;
152
153 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
154 WorkList.push_back(C);
155 return C;
156 }
157
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000158 // ReplaceInstUsesWith - This method is to be used when an instruction is
159 // found to be dead, replacable with another preexisting expression. Here
160 // we add all uses of I to the worklist, replace all uses of I with the new
161 // value, then return I, so that the inst combiner will know that I was
162 // modified.
163 //
164 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000165 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000166 if (&I != V) {
167 I.replaceAllUsesWith(V);
168 return &I;
169 } else {
170 // If we are replacing the instruction with itself, this must be in a
171 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000172 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000173 return &I;
174 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000175 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000176
177 // EraseInstFromFunction - When dealing with an instruction that has side
178 // effects or produces a void value, we can't rely on DCE to delete the
179 // instruction. Instead, visit methods should return the value returned by
180 // this function.
181 Instruction *EraseInstFromFunction(Instruction &I) {
182 assert(I.use_empty() && "Cannot erase instruction that is used!");
183 AddUsesToWorkList(I);
184 removeFromWorkList(&I);
185 I.getParent()->getInstList().erase(&I);
186 return 0; // Don't do anything with FI
187 }
188
189
Chris Lattner3ac7c262003-08-13 20:16:26 +0000190 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000191 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
192 /// InsertBefore instruction. This is specialized a bit to avoid inserting
193 /// casts that are known to not do anything...
194 ///
195 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
196 Instruction *InsertBefore);
197
Chris Lattner7fb29e12003-03-11 00:12:48 +0000198 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000199 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000200 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000201
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000202
203 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
204 // PHI node as operand #0, see if we can fold the instruction into the PHI
205 // (which is only possible if all operands to the PHI are constants).
206 Instruction *FoldOpIntoPhi(Instruction &I);
207
Chris Lattnerba1cb382003-09-19 17:17:26 +0000208 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
209 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000210
211 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
212 bool Inside, Instruction &IB);
Chris Lattner260ab202002-04-18 17:39:14 +0000213 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000214
Chris Lattnerc8b70922002-07-26 21:12:46 +0000215 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000216}
217
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000218// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000219// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000220static unsigned getComplexity(Value *V) {
221 if (isa<Instruction>(V)) {
222 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000223 return 3;
224 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000225 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000226 if (isa<Argument>(V)) return 3;
227 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000228}
Chris Lattner260ab202002-04-18 17:39:14 +0000229
Chris Lattner7fb29e12003-03-11 00:12:48 +0000230// isOnlyUse - Return true if this instruction will be deleted if we stop using
231// it.
232static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000233 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000234}
235
Chris Lattnere79e8542004-02-23 06:38:22 +0000236// getPromotedType - Return the specified type promoted as it would be to pass
237// though a va_arg area...
238static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000239 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000240 case Type::SByteTyID:
241 case Type::ShortTyID: return Type::IntTy;
242 case Type::UByteTyID:
243 case Type::UShortTyID: return Type::UIntTy;
244 case Type::FloatTyID: return Type::DoubleTy;
245 default: return Ty;
246 }
247}
248
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000249// SimplifyCommutative - This performs a few simplifications for commutative
250// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000251//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000252// 1. Order operands such that they are listed from right (least complex) to
253// left (most complex). This puts constants before unary operators before
254// binary operators.
255//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000256// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
257// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000258//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000259bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000260 bool Changed = false;
261 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
262 Changed = !I.swapOperands();
263
264 if (!I.isAssociative()) return Changed;
265 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000266 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
267 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
268 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000269 Constant *Folded = ConstantExpr::get(I.getOpcode(),
270 cast<Constant>(I.getOperand(1)),
271 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000272 I.setOperand(0, Op->getOperand(0));
273 I.setOperand(1, Folded);
274 return true;
275 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
276 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
277 isOnlyUse(Op) && isOnlyUse(Op1)) {
278 Constant *C1 = cast<Constant>(Op->getOperand(1));
279 Constant *C2 = cast<Constant>(Op1->getOperand(1));
280
281 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000282 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000283 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
284 Op1->getOperand(0),
285 Op1->getName(), &I);
286 WorkList.push_back(New);
287 I.setOperand(0, New);
288 I.setOperand(1, Folded);
289 return true;
290 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000291 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000292 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000293}
Chris Lattnerca081252001-12-14 16:52:21 +0000294
Chris Lattnerbb74e222003-03-10 23:06:50 +0000295// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
296// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000297//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000298static inline Value *dyn_castNegVal(Value *V) {
299 if (BinaryOperator::isNeg(V))
300 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
301
Chris Lattner9244df62003-04-30 22:19:10 +0000302 // Constants can be considered to be negated values if they can be folded...
303 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000304 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000305 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000306}
307
Chris Lattnerbb74e222003-03-10 23:06:50 +0000308static inline Value *dyn_castNotVal(Value *V) {
309 if (BinaryOperator::isNot(V))
310 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
311
312 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000313 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000314 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000315 return 0;
316}
317
Chris Lattner7fb29e12003-03-11 00:12:48 +0000318// dyn_castFoldableMul - If this value is a multiply that can be folded into
319// other computations (because it has a constant operand), return the
320// non-constant operand of the multiply.
321//
322static inline Value *dyn_castFoldableMul(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000323 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000324 if (Instruction *I = dyn_cast<Instruction>(V))
325 if (I->getOpcode() == Instruction::Mul)
326 if (isa<Constant>(I->getOperand(1)))
327 return I->getOperand(0);
328 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000329}
Chris Lattner31ae8632002-08-14 17:51:49 +0000330
Chris Lattner3082c5a2003-02-18 19:28:33 +0000331// Log2 - Calculate the log base 2 for the specified value if it is exactly a
332// power of 2.
333static unsigned Log2(uint64_t Val) {
334 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
335 unsigned Count = 0;
336 while (Val != 1) {
337 if (Val & 1) return 0; // Multiple bits set?
338 Val >>= 1;
339 ++Count;
340 }
341 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000342}
343
Chris Lattner623826c2004-09-28 21:48:02 +0000344// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000345static ConstantInt *AddOne(ConstantInt *C) {
346 return cast<ConstantInt>(ConstantExpr::getAdd(C,
347 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000348}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000349static ConstantInt *SubOne(ConstantInt *C) {
350 return cast<ConstantInt>(ConstantExpr::getSub(C,
351 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000352}
353
354// isTrueWhenEqual - Return true if the specified setcondinst instruction is
355// true when both operands are equal...
356//
357static bool isTrueWhenEqual(Instruction &I) {
358 return I.getOpcode() == Instruction::SetEQ ||
359 I.getOpcode() == Instruction::SetGE ||
360 I.getOpcode() == Instruction::SetLE;
361}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000362
363/// AssociativeOpt - Perform an optimization on an associative operator. This
364/// function is designed to check a chain of associative operators for a
365/// potential to apply a certain optimization. Since the optimization may be
366/// applicable if the expression was reassociated, this checks the chain, then
367/// reassociates the expression as necessary to expose the optimization
368/// opportunity. This makes use of a special Functor, which must define
369/// 'shouldApply' and 'apply' methods.
370///
371template<typename Functor>
372Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
373 unsigned Opcode = Root.getOpcode();
374 Value *LHS = Root.getOperand(0);
375
376 // Quick check, see if the immediate LHS matches...
377 if (F.shouldApply(LHS))
378 return F.apply(Root);
379
380 // Otherwise, if the LHS is not of the same opcode as the root, return.
381 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000382 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000383 // Should we apply this transform to the RHS?
384 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
385
386 // If not to the RHS, check to see if we should apply to the LHS...
387 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
388 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
389 ShouldApply = true;
390 }
391
392 // If the functor wants to apply the optimization to the RHS of LHSI,
393 // reassociate the expression from ((? op A) op B) to (? op (A op B))
394 if (ShouldApply) {
395 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000396
397 // Now all of the instructions are in the current basic block, go ahead
398 // and perform the reassociation.
399 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
400
401 // First move the selected RHS to the LHS of the root...
402 Root.setOperand(0, LHSI->getOperand(1));
403
404 // Make what used to be the LHS of the root be the user of the root...
405 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000406 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000407 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
408 return 0;
409 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000410 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000411 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000412 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
413 BasicBlock::iterator ARI = &Root; ++ARI;
414 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
415 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000416
417 // Now propagate the ExtraOperand down the chain of instructions until we
418 // get to LHSI.
419 while (TmpLHSI != LHSI) {
420 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000421 // Move the instruction to immediately before the chain we are
422 // constructing to avoid breaking dominance properties.
423 NextLHSI->getParent()->getInstList().remove(NextLHSI);
424 BB->getInstList().insert(ARI, NextLHSI);
425 ARI = NextLHSI;
426
Chris Lattnerb8b97502003-08-13 19:01:45 +0000427 Value *NextOp = NextLHSI->getOperand(1);
428 NextLHSI->setOperand(1, ExtraOperand);
429 TmpLHSI = NextLHSI;
430 ExtraOperand = NextOp;
431 }
432
433 // Now that the instructions are reassociated, have the functor perform
434 // the transformation...
435 return F.apply(Root);
436 }
437
438 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
439 }
440 return 0;
441}
442
443
444// AddRHS - Implements: X + X --> X << 1
445struct AddRHS {
446 Value *RHS;
447 AddRHS(Value *rhs) : RHS(rhs) {}
448 bool shouldApply(Value *LHS) const { return LHS == RHS; }
449 Instruction *apply(BinaryOperator &Add) const {
450 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
451 ConstantInt::get(Type::UByteTy, 1));
452 }
453};
454
455// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
456// iff C1&C2 == 0
457struct AddMaskingAnd {
458 Constant *C2;
459 AddMaskingAnd(Constant *c) : C2(c) {}
460 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000461 ConstantInt *C1;
462 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
463 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000464 }
465 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000466 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000467 }
468};
469
Chris Lattner183b3362004-04-09 19:05:30 +0000470static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
471 InstCombiner *IC) {
472 // Figure out if the constant is the left or the right argument.
473 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
474 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000475
Chris Lattner183b3362004-04-09 19:05:30 +0000476 if (Constant *SOC = dyn_cast<Constant>(SO)) {
477 if (ConstIsRHS)
478 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
479 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
480 }
481
482 Value *Op0 = SO, *Op1 = ConstOperand;
483 if (!ConstIsRHS)
484 std::swap(Op0, Op1);
485 Instruction *New;
486 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
487 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
488 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
489 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattnerf9d96652004-04-10 19:15:56 +0000490 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000491 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000492 abort();
493 }
Chris Lattner183b3362004-04-09 19:05:30 +0000494 return IC->InsertNewInstBefore(New, BI);
495}
496
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000497
498/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
499/// node as operand #0, see if we can fold the instruction into the PHI (which
500/// is only possible if all operands to the PHI are constants).
501Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
502 PHINode *PN = cast<PHINode>(I.getOperand(0));
503 if (!PN->hasOneUse()) return 0;
504
505 // Check to see if all of the operands of the PHI are constants. If not, we
506 // cannot do the transformation.
507 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
508 if (!isa<Constant>(PN->getIncomingValue(i)))
509 return 0;
510
511 // Okay, we can do the transformation: create the new PHI node.
512 PHINode *NewPN = new PHINode(I.getType(), I.getName());
513 I.setName("");
514 NewPN->op_reserve(PN->getNumOperands());
515 InsertNewInstBefore(NewPN, *PN);
516
517 // Next, add all of the operands to the PHI.
518 if (I.getNumOperands() == 2) {
519 Constant *C = cast<Constant>(I.getOperand(1));
520 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
521 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
522 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
523 PN->getIncomingBlock(i));
524 }
525 } else {
526 assert(isa<CastInst>(I) && "Unary op should be a cast!");
527 const Type *RetTy = I.getType();
528 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
529 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
530 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
531 PN->getIncomingBlock(i));
532 }
533 }
534 return ReplaceInstUsesWith(I, NewPN);
535}
536
Chris Lattner183b3362004-04-09 19:05:30 +0000537// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
538// constant as the other operand, try to fold the binary operator into the
539// select arguments.
540static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
541 InstCombiner *IC) {
542 // Don't modify shared select instructions
543 if (!SI->hasOneUse()) return 0;
544 Value *TV = SI->getOperand(1);
545 Value *FV = SI->getOperand(2);
546
547 if (isa<Constant>(TV) || isa<Constant>(FV)) {
548 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
549 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
550
551 return new SelectInst(SI->getCondition(), SelectTrueVal,
552 SelectFalseVal);
553 }
554 return 0;
555}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000556
Chris Lattner113f4f42002-06-25 16:13:24 +0000557Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000558 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000559 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000560
Chris Lattnercf4a9962004-04-10 22:01:55 +0000561 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000562 // X + undef -> undef
563 if (isa<UndefValue>(RHS))
564 return ReplaceInstUsesWith(I, RHS);
565
Chris Lattnercf4a9962004-04-10 22:01:55 +0000566 // X + 0 --> X
567 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
568 RHSC->isNullValue())
569 return ReplaceInstUsesWith(I, LHS);
570
571 // X + (signbit) --> X ^ signbit
572 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
573 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
574 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattner33eb9092004-11-05 04:45:43 +0000575 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000576 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000577 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000578
579 if (isa<PHINode>(LHS))
580 if (Instruction *NV = FoldOpIntoPhi(I))
581 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000582 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000583
Chris Lattnerb8b97502003-08-13 19:01:45 +0000584 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000585 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000586 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000587 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000588
Chris Lattner147e9752002-05-08 22:46:53 +0000589 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000590 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000591 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000592
593 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000594 if (!isa<Constant>(RHS))
595 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000596 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000597
Chris Lattner57c8d992003-02-18 19:57:07 +0000598 // X*C + X --> X * (C+1)
599 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000600 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000601 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000602 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
603 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000604 return BinaryOperator::createMul(RHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000605 }
606
607 // X + X*C --> X * (C+1)
608 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000609 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000610 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000611 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
612 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000613 return BinaryOperator::createMul(LHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000614 }
615
Chris Lattnerb8b97502003-08-13 19:01:45 +0000616 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000617 ConstantInt *C2;
618 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000619 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000620
Chris Lattner4efe20a2004-11-13 19:31:40 +0000621 // (X + (X << C2)) --> X * ((1 << C2) + 1)
622 // ((X << C2) + X) --> X * ((1 << C2) + 1)
623 Value *Tmp;
624 if ((RHS->hasOneUse() && match(RHS, m_Shl(m_Value(Tmp),
625 m_ConstantInt(C2))) && LHS == Tmp)||
626 (LHS->hasOneUse() && match(LHS, m_Shl(m_Value(Tmp),
627 m_ConstantInt(C2))) && RHS == Tmp)){
628 ConstantInt *One = ConstantInt::get(LHS->getType(), 1);
629 Constant *NewRHS =
630 ConstantExpr::getAdd(ConstantExpr::getShl(One, C2), One);
631 return BinaryOperator::createMul(Tmp, NewRHS);
632 }
633
Chris Lattnerb9cde762003-10-02 15:11:26 +0000634 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000635 Value *X;
636 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
637 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
638 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000639 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000640
Chris Lattnerbff91d92004-10-08 05:07:56 +0000641 // (X & FF00) + xx00 -> (X+xx00) & FF00
642 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
643 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
644 if (Anded == CRHS) {
645 // See if all bits from the first bit set in the Add RHS up are included
646 // in the mask. First, get the rightmost bit.
647 uint64_t AddRHSV = CRHS->getRawValue();
648
649 // Form a mask of all bits from the lowest bit added through the top.
650 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
651 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
652
653 // See if the and mask includes all of these bits.
654 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
655
656 if (AddRHSHighBits == AddRHSHighBitsAnd) {
657 // Okay, the xform is safe. Insert the new add pronto.
658 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
659 LHS->getName()), I);
660 return BinaryOperator::createAnd(NewAdd, C2);
661 }
662 }
663 }
664
665
Chris Lattnerd4252a72004-07-30 07:50:03 +0000666 // Try to fold constant add into select arguments.
667 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
668 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
669 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000670 }
671
Chris Lattner113f4f42002-06-25 16:13:24 +0000672 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000673}
674
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000675// isSignBit - Return true if the value represented by the constant only has the
676// highest order bit set.
677static bool isSignBit(ConstantInt *CI) {
678 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
679 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
680}
681
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000682static unsigned getTypeSizeInBits(const Type *Ty) {
683 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
684}
685
Chris Lattner022167f2004-03-13 00:11:49 +0000686/// RemoveNoopCast - Strip off nonconverting casts from the value.
687///
688static Value *RemoveNoopCast(Value *V) {
689 if (CastInst *CI = dyn_cast<CastInst>(V)) {
690 const Type *CTy = CI->getType();
691 const Type *OpTy = CI->getOperand(0)->getType();
692 if (CTy->isInteger() && OpTy->isInteger()) {
693 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
694 return RemoveNoopCast(CI->getOperand(0));
695 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
696 return RemoveNoopCast(CI->getOperand(0));
697 }
698 return V;
699}
700
Chris Lattner113f4f42002-06-25 16:13:24 +0000701Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000702 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000703
Chris Lattnere6794492002-08-12 21:17:25 +0000704 if (Op0 == Op1) // sub X, X -> 0
705 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000706
Chris Lattnere6794492002-08-12 21:17:25 +0000707 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000708 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000709 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000710
Chris Lattner81a7a232004-10-16 18:11:37 +0000711 if (isa<UndefValue>(Op0))
712 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
713 if (isa<UndefValue>(Op1))
714 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
715
Chris Lattner8f2f5982003-11-05 01:06:05 +0000716 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
717 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000718 if (C->isAllOnesValue())
719 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000720
Chris Lattner8f2f5982003-11-05 01:06:05 +0000721 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000722 Value *X;
723 if (match(Op1, m_Not(m_Value(X))))
724 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000725 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000726 // -((uint)X >> 31) -> ((int)X >> 31)
727 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000728 if (C->isNullValue()) {
729 Value *NoopCastedRHS = RemoveNoopCast(Op1);
730 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000731 if (SI->getOpcode() == Instruction::Shr)
732 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
733 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000734 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000735 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000736 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000737 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000738 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000739 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000740 // Ok, the transformation is safe. Insert a cast of the incoming
741 // value, then the new shift, then the new cast.
742 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
743 SI->getOperand(0)->getName());
744 Value *InV = InsertNewInstBefore(FirstCast, I);
745 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
746 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000747 if (NewShift->getType() == I.getType())
748 return NewShift;
749 else {
750 InV = InsertNewInstBefore(NewShift, I);
751 return new CastInst(NewShift, I.getType());
752 }
Chris Lattner92295c52004-03-12 23:53:13 +0000753 }
754 }
Chris Lattner022167f2004-03-13 00:11:49 +0000755 }
Chris Lattner183b3362004-04-09 19:05:30 +0000756
757 // Try to fold constant sub into select arguments.
758 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
759 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
760 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000761
762 if (isa<PHINode>(Op0))
763 if (Instruction *NV = FoldOpIntoPhi(I))
764 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000765 }
766
Chris Lattner3082c5a2003-02-18 19:28:33 +0000767 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000768 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000769 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
770 // is not used by anyone else...
771 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000772 if (Op1I->getOpcode() == Instruction::Sub &&
773 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000774 // Swap the two operands of the subexpr...
775 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
776 Op1I->setOperand(0, IIOp1);
777 Op1I->setOperand(1, IIOp0);
778
779 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000780 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000781 }
782
783 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
784 //
785 if (Op1I->getOpcode() == Instruction::And &&
786 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
787 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
788
Chris Lattner396dbfe2004-06-09 05:08:07 +0000789 Value *NewNot =
790 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000791 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000792 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000793
Chris Lattner0aee4b72004-10-06 15:08:25 +0000794 // -(X sdiv C) -> (X sdiv -C)
795 if (Op1I->getOpcode() == Instruction::Div)
796 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
797 if (CSI->getValue() == 0)
798 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
799 return BinaryOperator::createDiv(Op1I->getOperand(0),
800 ConstantExpr::getNeg(DivRHS));
801
Chris Lattner57c8d992003-02-18 19:57:07 +0000802 // X - X*C --> X * (1-C)
803 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000804 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000805 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner34428442003-05-27 16:40:51 +0000806 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000807 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000808 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000809 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000810 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000811
Chris Lattner57c8d992003-02-18 19:57:07 +0000812 // X*C - X --> X * (C-1)
813 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000814 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000815 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner34428442003-05-27 16:40:51 +0000816 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000817 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000818 return BinaryOperator::createMul(Op1, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000819 }
820
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000821 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000822}
823
Chris Lattnere79e8542004-02-23 06:38:22 +0000824/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
825/// really just returns true if the most significant (sign) bit is set.
826static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
827 if (RHS->getType()->isSigned()) {
828 // True if source is LHS < 0 or LHS <= -1
829 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
830 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
831 } else {
832 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
833 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
834 // the size of the integer type.
835 if (Opcode == Instruction::SetGE)
836 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
837 if (Opcode == Instruction::SetGT)
838 return RHSC->getValue() ==
839 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
840 }
841 return false;
842}
843
Chris Lattner113f4f42002-06-25 16:13:24 +0000844Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000845 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000846 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000847
Chris Lattner81a7a232004-10-16 18:11:37 +0000848 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
849 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
850
Chris Lattnere6794492002-08-12 21:17:25 +0000851 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000852 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
853 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000854
855 // ((X << C1)*C2) == (X * (C2 << C1))
856 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
857 if (SI->getOpcode() == Instruction::Shl)
858 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000859 return BinaryOperator::createMul(SI->getOperand(0),
860 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000861
Chris Lattnercce81be2003-09-11 22:24:54 +0000862 if (CI->isNullValue())
863 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
864 if (CI->equalsInt(1)) // X * 1 == X
865 return ReplaceInstUsesWith(I, Op0);
866 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000867 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000868
Chris Lattnercce81be2003-09-11 22:24:54 +0000869 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000870 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
871 return new ShiftInst(Instruction::Shl, Op0,
872 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000873 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000874 if (Op1F->isNullValue())
875 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000876
Chris Lattner3082c5a2003-02-18 19:28:33 +0000877 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
878 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
879 if (Op1F->getValue() == 1.0)
880 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
881 }
Chris Lattner183b3362004-04-09 19:05:30 +0000882
883 // Try to fold constant mul into select arguments.
884 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
885 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
886 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000887
888 if (isa<PHINode>(Op0))
889 if (Instruction *NV = FoldOpIntoPhi(I))
890 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000891 }
892
Chris Lattner934a64cf2003-03-10 23:23:04 +0000893 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
894 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000895 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000896
Chris Lattner2635b522004-02-23 05:39:21 +0000897 // If one of the operands of the multiply is a cast from a boolean value, then
898 // we know the bool is either zero or one, so this is a 'masking' multiply.
899 // See if we can simplify things based on how the boolean was originally
900 // formed.
901 CastInst *BoolCast = 0;
902 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
903 if (CI->getOperand(0)->getType() == Type::BoolTy)
904 BoolCast = CI;
905 if (!BoolCast)
906 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
907 if (CI->getOperand(0)->getType() == Type::BoolTy)
908 BoolCast = CI;
909 if (BoolCast) {
910 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
911 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
912 const Type *SCOpTy = SCIOp0->getType();
913
Chris Lattnere79e8542004-02-23 06:38:22 +0000914 // If the setcc is true iff the sign bit of X is set, then convert this
915 // multiply into a shift/and combination.
916 if (isa<ConstantInt>(SCIOp1) &&
917 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000918 // Shift the X value right to turn it into "all signbits".
919 Constant *Amt = ConstantUInt::get(Type::UByteTy,
920 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000921 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000922 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000923 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
924 SCIOp0->getName()), I);
925 }
926
927 Value *V =
928 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
929 BoolCast->getOperand(0)->getName()+
930 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000931
932 // If the multiply type is not the same as the source type, sign extend
933 // or truncate to the multiply type.
934 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000935 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000936
937 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000938 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000939 }
940 }
941 }
942
Chris Lattner113f4f42002-06-25 16:13:24 +0000943 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000944}
945
Chris Lattner113f4f42002-06-25 16:13:24 +0000946Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000947 if (isa<UndefValue>(I.getOperand(0))) // undef / X -> 0
948 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
949 if (isa<UndefValue>(I.getOperand(1)))
950 return ReplaceInstUsesWith(I, I.getOperand(1)); // X / undef -> undef
951
Chris Lattner3082c5a2003-02-18 19:28:33 +0000952 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000953 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000954 if (RHS->equalsInt(1))
955 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000956
Chris Lattnere20c3342004-04-26 14:01:59 +0000957 // div X, -1 == -X
958 if (RHS->isAllOnesValue())
959 return BinaryOperator::createNeg(I.getOperand(0));
960
Chris Lattner272d5ca2004-09-28 18:22:15 +0000961 if (Instruction *LHS = dyn_cast<Instruction>(I.getOperand(0)))
962 if (LHS->getOpcode() == Instruction::Div)
963 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +0000964 // (X / C1) / C2 -> X / (C1*C2)
965 return BinaryOperator::createDiv(LHS->getOperand(0),
966 ConstantExpr::getMul(RHS, LHSRHS));
967 }
968
Chris Lattner3082c5a2003-02-18 19:28:33 +0000969 // Check to see if this is an unsigned division with an exact power of 2,
970 // if so, convert to a right shift.
971 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
972 if (uint64_t Val = C->getValue()) // Don't break X / 0
973 if (uint64_t C = Log2(Val))
974 return new ShiftInst(Instruction::Shr, I.getOperand(0),
975 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000976
Chris Lattner4ad08352004-10-09 02:50:40 +0000977 // -X/C -> X/-C
978 if (RHS->getType()->isSigned())
979 if (Value *LHSNeg = dyn_castNegVal(I.getOperand(0)))
980 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
981
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000982 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
983 if (Instruction *NV = FoldOpIntoPhi(I))
984 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000985 }
986
987 // 0 / X == 0, we don't need to preserve faults!
988 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
989 if (LHS->equalsInt(0))
990 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
991
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000992 return 0;
993}
994
995
Chris Lattner113f4f42002-06-25 16:13:24 +0000996Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000997 if (I.getType()->isSigned())
998 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner98c6bdf2004-07-06 07:11:42 +0000999 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001000 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001001 // X % -Y -> X % Y
1002 AddUsesToWorkList(I);
1003 I.setOperand(1, RHSNeg);
1004 return &I;
1005 }
1006
Chris Lattner81a7a232004-10-16 18:11:37 +00001007 if (isa<UndefValue>(I.getOperand(0))) // undef % X -> 0
1008 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1009 if (isa<UndefValue>(I.getOperand(1)))
1010 return ReplaceInstUsesWith(I, I.getOperand(1)); // X % undef -> undef
1011
Chris Lattner3082c5a2003-02-18 19:28:33 +00001012 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
1013 if (RHS->equalsInt(1)) // X % 1 == 0
1014 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1015
1016 // Check to see if this is an unsigned remainder with an exact power of 2,
1017 // if so, convert to a bitwise and.
1018 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1019 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001020 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001021 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattner3082c5a2003-02-18 19:28:33 +00001022 ConstantUInt::get(I.getType(), Val-1));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001023 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
1024 if (Instruction *NV = FoldOpIntoPhi(I))
1025 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +00001026 }
1027
1028 // 0 % X == 0, we don't need to preserve faults!
1029 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
1030 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001031 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1032
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001033 return 0;
1034}
1035
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001036// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001037static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001038 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1039 // Calculate -1 casted to the right type...
1040 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1041 uint64_t Val = ~0ULL; // All ones
1042 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1043 return CU->getValue() == Val-1;
1044 }
1045
1046 const ConstantSInt *CS = cast<ConstantSInt>(C);
1047
1048 // Calculate 0111111111..11111
1049 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1050 int64_t Val = INT64_MAX; // All ones
1051 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1052 return CS->getValue() == Val-1;
1053}
1054
1055// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001056static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001057 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1058 return CU->getValue() == 1;
1059
1060 const ConstantSInt *CS = cast<ConstantSInt>(C);
1061
1062 // Calculate 1111111111000000000000
1063 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1064 int64_t Val = -1; // All ones
1065 Val <<= TypeBits-1; // Shift over to the right spot
1066 return CS->getValue() == Val+1;
1067}
1068
Chris Lattner35167c32004-06-09 07:59:58 +00001069// isOneBitSet - Return true if there is exactly one bit set in the specified
1070// constant.
1071static bool isOneBitSet(const ConstantInt *CI) {
1072 uint64_t V = CI->getRawValue();
1073 return V && (V & (V-1)) == 0;
1074}
1075
Chris Lattner8fc5af42004-09-23 21:46:38 +00001076#if 0 // Currently unused
1077// isLowOnes - Return true if the constant is of the form 0+1+.
1078static bool isLowOnes(const ConstantInt *CI) {
1079 uint64_t V = CI->getRawValue();
1080
1081 // There won't be bits set in parts that the type doesn't contain.
1082 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1083
1084 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1085 return U && V && (U & V) == 0;
1086}
1087#endif
1088
1089// isHighOnes - Return true if the constant is of the form 1+0+.
1090// This is the same as lowones(~X).
1091static bool isHighOnes(const ConstantInt *CI) {
1092 uint64_t V = ~CI->getRawValue();
1093
1094 // There won't be bits set in parts that the type doesn't contain.
1095 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1096
1097 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1098 return U && V && (U & V) == 0;
1099}
1100
1101
Chris Lattner3ac7c262003-08-13 20:16:26 +00001102/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1103/// are carefully arranged to allow folding of expressions such as:
1104///
1105/// (A < B) | (A > B) --> (A != B)
1106///
1107/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1108/// represents that the comparison is true if A == B, and bit value '1' is true
1109/// if A < B.
1110///
1111static unsigned getSetCondCode(const SetCondInst *SCI) {
1112 switch (SCI->getOpcode()) {
1113 // False -> 0
1114 case Instruction::SetGT: return 1;
1115 case Instruction::SetEQ: return 2;
1116 case Instruction::SetGE: return 3;
1117 case Instruction::SetLT: return 4;
1118 case Instruction::SetNE: return 5;
1119 case Instruction::SetLE: return 6;
1120 // True -> 7
1121 default:
1122 assert(0 && "Invalid SetCC opcode!");
1123 return 0;
1124 }
1125}
1126
1127/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1128/// opcode and two operands into either a constant true or false, or a brand new
1129/// SetCC instruction.
1130static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1131 switch (Opcode) {
1132 case 0: return ConstantBool::False;
1133 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1134 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1135 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1136 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1137 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1138 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1139 case 7: return ConstantBool::True;
1140 default: assert(0 && "Illegal SetCCCode!"); return 0;
1141 }
1142}
1143
1144// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1145struct FoldSetCCLogical {
1146 InstCombiner &IC;
1147 Value *LHS, *RHS;
1148 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1149 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1150 bool shouldApply(Value *V) const {
1151 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1152 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1153 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1154 return false;
1155 }
1156 Instruction *apply(BinaryOperator &Log) const {
1157 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1158 if (SCI->getOperand(0) != LHS) {
1159 assert(SCI->getOperand(1) == LHS);
1160 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1161 }
1162
1163 unsigned LHSCode = getSetCondCode(SCI);
1164 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1165 unsigned Code;
1166 switch (Log.getOpcode()) {
1167 case Instruction::And: Code = LHSCode & RHSCode; break;
1168 case Instruction::Or: Code = LHSCode | RHSCode; break;
1169 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001170 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001171 }
1172
1173 Value *RV = getSetCCValue(Code, LHS, RHS);
1174 if (Instruction *I = dyn_cast<Instruction>(RV))
1175 return I;
1176 // Otherwise, it's a constant boolean value...
1177 return IC.ReplaceInstUsesWith(Log, RV);
1178 }
1179};
1180
1181
Chris Lattnerba1cb382003-09-19 17:17:26 +00001182// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1183// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1184// guaranteed to be either a shift instruction or a binary operator.
1185Instruction *InstCombiner::OptAndOp(Instruction *Op,
1186 ConstantIntegral *OpRHS,
1187 ConstantIntegral *AndRHS,
1188 BinaryOperator &TheAnd) {
1189 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001190 Constant *Together = 0;
1191 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001192 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001193
Chris Lattnerba1cb382003-09-19 17:17:26 +00001194 switch (Op->getOpcode()) {
1195 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001196 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001197 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001198 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001199 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001200 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1201 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001202 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001203 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001204 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001205 }
1206 break;
1207 case Instruction::Or:
1208 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001209 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001210 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001211 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001212 if (Together == AndRHS) // (X | C) & C --> C
1213 return ReplaceInstUsesWith(TheAnd, AndRHS);
1214
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001215 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001216 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1217 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001218 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001219 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001220 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001221 }
1222 }
1223 break;
1224 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001225 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001226 // Adding a one to a single bit bit-field should be turned into an XOR
1227 // of the bit. First thing to check is to see if this AND is with a
1228 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001229 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001230
1231 // Clear bits that are not part of the constant.
1232 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1233
1234 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001235 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001236 // Ok, at this point, we know that we are masking the result of the
1237 // ADD down to exactly one bit. If the constant we are adding has
1238 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001239 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001240
1241 // Check to see if any bits below the one bit set in AndRHSV are set.
1242 if ((AddRHS & (AndRHSV-1)) == 0) {
1243 // If not, the only thing that can effect the output of the AND is
1244 // the bit specified by AndRHSV. If that bit is set, the effect of
1245 // the XOR is to toggle the bit. If it is clear, then the ADD has
1246 // no effect.
1247 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1248 TheAnd.setOperand(0, X);
1249 return &TheAnd;
1250 } else {
1251 std::string Name = Op->getName(); Op->setName("");
1252 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001253 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001254 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001255 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001256 }
1257 }
1258 }
1259 }
1260 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001261
1262 case Instruction::Shl: {
1263 // We know that the AND will not produce any of the bits shifted in, so if
1264 // the anded constant includes them, clear them now!
1265 //
1266 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001267 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1268 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1269
1270 if (CI == ShlMask) { // Masking out bits that the shift already masks
1271 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1272 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001273 TheAnd.setOperand(1, CI);
1274 return &TheAnd;
1275 }
1276 break;
1277 }
1278 case Instruction::Shr:
1279 // We know that the AND will not produce any of the bits shifted in, so if
1280 // the anded constant includes them, clear them now! This only applies to
1281 // unsigned shifts, because a signed shr may bring in set bits!
1282 //
1283 if (AndRHS->getType()->isUnsigned()) {
1284 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001285 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1286 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1287
1288 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1289 return ReplaceInstUsesWith(TheAnd, Op);
1290 } else if (CI != AndRHS) {
1291 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001292 return &TheAnd;
1293 }
Chris Lattner7e794272004-09-24 15:21:34 +00001294 } else { // Signed shr.
1295 // See if this is shifting in some sign extension, then masking it out
1296 // with an and.
1297 if (Op->hasOneUse()) {
1298 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1299 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1300 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001301 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001302 // Make the argument unsigned.
1303 Value *ShVal = Op->getOperand(0);
1304 ShVal = InsertCastBefore(ShVal,
1305 ShVal->getType()->getUnsignedVersion(),
1306 TheAnd);
1307 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1308 OpRHS, Op->getName()),
1309 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001310 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1311 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1312 TheAnd.getName()),
1313 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001314 return new CastInst(ShVal, Op->getType());
1315 }
1316 }
Chris Lattner2da29172003-09-19 19:05:02 +00001317 }
1318 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001319 }
1320 return 0;
1321}
1322
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001323
Chris Lattner6862fbd2004-09-29 17:40:11 +00001324/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1325/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1326/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1327/// insert new instructions.
1328Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1329 bool Inside, Instruction &IB) {
1330 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1331 "Lo is not <= Hi in range emission code!");
1332 if (Inside) {
1333 if (Lo == Hi) // Trivially false.
1334 return new SetCondInst(Instruction::SetNE, V, V);
1335 if (cast<ConstantIntegral>(Lo)->isMinValue())
1336 return new SetCondInst(Instruction::SetLT, V, Hi);
1337
1338 Constant *AddCST = ConstantExpr::getNeg(Lo);
1339 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1340 InsertNewInstBefore(Add, IB);
1341 // Convert to unsigned for the comparison.
1342 const Type *UnsType = Add->getType()->getUnsignedVersion();
1343 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1344 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1345 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1346 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1347 }
1348
1349 if (Lo == Hi) // Trivially true.
1350 return new SetCondInst(Instruction::SetEQ, V, V);
1351
1352 Hi = SubOne(cast<ConstantInt>(Hi));
1353 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1354 return new SetCondInst(Instruction::SetGT, V, Hi);
1355
1356 // Emit X-Lo > Hi-Lo-1
1357 Constant *AddCST = ConstantExpr::getNeg(Lo);
1358 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1359 InsertNewInstBefore(Add, IB);
1360 // Convert to unsigned for the comparison.
1361 const Type *UnsType = Add->getType()->getUnsignedVersion();
1362 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1363 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1364 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1365 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1366}
1367
1368
Chris Lattner113f4f42002-06-25 16:13:24 +00001369Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001370 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001371 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001372
Chris Lattner81a7a232004-10-16 18:11:37 +00001373 if (isa<UndefValue>(Op1)) // X & undef -> 0
1374 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1375
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001376 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001377 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1378 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001379
1380 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001381 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001382 if (RHS->isAllOnesValue())
1383 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001384
Chris Lattnerba1cb382003-09-19 17:17:26 +00001385 // Optimize a variety of ((val OP C1) & C2) combinations...
1386 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1387 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001388 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001389 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001390 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1391 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001392 }
Chris Lattner183b3362004-04-09 19:05:30 +00001393
1394 // Try to fold constant and into select arguments.
1395 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1396 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1397 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001398 if (isa<PHINode>(Op0))
1399 if (Instruction *NV = FoldOpIntoPhi(I))
1400 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001401 }
1402
Chris Lattnerbb74e222003-03-10 23:06:50 +00001403 Value *Op0NotVal = dyn_castNotVal(Op0);
1404 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001405
Chris Lattner023a4832004-06-18 06:07:51 +00001406 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1407 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1408
Misha Brukman9c003d82004-07-30 12:50:08 +00001409 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001410 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001411 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1412 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001413 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001414 return BinaryOperator::createNot(Or);
1415 }
1416
Chris Lattner623826c2004-09-28 21:48:02 +00001417 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1418 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001419 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1420 return R;
1421
Chris Lattner623826c2004-09-28 21:48:02 +00001422 Value *LHSVal, *RHSVal;
1423 ConstantInt *LHSCst, *RHSCst;
1424 Instruction::BinaryOps LHSCC, RHSCC;
1425 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1426 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1427 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1428 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1429 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1430 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1431 // Ensure that the larger constant is on the RHS.
1432 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1433 SetCondInst *LHS = cast<SetCondInst>(Op0);
1434 if (cast<ConstantBool>(Cmp)->getValue()) {
1435 std::swap(LHS, RHS);
1436 std::swap(LHSCst, RHSCst);
1437 std::swap(LHSCC, RHSCC);
1438 }
1439
1440 // At this point, we know we have have two setcc instructions
1441 // comparing a value against two constants and and'ing the result
1442 // together. Because of the above check, we know that we only have
1443 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1444 // FoldSetCCLogical check above), that the two constants are not
1445 // equal.
1446 assert(LHSCst != RHSCst && "Compares not folded above?");
1447
1448 switch (LHSCC) {
1449 default: assert(0 && "Unknown integer condition code!");
1450 case Instruction::SetEQ:
1451 switch (RHSCC) {
1452 default: assert(0 && "Unknown integer condition code!");
1453 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1454 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1455 return ReplaceInstUsesWith(I, ConstantBool::False);
1456 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1457 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1458 return ReplaceInstUsesWith(I, LHS);
1459 }
1460 case Instruction::SetNE:
1461 switch (RHSCC) {
1462 default: assert(0 && "Unknown integer condition code!");
1463 case Instruction::SetLT:
1464 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1465 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1466 break; // (X != 13 & X < 15) -> no change
1467 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1468 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1469 return ReplaceInstUsesWith(I, RHS);
1470 case Instruction::SetNE:
1471 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1472 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1473 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1474 LHSVal->getName()+".off");
1475 InsertNewInstBefore(Add, I);
1476 const Type *UnsType = Add->getType()->getUnsignedVersion();
1477 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1478 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1479 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1480 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1481 }
1482 break; // (X != 13 & X != 15) -> no change
1483 }
1484 break;
1485 case Instruction::SetLT:
1486 switch (RHSCC) {
1487 default: assert(0 && "Unknown integer condition code!");
1488 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1489 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1490 return ReplaceInstUsesWith(I, ConstantBool::False);
1491 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1492 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1493 return ReplaceInstUsesWith(I, LHS);
1494 }
1495 case Instruction::SetGT:
1496 switch (RHSCC) {
1497 default: assert(0 && "Unknown integer condition code!");
1498 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1499 return ReplaceInstUsesWith(I, LHS);
1500 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1501 return ReplaceInstUsesWith(I, RHS);
1502 case Instruction::SetNE:
1503 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1504 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1505 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001506 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1507 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001508 }
1509 }
1510 }
1511 }
1512
Chris Lattner113f4f42002-06-25 16:13:24 +00001513 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001514}
1515
Chris Lattner113f4f42002-06-25 16:13:24 +00001516Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001517 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001518 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001519
Chris Lattner81a7a232004-10-16 18:11:37 +00001520 if (isa<UndefValue>(Op1))
1521 return ReplaceInstUsesWith(I, // X | undef -> -1
1522 ConstantIntegral::getAllOnesValue(I.getType()));
1523
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001524 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001525 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1526 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001527
1528 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001529 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001530 if (RHS->isAllOnesValue())
1531 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001532
Chris Lattnerd4252a72004-07-30 07:50:03 +00001533 ConstantInt *C1; Value *X;
1534 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1535 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1536 std::string Op0Name = Op0->getName(); Op0->setName("");
1537 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1538 InsertNewInstBefore(Or, I);
1539 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1540 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001541
Chris Lattnerd4252a72004-07-30 07:50:03 +00001542 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1543 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1544 std::string Op0Name = Op0->getName(); Op0->setName("");
1545 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1546 InsertNewInstBefore(Or, I);
1547 return BinaryOperator::createXor(Or,
1548 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001549 }
Chris Lattner183b3362004-04-09 19:05:30 +00001550
1551 // Try to fold constant and into select arguments.
1552 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1553 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1554 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001555 if (isa<PHINode>(Op0))
1556 if (Instruction *NV = FoldOpIntoPhi(I))
1557 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001558 }
1559
Chris Lattner812aab72003-08-12 19:11:07 +00001560 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001561 Value *A, *B; ConstantInt *C1, *C2;
1562 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1563 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1564 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001565
Chris Lattnerd4252a72004-07-30 07:50:03 +00001566 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1567 if (A == Op1) // ~A | A == -1
1568 return ReplaceInstUsesWith(I,
1569 ConstantIntegral::getAllOnesValue(I.getType()));
1570 } else {
1571 A = 0;
1572 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001573
Chris Lattnerd4252a72004-07-30 07:50:03 +00001574 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1575 if (Op0 == B)
1576 return ReplaceInstUsesWith(I,
1577 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001578
Misha Brukman9c003d82004-07-30 12:50:08 +00001579 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001580 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1581 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1582 I.getName()+".demorgan"), I);
1583 return BinaryOperator::createNot(And);
1584 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001585 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001586
Chris Lattner3ac7c262003-08-13 20:16:26 +00001587 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001588 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001589 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1590 return R;
1591
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001592 Value *LHSVal, *RHSVal;
1593 ConstantInt *LHSCst, *RHSCst;
1594 Instruction::BinaryOps LHSCC, RHSCC;
1595 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1596 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1597 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1598 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1599 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1600 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1601 // Ensure that the larger constant is on the RHS.
1602 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1603 SetCondInst *LHS = cast<SetCondInst>(Op0);
1604 if (cast<ConstantBool>(Cmp)->getValue()) {
1605 std::swap(LHS, RHS);
1606 std::swap(LHSCst, RHSCst);
1607 std::swap(LHSCC, RHSCC);
1608 }
1609
1610 // At this point, we know we have have two setcc instructions
1611 // comparing a value against two constants and or'ing the result
1612 // together. Because of the above check, we know that we only have
1613 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1614 // FoldSetCCLogical check above), that the two constants are not
1615 // equal.
1616 assert(LHSCst != RHSCst && "Compares not folded above?");
1617
1618 switch (LHSCC) {
1619 default: assert(0 && "Unknown integer condition code!");
1620 case Instruction::SetEQ:
1621 switch (RHSCC) {
1622 default: assert(0 && "Unknown integer condition code!");
1623 case Instruction::SetEQ:
1624 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1625 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1626 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1627 LHSVal->getName()+".off");
1628 InsertNewInstBefore(Add, I);
1629 const Type *UnsType = Add->getType()->getUnsignedVersion();
1630 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1631 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1632 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1633 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1634 }
1635 break; // (X == 13 | X == 15) -> no change
1636
1637 case Instruction::SetGT:
1638 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1639 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1640 break; // (X == 13 | X > 15) -> no change
1641 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1642 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1643 return ReplaceInstUsesWith(I, RHS);
1644 }
1645 break;
1646 case Instruction::SetNE:
1647 switch (RHSCC) {
1648 default: assert(0 && "Unknown integer condition code!");
1649 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1650 return ReplaceInstUsesWith(I, RHS);
1651 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1652 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1653 return ReplaceInstUsesWith(I, LHS);
1654 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1655 return ReplaceInstUsesWith(I, ConstantBool::True);
1656 }
1657 break;
1658 case Instruction::SetLT:
1659 switch (RHSCC) {
1660 default: assert(0 && "Unknown integer condition code!");
1661 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1662 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001663 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1664 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001665 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1666 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1667 return ReplaceInstUsesWith(I, RHS);
1668 }
1669 break;
1670 case Instruction::SetGT:
1671 switch (RHSCC) {
1672 default: assert(0 && "Unknown integer condition code!");
1673 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1674 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1675 return ReplaceInstUsesWith(I, LHS);
1676 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1677 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1678 return ReplaceInstUsesWith(I, ConstantBool::True);
1679 }
1680 }
1681 }
1682 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001683 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001684}
1685
Chris Lattnerc2076352004-02-16 01:20:27 +00001686// XorSelf - Implements: X ^ X --> 0
1687struct XorSelf {
1688 Value *RHS;
1689 XorSelf(Value *rhs) : RHS(rhs) {}
1690 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1691 Instruction *apply(BinaryOperator &Xor) const {
1692 return &Xor;
1693 }
1694};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001695
1696
Chris Lattner113f4f42002-06-25 16:13:24 +00001697Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001698 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001699 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001700
Chris Lattner81a7a232004-10-16 18:11:37 +00001701 if (isa<UndefValue>(Op1))
1702 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1703
Chris Lattnerc2076352004-02-16 01:20:27 +00001704 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1705 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1706 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001707 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001708 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001709
Chris Lattner97638592003-07-23 21:37:07 +00001710 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001711 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001712 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001713 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001714
Chris Lattner97638592003-07-23 21:37:07 +00001715 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001716 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001717 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001718 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001719 return new SetCondInst(SCI->getInverseCondition(),
1720 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001721
Chris Lattner8f2f5982003-11-05 01:06:05 +00001722 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001723 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1724 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001725 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1726 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001727 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001728 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001729 }
Chris Lattner023a4832004-06-18 06:07:51 +00001730
1731 // ~(~X & Y) --> (X | ~Y)
1732 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1733 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1734 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1735 Instruction *NotY =
1736 BinaryOperator::createNot(Op0I->getOperand(1),
1737 Op0I->getOperand(1)->getName()+".not");
1738 InsertNewInstBefore(NotY, I);
1739 return BinaryOperator::createOr(Op0NotVal, NotY);
1740 }
1741 }
Chris Lattner97638592003-07-23 21:37:07 +00001742
1743 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001744 switch (Op0I->getOpcode()) {
1745 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001746 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001747 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001748 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1749 return BinaryOperator::createSub(
1750 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001751 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001752 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001753 }
Chris Lattnere5806662003-11-04 23:50:51 +00001754 break;
1755 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001756 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001757 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1758 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001759 break;
1760 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001761 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001762 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001763 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001764 break;
1765 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001766 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001767 }
Chris Lattner183b3362004-04-09 19:05:30 +00001768
1769 // Try to fold constant and into select arguments.
1770 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1771 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1772 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001773 if (isa<PHINode>(Op0))
1774 if (Instruction *NV = FoldOpIntoPhi(I))
1775 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001776 }
1777
Chris Lattnerbb74e222003-03-10 23:06:50 +00001778 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001779 if (X == Op1)
1780 return ReplaceInstUsesWith(I,
1781 ConstantIntegral::getAllOnesValue(I.getType()));
1782
Chris Lattnerbb74e222003-03-10 23:06:50 +00001783 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001784 if (X == Op0)
1785 return ReplaceInstUsesWith(I,
1786 ConstantIntegral::getAllOnesValue(I.getType()));
1787
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001788 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001789 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001790 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1791 cast<BinaryOperator>(Op1I)->swapOperands();
1792 I.swapOperands();
1793 std::swap(Op0, Op1);
1794 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1795 I.swapOperands();
1796 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001797 }
1798 } else if (Op1I->getOpcode() == Instruction::Xor) {
1799 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1800 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1801 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1802 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1803 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001804
1805 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001806 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001807 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1808 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001809 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001810 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1811 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001812 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001813 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001814 } else if (Op0I->getOpcode() == Instruction::Xor) {
1815 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1816 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1817 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1818 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001819 }
1820
Chris Lattner7aa2d472004-08-01 19:42:59 +00001821 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001822 Value *A, *B; ConstantInt *C1, *C2;
1823 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1824 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00001825 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00001826 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001827
Chris Lattner3ac7c262003-08-13 20:16:26 +00001828 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1829 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1830 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1831 return R;
1832
Chris Lattner113f4f42002-06-25 16:13:24 +00001833 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001834}
1835
Chris Lattner6862fbd2004-09-29 17:40:11 +00001836/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1837/// overflowed for this type.
1838static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1839 ConstantInt *In2) {
1840 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1841 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1842}
1843
1844static bool isPositive(ConstantInt *C) {
1845 return cast<ConstantSInt>(C)->getValue() >= 0;
1846}
1847
1848/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1849/// overflowed for this type.
1850static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1851 ConstantInt *In2) {
1852 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1853
1854 if (In1->getType()->isUnsigned())
1855 return cast<ConstantUInt>(Result)->getValue() <
1856 cast<ConstantUInt>(In1)->getValue();
1857 if (isPositive(In1) != isPositive(In2))
1858 return false;
1859 if (isPositive(In1))
1860 return cast<ConstantSInt>(Result)->getValue() <
1861 cast<ConstantSInt>(In1)->getValue();
1862 return cast<ConstantSInt>(Result)->getValue() >
1863 cast<ConstantSInt>(In1)->getValue();
1864}
1865
Chris Lattner113f4f42002-06-25 16:13:24 +00001866Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001867 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001868 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1869 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001870
1871 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001872 if (Op0 == Op1)
1873 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001874
Chris Lattner81a7a232004-10-16 18:11:37 +00001875 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
1876 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
1877
Chris Lattnerd07283a2003-08-13 05:38:46 +00001878 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1879 if (isa<ConstantPointerNull>(Op1) &&
1880 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001881 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1882
Chris Lattnerd07283a2003-08-13 05:38:46 +00001883
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001884 // setcc's with boolean values can always be turned into bitwise operations
1885 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00001886 switch (I.getOpcode()) {
1887 default: assert(0 && "Invalid setcc instruction!");
1888 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001889 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001890 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001891 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001892 }
Chris Lattner4456da62004-08-11 00:50:51 +00001893 case Instruction::SetNE:
1894 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001895
Chris Lattner4456da62004-08-11 00:50:51 +00001896 case Instruction::SetGT:
1897 std::swap(Op0, Op1); // Change setgt -> setlt
1898 // FALL THROUGH
1899 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1900 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1901 InsertNewInstBefore(Not, I);
1902 return BinaryOperator::createAnd(Not, Op1);
1903 }
1904 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001905 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00001906 // FALL THROUGH
1907 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1908 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1909 InsertNewInstBefore(Not, I);
1910 return BinaryOperator::createOr(Not, Op1);
1911 }
1912 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001913 }
1914
Chris Lattner2dd01742004-06-09 04:24:29 +00001915 // See if we are doing a comparison between a constant and an instruction that
1916 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001917 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00001918 // Check to see if we are comparing against the minimum or maximum value...
1919 if (CI->isMinValue()) {
1920 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1921 return ReplaceInstUsesWith(I, ConstantBool::False);
1922 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1923 return ReplaceInstUsesWith(I, ConstantBool::True);
1924 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1925 return BinaryOperator::createSetEQ(Op0, Op1);
1926 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1927 return BinaryOperator::createSetNE(Op0, Op1);
1928
1929 } else if (CI->isMaxValue()) {
1930 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1931 return ReplaceInstUsesWith(I, ConstantBool::False);
1932 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1933 return ReplaceInstUsesWith(I, ConstantBool::True);
1934 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1935 return BinaryOperator::createSetEQ(Op0, Op1);
1936 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1937 return BinaryOperator::createSetNE(Op0, Op1);
1938
1939 // Comparing against a value really close to min or max?
1940 } else if (isMinValuePlusOne(CI)) {
1941 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1942 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
1943 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1944 return BinaryOperator::createSetNE(Op0, SubOne(CI));
1945
1946 } else if (isMaxValueMinusOne(CI)) {
1947 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1948 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
1949 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1950 return BinaryOperator::createSetNE(Op0, AddOne(CI));
1951 }
1952
1953 // If we still have a setle or setge instruction, turn it into the
1954 // appropriate setlt or setgt instruction. Since the border cases have
1955 // already been handled above, this requires little checking.
1956 //
1957 if (I.getOpcode() == Instruction::SetLE)
1958 return BinaryOperator::createSetLT(Op0, AddOne(CI));
1959 if (I.getOpcode() == Instruction::SetGE)
1960 return BinaryOperator::createSetGT(Op0, SubOne(CI));
1961
Chris Lattnere1e10e12004-05-25 06:32:08 +00001962 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001963 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001964 case Instruction::PHI:
1965 if (Instruction *NV = FoldOpIntoPhi(I))
1966 return NV;
1967 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001968 case Instruction::And:
1969 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1970 LHSI->getOperand(0)->hasOneUse()) {
1971 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1972 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1973 // happens a LOT in code produced by the C front-end, for bitfield
1974 // access.
1975 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1976 ConstantUInt *ShAmt;
1977 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1978 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1979 const Type *Ty = LHSI->getType();
1980
1981 // We can fold this as long as we can't shift unknown bits
1982 // into the mask. This can only happen with signed shift
1983 // rights, as they sign-extend.
1984 if (ShAmt) {
1985 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00001986 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001987 if (!CanFold) {
1988 // To test for the bad case of the signed shr, see if any
1989 // of the bits shifted in could be tested after the mask.
1990 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00001991 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001992 Constant *ShVal =
1993 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1994 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1995 CanFold = true;
1996 }
1997
1998 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00001999 Constant *NewCst;
2000 if (Shift->getOpcode() == Instruction::Shl)
2001 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2002 else
2003 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002004
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002005 // Check to see if we are shifting out any of the bits being
2006 // compared.
2007 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2008 // If we shifted bits out, the fold is not going to work out.
2009 // As a special case, check to see if this means that the
2010 // result is always true or false now.
2011 if (I.getOpcode() == Instruction::SetEQ)
2012 return ReplaceInstUsesWith(I, ConstantBool::False);
2013 if (I.getOpcode() == Instruction::SetNE)
2014 return ReplaceInstUsesWith(I, ConstantBool::True);
2015 } else {
2016 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002017 Constant *NewAndCST;
2018 if (Shift->getOpcode() == Instruction::Shl)
2019 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2020 else
2021 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2022 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002023 LHSI->setOperand(0, Shift->getOperand(0));
2024 WorkList.push_back(Shift); // Shift is dead.
2025 AddUsesToWorkList(I);
2026 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002027 }
2028 }
Chris Lattner35167c32004-06-09 07:59:58 +00002029 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002030 }
2031 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002032
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002033 case Instruction::Cast: { // (setcc (cast X to larger), CI)
2034 const Type *SrcTy = LHSI->getOperand(0)->getType();
2035 if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) {
Chris Lattnerc9491282004-09-29 03:16:24 +00002036 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002037 if (SrcTy == Type::BoolTy) SrcBits = 1;
Chris Lattnerc9491282004-09-29 03:16:24 +00002038 unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002039 if (LHSI->getType() == Type::BoolTy) DestBits = 1;
Chris Lattner96f66162004-11-02 03:50:32 +00002040 if (SrcBits < DestBits &&
2041 // FIXME: Reenable the code below for < and >. However, we have
2042 // to handle the cases when the source of the cast and the dest of
2043 // the cast have different signs. e.g:
2044 // (cast sbyte %X to uint) >u 255U -> X <s (sbyte)0
2045 (I.getOpcode() == Instruction::SetEQ ||
2046 I.getOpcode() == Instruction::SetNE)) {
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002047 // Check to see if the comparison is always true or false.
2048 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
2049 if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002050 switch (I.getOpcode()) {
2051 default: assert(0 && "unknown integer comparison");
Chris Lattner96f66162004-11-02 03:50:32 +00002052#if 0
2053 case Instruction::SetLT: {
2054 Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
2055 Max = ConstantExpr::getCast(Max, LHSI->getType());
2056 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
2057 }
2058 case Instruction::SetGT: {
2059 Constant *Min = ConstantIntegral::getMinValue(SrcTy);
2060 Min = ConstantExpr::getCast(Min, LHSI->getType());
2061 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
2062 }
2063#endif
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002064 case Instruction::SetEQ:
2065 return ReplaceInstUsesWith(I, ConstantBool::False);
2066 case Instruction::SetNE:
2067 return ReplaceInstUsesWith(I, ConstantBool::True);
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002068 }
2069 }
2070
Chris Lattner96f66162004-11-02 03:50:32 +00002071 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0), NewCst);
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002072 }
2073 }
2074 break;
2075 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00002076 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2077 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2078 switch (I.getOpcode()) {
2079 default: break;
2080 case Instruction::SetEQ:
2081 case Instruction::SetNE: {
2082 // If we are comparing against bits always shifted out, the
2083 // comparison cannot succeed.
2084 Constant *Comp =
2085 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2086 if (Comp != CI) {// Comparing against a bit that we know is zero.
2087 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2088 Constant *Cst = ConstantBool::get(IsSetNE);
2089 return ReplaceInstUsesWith(I, Cst);
2090 }
2091
2092 if (LHSI->hasOneUse()) {
2093 // Otherwise strength reduce the shift into an and.
2094 unsigned ShAmtVal = ShAmt->getValue();
2095 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2096 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2097
2098 Constant *Mask;
2099 if (CI->getType()->isUnsigned()) {
2100 Mask = ConstantUInt::get(CI->getType(), Val);
2101 } else if (ShAmtVal != 0) {
2102 Mask = ConstantSInt::get(CI->getType(), Val);
2103 } else {
2104 Mask = ConstantInt::getAllOnesValue(CI->getType());
2105 }
2106
2107 Instruction *AndI =
2108 BinaryOperator::createAnd(LHSI->getOperand(0),
2109 Mask, LHSI->getName()+".mask");
2110 Value *And = InsertNewInstBefore(AndI, I);
2111 return new SetCondInst(I.getOpcode(), And,
2112 ConstantExpr::getUShr(CI, ShAmt));
2113 }
2114 }
2115 }
2116 }
2117 break;
2118
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002119 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002120 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002121 switch (I.getOpcode()) {
2122 default: break;
2123 case Instruction::SetEQ:
2124 case Instruction::SetNE: {
2125 // If we are comparing against bits always shifted out, the
2126 // comparison cannot succeed.
2127 Constant *Comp =
2128 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2129
2130 if (Comp != CI) {// Comparing against a bit that we know is zero.
2131 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2132 Constant *Cst = ConstantBool::get(IsSetNE);
2133 return ReplaceInstUsesWith(I, Cst);
2134 }
2135
2136 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00002137 unsigned ShAmtVal = ShAmt->getValue();
2138
Chris Lattner1023b872004-09-27 16:18:50 +00002139 // Otherwise strength reduce the shift into an and.
2140 uint64_t Val = ~0ULL; // All ones.
2141 Val <<= ShAmtVal; // Shift over to the right spot.
2142
2143 Constant *Mask;
2144 if (CI->getType()->isUnsigned()) {
2145 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2146 Val &= (1ULL << TypeBits)-1;
2147 Mask = ConstantUInt::get(CI->getType(), Val);
2148 } else {
2149 Mask = ConstantSInt::get(CI->getType(), Val);
2150 }
2151
2152 Instruction *AndI =
2153 BinaryOperator::createAnd(LHSI->getOperand(0),
2154 Mask, LHSI->getName()+".mask");
2155 Value *And = InsertNewInstBefore(AndI, I);
2156 return new SetCondInst(I.getOpcode(), And,
2157 ConstantExpr::getShl(CI, ShAmt));
2158 }
2159 break;
2160 }
2161 }
2162 }
2163 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002164
Chris Lattner6862fbd2004-09-29 17:40:11 +00002165 case Instruction::Div:
2166 // Fold: (div X, C1) op C2 -> range check
2167 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2168 // Fold this div into the comparison, producing a range check.
2169 // Determine, based on the divide type, what the range is being
2170 // checked. If there is an overflow on the low or high side, remember
2171 // it, otherwise compute the range [low, hi) bounding the new value.
2172 bool LoOverflow = false, HiOverflow = 0;
2173 ConstantInt *LoBound = 0, *HiBound = 0;
2174
2175 ConstantInt *Prod;
2176 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2177
Chris Lattnera92af962004-10-11 19:40:04 +00002178 Instruction::BinaryOps Opcode = I.getOpcode();
2179
Chris Lattner6862fbd2004-09-29 17:40:11 +00002180 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2181 } else if (LHSI->getType()->isUnsigned()) { // udiv
2182 LoBound = Prod;
2183 LoOverflow = ProdOV;
2184 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2185 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2186 if (CI->isNullValue()) { // (X / pos) op 0
2187 // Can't overflow.
2188 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2189 HiBound = DivRHS;
2190 } else if (isPositive(CI)) { // (X / pos) op pos
2191 LoBound = Prod;
2192 LoOverflow = ProdOV;
2193 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2194 } else { // (X / pos) op neg
2195 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2196 LoOverflow = AddWithOverflow(LoBound, Prod,
2197 cast<ConstantInt>(DivRHSH));
2198 HiBound = Prod;
2199 HiOverflow = ProdOV;
2200 }
2201 } else { // Divisor is < 0.
2202 if (CI->isNullValue()) { // (X / neg) op 0
2203 LoBound = AddOne(DivRHS);
2204 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2205 } else if (isPositive(CI)) { // (X / neg) op pos
2206 HiOverflow = LoOverflow = ProdOV;
2207 if (!LoOverflow)
2208 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2209 HiBound = AddOne(Prod);
2210 } else { // (X / neg) op neg
2211 LoBound = Prod;
2212 LoOverflow = HiOverflow = ProdOV;
2213 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2214 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002215
Chris Lattnera92af962004-10-11 19:40:04 +00002216 // Dividing by a negate swaps the condition.
2217 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002218 }
2219
2220 if (LoBound) {
2221 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002222 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002223 default: assert(0 && "Unhandled setcc opcode!");
2224 case Instruction::SetEQ:
2225 if (LoOverflow && HiOverflow)
2226 return ReplaceInstUsesWith(I, ConstantBool::False);
2227 else if (HiOverflow)
2228 return new SetCondInst(Instruction::SetGE, X, LoBound);
2229 else if (LoOverflow)
2230 return new SetCondInst(Instruction::SetLT, X, HiBound);
2231 else
2232 return InsertRangeTest(X, LoBound, HiBound, true, I);
2233 case Instruction::SetNE:
2234 if (LoOverflow && HiOverflow)
2235 return ReplaceInstUsesWith(I, ConstantBool::True);
2236 else if (HiOverflow)
2237 return new SetCondInst(Instruction::SetLT, X, LoBound);
2238 else if (LoOverflow)
2239 return new SetCondInst(Instruction::SetGE, X, HiBound);
2240 else
2241 return InsertRangeTest(X, LoBound, HiBound, false, I);
2242 case Instruction::SetLT:
2243 if (LoOverflow)
2244 return ReplaceInstUsesWith(I, ConstantBool::False);
2245 return new SetCondInst(Instruction::SetLT, X, LoBound);
2246 case Instruction::SetGT:
2247 if (HiOverflow)
2248 return ReplaceInstUsesWith(I, ConstantBool::False);
2249 return new SetCondInst(Instruction::SetGE, X, HiBound);
2250 }
2251 }
2252 }
2253 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002254 case Instruction::Select:
2255 // If either operand of the select is a constant, we can fold the
2256 // comparison into the select arms, which will cause one to be
2257 // constant folded and the select turned into a bitwise or.
2258 Value *Op1 = 0, *Op2 = 0;
2259 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00002260 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002261 // Fold the known value into the constant operand.
2262 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2263 // Insert a new SetCC of the other select operand.
2264 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002265 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002266 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00002267 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002268 // Fold the known value into the constant operand.
2269 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2270 // Insert a new SetCC of the other select operand.
2271 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002272 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002273 I.getName()), I);
2274 }
Chris Lattner2dd01742004-06-09 04:24:29 +00002275 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002276
2277 if (Op1)
2278 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2279 break;
2280 }
2281
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002282 // Simplify seteq and setne instructions...
2283 if (I.getOpcode() == Instruction::SetEQ ||
2284 I.getOpcode() == Instruction::SetNE) {
2285 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2286
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002287 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002288 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002289 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2290 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002291 case Instruction::Rem:
2292 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2293 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2294 BO->hasOneUse() &&
2295 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2296 if (unsigned L2 =
2297 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2298 const Type *UTy = BO->getType()->getUnsignedVersion();
2299 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2300 UTy, "tmp"), I);
2301 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2302 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2303 RHSCst, BO->getName()), I);
2304 return BinaryOperator::create(I.getOpcode(), NewRem,
2305 Constant::getNullValue(UTy));
2306 }
2307 break;
2308
Chris Lattnerc992add2003-08-13 05:33:12 +00002309 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002310 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2311 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002312 if (BO->hasOneUse())
2313 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2314 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002315 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002316 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2317 // efficiently invertible, or if the add has just this one use.
2318 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00002319
Chris Lattnerc992add2003-08-13 05:33:12 +00002320 if (Value *NegVal = dyn_castNegVal(BOp1))
2321 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2322 else if (Value *NegVal = dyn_castNegVal(BOp0))
2323 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002324 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002325 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2326 BO->setName("");
2327 InsertNewInstBefore(Neg, I);
2328 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2329 }
2330 }
2331 break;
2332 case Instruction::Xor:
2333 // For the xor case, we can xor two constants together, eliminating
2334 // the explicit xor.
2335 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2336 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002337 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002338
2339 // FALLTHROUGH
2340 case Instruction::Sub:
2341 // Replace (([sub|xor] A, B) != 0) with (A != B)
2342 if (CI->isNullValue())
2343 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2344 BO->getOperand(1));
2345 break;
2346
2347 case Instruction::Or:
2348 // If bits are being or'd in that are not present in the constant we
2349 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002350 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002351 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002352 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002353 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002354 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002355 break;
2356
2357 case Instruction::And:
2358 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002359 // If bits are being compared against that are and'd out, then the
2360 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002361 if (!ConstantExpr::getAnd(CI,
2362 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002363 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002364
Chris Lattner35167c32004-06-09 07:59:58 +00002365 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002366 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002367 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2368 Instruction::SetNE, Op0,
2369 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002370
Chris Lattnerc992add2003-08-13 05:33:12 +00002371 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2372 // to be a signed value as appropriate.
2373 if (isSignBit(BOC)) {
2374 Value *X = BO->getOperand(0);
2375 // If 'X' is not signed, insert a cast now...
2376 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002377 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002378 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002379 }
2380 return new SetCondInst(isSetNE ? Instruction::SetLT :
2381 Instruction::SetGE, X,
2382 Constant::getNullValue(X->getType()));
2383 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002384
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002385 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002386 if (CI->isNullValue() && isHighOnes(BOC)) {
2387 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002388 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002389
2390 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002391 if (NegX->getType()->isSigned()) {
2392 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2393 X = InsertCastBefore(X, DestTy, I);
2394 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002395 }
2396
2397 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002398 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002399 }
2400
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002401 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002402 default: break;
2403 }
2404 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002405 } else { // Not a SetEQ/SetNE
2406 // If the LHS is a cast from an integral value of the same size,
2407 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2408 Value *CastOp = Cast->getOperand(0);
2409 const Type *SrcTy = CastOp->getType();
2410 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2411 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2412 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2413 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2414 "Source and destination signednesses should differ!");
2415 if (Cast->getType()->isSigned()) {
2416 // If this is a signed comparison, check for comparisons in the
2417 // vicinity of zero.
2418 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2419 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002420 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002421 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2422 else if (I.getOpcode() == Instruction::SetGT &&
2423 cast<ConstantSInt>(CI)->getValue() == -1)
2424 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002425 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002426 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2427 } else {
2428 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2429 if (I.getOpcode() == Instruction::SetLT &&
2430 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2431 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002432 return BinaryOperator::createSetGT(CastOp,
2433 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002434 else if (I.getOpcode() == Instruction::SetGT &&
2435 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2436 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002437 return BinaryOperator::createSetLT(CastOp,
2438 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002439 }
2440 }
2441 }
Chris Lattnere967b342003-06-04 05:10:11 +00002442 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002443 }
2444
Chris Lattner16930792003-11-03 04:25:02 +00002445 // Test to see if the operands of the setcc are casted versions of other
2446 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002447 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2448 Value *CastOp0 = CI->getOperand(0);
2449 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002450 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002451 (I.getOpcode() == Instruction::SetEQ ||
2452 I.getOpcode() == Instruction::SetNE)) {
2453 // We keep moving the cast from the left operand over to the right
2454 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002455 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002456
2457 // If operand #1 is a cast instruction, see if we can eliminate it as
2458 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002459 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2460 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002461 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002462 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002463
2464 // If Op1 is a constant, we can fold the cast into the constant.
2465 if (Op1->getType() != Op0->getType())
2466 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2467 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2468 } else {
2469 // Otherwise, cast the RHS right before the setcc
2470 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2471 InsertNewInstBefore(cast<Instruction>(Op1), I);
2472 }
2473 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2474 }
2475
Chris Lattner6444c372003-11-03 05:17:03 +00002476 // Handle the special case of: setcc (cast bool to X), <cst>
2477 // This comes up when you have code like
2478 // int X = A < B;
2479 // if (X) ...
2480 // For generality, we handle any zero-extension of any operand comparison
2481 // with a constant.
2482 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2483 const Type *SrcTy = CastOp0->getType();
2484 const Type *DestTy = Op0->getType();
2485 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2486 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2487 // Ok, we have an expansion of operand 0 into a new type. Get the
2488 // constant value, masink off bits which are not set in the RHS. These
2489 // could be set if the destination value is signed.
2490 uint64_t ConstVal = ConstantRHS->getRawValue();
2491 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2492
2493 // If the constant we are comparing it with has high bits set, which
2494 // don't exist in the original value, the values could never be equal,
2495 // because the source would be zero extended.
2496 unsigned SrcBits =
2497 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002498 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2499 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002500 switch (I.getOpcode()) {
2501 default: assert(0 && "Unknown comparison type!");
2502 case Instruction::SetEQ:
2503 return ReplaceInstUsesWith(I, ConstantBool::False);
2504 case Instruction::SetNE:
2505 return ReplaceInstUsesWith(I, ConstantBool::True);
2506 case Instruction::SetLT:
2507 case Instruction::SetLE:
2508 if (DestTy->isSigned() && HasSignBit)
2509 return ReplaceInstUsesWith(I, ConstantBool::False);
2510 return ReplaceInstUsesWith(I, ConstantBool::True);
2511 case Instruction::SetGT:
2512 case Instruction::SetGE:
2513 if (DestTy->isSigned() && HasSignBit)
2514 return ReplaceInstUsesWith(I, ConstantBool::True);
2515 return ReplaceInstUsesWith(I, ConstantBool::False);
2516 }
2517 }
2518
2519 // Otherwise, we can replace the setcc with a setcc of the smaller
2520 // operand value.
2521 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2522 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2523 }
2524 }
2525 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002526 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002527}
2528
2529
2530
Chris Lattnere8d6c602003-03-10 19:16:08 +00002531Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002532 assert(I.getOperand(1)->getType() == Type::UByteTy);
2533 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002534 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002535
2536 // shl X, 0 == X and shr X, 0 == X
2537 // shl 0, X == 0 and shr 0, X == 0
2538 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00002539 Op0 == Constant::getNullValue(Op0->getType()))
2540 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002541
Chris Lattner81a7a232004-10-16 18:11:37 +00002542 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
2543 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00002544 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00002545 else // undef << X -> 0 AND undef >>u X -> 0
2546 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2547 }
2548 if (isa<UndefValue>(Op1)) {
2549 if (isLeftShift || I.getType()->isUnsigned())
2550 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2551 else
2552 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
2553 }
2554
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002555 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2556 if (!isLeftShift)
2557 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2558 if (CSI->isAllOnesValue())
2559 return ReplaceInstUsesWith(I, CSI);
2560
Chris Lattner183b3362004-04-09 19:05:30 +00002561 // Try to fold constant and into select arguments.
2562 if (isa<Constant>(Op0))
2563 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2564 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2565 return R;
2566
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002567 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002568 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2569 // of a signed value.
2570 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00002571 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002572 if (CUI->getValue() >= TypeBits) {
2573 if (!Op0->getType()->isSigned() || isLeftShift)
2574 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2575 else {
2576 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2577 return &I;
2578 }
2579 }
Chris Lattner55f3d942002-09-10 23:04:09 +00002580
Chris Lattnerede3fe02003-08-13 04:18:28 +00002581 // ((X*C1) << C2) == (X * (C1 << C2))
2582 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2583 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2584 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002585 return BinaryOperator::createMul(BO->getOperand(0),
2586 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00002587
Chris Lattner183b3362004-04-09 19:05:30 +00002588 // Try to fold constant and into select arguments.
2589 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2590 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2591 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002592 if (isa<PHINode>(Op0))
2593 if (Instruction *NV = FoldOpIntoPhi(I))
2594 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00002595
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002596 // If the operand is an bitwise operator with a constant RHS, and the
2597 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002598 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002599 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2600 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2601 bool isValid = true; // Valid only for And, Or, Xor
2602 bool highBitSet = false; // Transform if high bit of constant set?
2603
2604 switch (Op0BO->getOpcode()) {
2605 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00002606 case Instruction::Add:
2607 isValid = isLeftShift;
2608 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002609 case Instruction::Or:
2610 case Instruction::Xor:
2611 highBitSet = false;
2612 break;
2613 case Instruction::And:
2614 highBitSet = true;
2615 break;
2616 }
2617
2618 // If this is a signed shift right, and the high bit is modified
2619 // by the logical operation, do not perform the transformation.
2620 // The highBitSet boolean indicates the value of the high bit of
2621 // the constant which would cause it to be modified for this
2622 // operation.
2623 //
2624 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2625 uint64_t Val = Op0C->getRawValue();
2626 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2627 }
2628
2629 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002630 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002631
2632 Instruction *NewShift =
2633 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2634 Op0BO->getName());
2635 Op0BO->setName("");
2636 InsertNewInstBefore(NewShift, I);
2637
2638 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2639 NewRHS);
2640 }
2641 }
2642
Chris Lattner3204d4e2003-07-24 17:52:58 +00002643 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002644 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00002645 if (ConstantUInt *ShiftAmt1C =
2646 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002647 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2648 unsigned ShiftAmt2 = CUI->getValue();
2649
2650 // Check for (A << c1) << c2 and (A >> c1) >> c2
2651 if (I.getOpcode() == Op0SI->getOpcode()) {
2652 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002653 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2654 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00002655 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2656 ConstantUInt::get(Type::UByteTy, Amt));
2657 }
2658
Chris Lattnerab780df2003-07-24 18:38:56 +00002659 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2660 // signed types, we can only support the (A >> c1) << c2 configuration,
2661 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002662 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002663 // Calculate bitmask for what gets shifted off the edge...
2664 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002665 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002666 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002667 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002668 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00002669
2670 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002671 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2672 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00002673 InsertNewInstBefore(Mask, I);
2674
2675 // Figure out what flavor of shift we should use...
2676 if (ShiftAmt1 == ShiftAmt2)
2677 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2678 else if (ShiftAmt1 < ShiftAmt2) {
2679 return new ShiftInst(I.getOpcode(), Mask,
2680 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2681 } else {
2682 return new ShiftInst(Op0SI->getOpcode(), Mask,
2683 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2684 }
2685 }
2686 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002687 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00002688
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002689 return 0;
2690}
2691
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002692enum CastType {
2693 Noop = 0,
2694 Truncate = 1,
2695 Signext = 2,
2696 Zeroext = 3
2697};
2698
2699/// getCastType - In the future, we will split the cast instruction into these
2700/// various types. Until then, we have to do the analysis here.
2701static CastType getCastType(const Type *Src, const Type *Dest) {
2702 assert(Src->isIntegral() && Dest->isIntegral() &&
2703 "Only works on integral types!");
2704 unsigned SrcSize = Src->getPrimitiveSize()*8;
2705 if (Src == Type::BoolTy) SrcSize = 1;
2706 unsigned DestSize = Dest->getPrimitiveSize()*8;
2707 if (Dest == Type::BoolTy) DestSize = 1;
2708
2709 if (SrcSize == DestSize) return Noop;
2710 if (SrcSize > DestSize) return Truncate;
2711 if (Src->isSigned()) return Signext;
2712 return Zeroext;
2713}
2714
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002715
Chris Lattner48a44f72002-05-02 17:06:02 +00002716// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2717// instruction.
2718//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002719static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00002720 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002721
Chris Lattner650b6da2002-08-02 20:00:25 +00002722 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2723 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00002724 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00002725 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00002726 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00002727
Chris Lattner4fbad962004-07-21 04:27:24 +00002728 // If we are casting between pointer and integer types, treat pointers as
2729 // integers of the appropriate size for the code below.
2730 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2731 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2732 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00002733
Chris Lattner48a44f72002-05-02 17:06:02 +00002734 // Allow free casting and conversion of sizes as long as the sign doesn't
2735 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002736 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002737 CastType FirstCast = getCastType(SrcTy, MidTy);
2738 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00002739
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002740 // Capture the effect of these two casts. If the result is a legal cast,
2741 // the CastType is stored here, otherwise a special code is used.
2742 static const unsigned CastResult[] = {
2743 // First cast is noop
2744 0, 1, 2, 3,
2745 // First cast is a truncate
2746 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2747 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00002748 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002749 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00002750 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002751 };
2752
2753 unsigned Result = CastResult[FirstCast*4+SecondCast];
2754 switch (Result) {
2755 default: assert(0 && "Illegal table value!");
2756 case 0:
2757 case 1:
2758 case 2:
2759 case 3:
2760 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2761 // truncates, we could eliminate more casts.
2762 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2763 case 4:
2764 return false; // Not possible to eliminate this here.
2765 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00002766 // Sign or zero extend followed by truncate is always ok if the result
2767 // is a truncate or noop.
2768 CastType ResultCast = getCastType(SrcTy, DstTy);
2769 if (ResultCast == Noop || ResultCast == Truncate)
2770 return true;
2771 // Otherwise we are still growing the value, we are only safe if the
2772 // result will match the sign/zeroextendness of the result.
2773 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00002774 }
Chris Lattner650b6da2002-08-02 20:00:25 +00002775 }
Chris Lattner48a44f72002-05-02 17:06:02 +00002776 return false;
2777}
2778
Chris Lattner11ffd592004-07-20 05:21:00 +00002779static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002780 if (V->getType() == Ty || isa<Constant>(V)) return false;
2781 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00002782 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2783 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002784 return false;
2785 return true;
2786}
2787
2788/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2789/// InsertBefore instruction. This is specialized a bit to avoid inserting
2790/// casts that are known to not do anything...
2791///
2792Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2793 Instruction *InsertBefore) {
2794 if (V->getType() == DestTy) return V;
2795 if (Constant *C = dyn_cast<Constant>(V))
2796 return ConstantExpr::getCast(C, DestTy);
2797
2798 CastInst *CI = new CastInst(V, DestTy, V->getName());
2799 InsertNewInstBefore(CI, *InsertBefore);
2800 return CI;
2801}
Chris Lattner48a44f72002-05-02 17:06:02 +00002802
2803// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002804//
Chris Lattner113f4f42002-06-25 16:13:24 +00002805Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002806 Value *Src = CI.getOperand(0);
2807
Chris Lattner48a44f72002-05-02 17:06:02 +00002808 // If the user is casting a value to the same type, eliminate this cast
2809 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002810 if (CI.getType() == Src->getType())
2811 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002812
Chris Lattner81a7a232004-10-16 18:11:37 +00002813 if (isa<UndefValue>(Src)) // cast undef -> undef
2814 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
2815
Chris Lattner48a44f72002-05-02 17:06:02 +00002816 // If casting the result of another cast instruction, try to eliminate this
2817 // one!
2818 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002819 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002820 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner11ffd592004-07-20 05:21:00 +00002821 CSrc->getType(), CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002822 // This instruction now refers directly to the cast's src operand. This
2823 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002824 CI.setOperand(0, CSrc->getOperand(0));
2825 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002826 }
2827
Chris Lattner650b6da2002-08-02 20:00:25 +00002828 // If this is an A->B->A cast, and we are dealing with integral types, try
2829 // to convert this into a logical 'and' instruction.
2830 //
2831 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002832 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002833 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2834 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2835 assert(CSrc->getType() != Type::ULongTy &&
2836 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002837 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002838 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002839 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002840 }
2841 }
2842
Chris Lattner03841652004-05-25 04:29:21 +00002843 // If this is a cast to bool, turn it into the appropriate setne instruction.
2844 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002845 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002846 Constant::getNullValue(CI.getOperand(0)->getType()));
2847
Chris Lattnerd0d51602003-06-21 23:12:02 +00002848 // If casting the result of a getelementptr instruction with no offset, turn
2849 // this into a cast of the original pointer!
2850 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002851 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002852 bool AllZeroOperands = true;
2853 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2854 if (!isa<Constant>(GEP->getOperand(i)) ||
2855 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2856 AllZeroOperands = false;
2857 break;
2858 }
2859 if (AllZeroOperands) {
2860 CI.setOperand(0, GEP->getOperand(0));
2861 return &CI;
2862 }
2863 }
2864
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002865 // If we are casting a malloc or alloca to a pointer to a type of the same
2866 // size, rewrite the allocation instruction to allocate the "right" type.
2867 //
2868 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002869 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002870 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2871 // Get the type really allocated and the type casted to...
2872 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002873 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002874 if (AllocElTy->isSized() && CastElTy->isSized()) {
2875 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2876 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002877
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002878 // If the allocation is for an even multiple of the cast type size
2879 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2880 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002881 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002882 std::string Name = AI->getName(); AI->setName("");
2883 AllocationInst *New;
2884 if (isa<MallocInst>(AI))
2885 New = new MallocInst(CastElTy, Amt, Name);
2886 else
2887 New = new AllocaInst(CastElTy, Amt, Name);
2888 InsertNewInstBefore(New, *AI);
2889 return ReplaceInstUsesWith(CI, New);
2890 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002891 }
2892 }
2893
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002894 if (isa<PHINode>(Src))
2895 if (Instruction *NV = FoldOpIntoPhi(CI))
2896 return NV;
2897
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002898 // If the source value is an instruction with only this use, we can attempt to
2899 // propagate the cast into the instruction. Also, only handle integral types
2900 // for now.
2901 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002902 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002903 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2904 const Type *DestTy = CI.getType();
2905 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2906 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2907
2908 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2909 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2910
2911 switch (SrcI->getOpcode()) {
2912 case Instruction::Add:
2913 case Instruction::Mul:
2914 case Instruction::And:
2915 case Instruction::Or:
2916 case Instruction::Xor:
2917 // If we are discarding information, or just changing the sign, rewrite.
2918 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2919 // Don't insert two casts if they cannot be eliminated. We allow two
2920 // casts to be inserted if the sizes are the same. This could only be
2921 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00002922 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2923 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002924 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2925 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2926 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2927 ->getOpcode(), Op0c, Op1c);
2928 }
2929 }
2930 break;
2931 case Instruction::Shl:
2932 // Allow changing the sign of the source operand. Do not allow changing
2933 // the size of the shift, UNLESS the shift amount is a constant. We
2934 // mush not change variable sized shifts to a smaller size, because it
2935 // is undefined to shift more bits out than exist in the value.
2936 if (DestBitSize == SrcBitSize ||
2937 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2938 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2939 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2940 }
2941 break;
2942 }
2943 }
2944
Chris Lattner260ab202002-04-18 17:39:14 +00002945 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00002946}
2947
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002948/// GetSelectFoldableOperands - We want to turn code that looks like this:
2949/// %C = or %A, %B
2950/// %D = select %cond, %C, %A
2951/// into:
2952/// %C = select %cond, %B, 0
2953/// %D = or %A, %C
2954///
2955/// Assuming that the specified instruction is an operand to the select, return
2956/// a bitmask indicating which operands of this instruction are foldable if they
2957/// equal the other incoming value of the select.
2958///
2959static unsigned GetSelectFoldableOperands(Instruction *I) {
2960 switch (I->getOpcode()) {
2961 case Instruction::Add:
2962 case Instruction::Mul:
2963 case Instruction::And:
2964 case Instruction::Or:
2965 case Instruction::Xor:
2966 return 3; // Can fold through either operand.
2967 case Instruction::Sub: // Can only fold on the amount subtracted.
2968 case Instruction::Shl: // Can only fold on the shift amount.
2969 case Instruction::Shr:
2970 return 1;
2971 default:
2972 return 0; // Cannot fold
2973 }
2974}
2975
2976/// GetSelectFoldableConstant - For the same transformation as the previous
2977/// function, return the identity constant that goes into the select.
2978static Constant *GetSelectFoldableConstant(Instruction *I) {
2979 switch (I->getOpcode()) {
2980 default: assert(0 && "This cannot happen!"); abort();
2981 case Instruction::Add:
2982 case Instruction::Sub:
2983 case Instruction::Or:
2984 case Instruction::Xor:
2985 return Constant::getNullValue(I->getType());
2986 case Instruction::Shl:
2987 case Instruction::Shr:
2988 return Constant::getNullValue(Type::UByteTy);
2989 case Instruction::And:
2990 return ConstantInt::getAllOnesValue(I->getType());
2991 case Instruction::Mul:
2992 return ConstantInt::get(I->getType(), 1);
2993 }
2994}
2995
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002996Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00002997 Value *CondVal = SI.getCondition();
2998 Value *TrueVal = SI.getTrueValue();
2999 Value *FalseVal = SI.getFalseValue();
3000
3001 // select true, X, Y -> X
3002 // select false, X, Y -> Y
3003 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003004 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00003005 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003006 else {
3007 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00003008 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003009 }
Chris Lattner533bc492004-03-30 19:37:13 +00003010
3011 // select C, X, X -> X
3012 if (TrueVal == FalseVal)
3013 return ReplaceInstUsesWith(SI, TrueVal);
3014
Chris Lattner81a7a232004-10-16 18:11:37 +00003015 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3016 return ReplaceInstUsesWith(SI, FalseVal);
3017 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3018 return ReplaceInstUsesWith(SI, TrueVal);
3019 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3020 if (isa<Constant>(TrueVal))
3021 return ReplaceInstUsesWith(SI, TrueVal);
3022 else
3023 return ReplaceInstUsesWith(SI, FalseVal);
3024 }
3025
Chris Lattner1c631e82004-04-08 04:43:23 +00003026 if (SI.getType() == Type::BoolTy)
3027 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3028 if (C == ConstantBool::True) {
3029 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003030 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003031 } else {
3032 // Change: A = select B, false, C --> A = and !B, C
3033 Value *NotCond =
3034 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3035 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003036 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003037 }
3038 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3039 if (C == ConstantBool::False) {
3040 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003041 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003042 } else {
3043 // Change: A = select B, C, true --> A = or !B, C
3044 Value *NotCond =
3045 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3046 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003047 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003048 }
3049 }
3050
Chris Lattner183b3362004-04-09 19:05:30 +00003051 // Selecting between two integer constants?
3052 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3053 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3054 // select C, 1, 0 -> cast C to int
3055 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3056 return new CastInst(CondVal, SI.getType());
3057 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3058 // select C, 0, 1 -> cast !C to int
3059 Value *NotCond =
3060 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00003061 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00003062 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00003063 }
Chris Lattner35167c32004-06-09 07:59:58 +00003064
3065 // If one of the constants is zero (we know they can't both be) and we
3066 // have a setcc instruction with zero, and we have an 'and' with the
3067 // non-constant value, eliminate this whole mess. This corresponds to
3068 // cases like this: ((X & 27) ? 27 : 0)
3069 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3070 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3071 if ((IC->getOpcode() == Instruction::SetEQ ||
3072 IC->getOpcode() == Instruction::SetNE) &&
3073 isa<ConstantInt>(IC->getOperand(1)) &&
3074 cast<Constant>(IC->getOperand(1))->isNullValue())
3075 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3076 if (ICA->getOpcode() == Instruction::And &&
3077 isa<ConstantInt>(ICA->getOperand(1)) &&
3078 (ICA->getOperand(1) == TrueValC ||
3079 ICA->getOperand(1) == FalseValC) &&
3080 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3081 // Okay, now we know that everything is set up, we just don't
3082 // know whether we have a setne or seteq and whether the true or
3083 // false val is the zero.
3084 bool ShouldNotVal = !TrueValC->isNullValue();
3085 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3086 Value *V = ICA;
3087 if (ShouldNotVal)
3088 V = InsertNewInstBefore(BinaryOperator::create(
3089 Instruction::Xor, V, ICA->getOperand(1)), SI);
3090 return ReplaceInstUsesWith(SI, V);
3091 }
Chris Lattner533bc492004-03-30 19:37:13 +00003092 }
Chris Lattner623fba12004-04-10 22:21:27 +00003093
3094 // See if we are selecting two values based on a comparison of the two values.
3095 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3096 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3097 // Transform (X == Y) ? X : Y -> Y
3098 if (SCI->getOpcode() == Instruction::SetEQ)
3099 return ReplaceInstUsesWith(SI, FalseVal);
3100 // Transform (X != Y) ? X : Y -> X
3101 if (SCI->getOpcode() == Instruction::SetNE)
3102 return ReplaceInstUsesWith(SI, TrueVal);
3103 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3104
3105 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3106 // Transform (X == Y) ? Y : X -> X
3107 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003108 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003109 // Transform (X != Y) ? Y : X -> Y
3110 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003111 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003112 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3113 }
3114 }
Chris Lattner1c631e82004-04-08 04:43:23 +00003115
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003116 // See if we can fold the select into one of our operands.
3117 if (SI.getType()->isInteger()) {
3118 // See the comment above GetSelectFoldableOperands for a description of the
3119 // transformation we are doing here.
3120 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3121 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3122 !isa<Constant>(FalseVal))
3123 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3124 unsigned OpToFold = 0;
3125 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3126 OpToFold = 1;
3127 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3128 OpToFold = 2;
3129 }
3130
3131 if (OpToFold) {
3132 Constant *C = GetSelectFoldableConstant(TVI);
3133 std::string Name = TVI->getName(); TVI->setName("");
3134 Instruction *NewSel =
3135 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3136 Name);
3137 InsertNewInstBefore(NewSel, SI);
3138 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3139 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3140 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3141 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3142 else {
3143 assert(0 && "Unknown instruction!!");
3144 }
3145 }
3146 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003147
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003148 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3149 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3150 !isa<Constant>(TrueVal))
3151 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3152 unsigned OpToFold = 0;
3153 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3154 OpToFold = 1;
3155 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3156 OpToFold = 2;
3157 }
3158
3159 if (OpToFold) {
3160 Constant *C = GetSelectFoldableConstant(FVI);
3161 std::string Name = FVI->getName(); FVI->setName("");
3162 Instruction *NewSel =
3163 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3164 Name);
3165 InsertNewInstBefore(NewSel, SI);
3166 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3167 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3168 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3169 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3170 else {
3171 assert(0 && "Unknown instruction!!");
3172 }
3173 }
3174 }
3175 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003176 return 0;
3177}
3178
3179
Chris Lattner970c33a2003-06-19 17:00:31 +00003180// CallInst simplification
3181//
3182Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003183 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3184 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00003185 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3186 bool Changed = false;
3187
3188 // memmove/cpy/set of zero bytes is a noop.
3189 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3190 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3191
3192 // FIXME: Increase alignment here.
3193
3194 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3195 if (CI->getRawValue() == 1) {
3196 // Replace the instruction with just byte operations. We would
3197 // transform other cases to loads/stores, but we don't know if
3198 // alignment is sufficient.
3199 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003200 }
3201
Chris Lattner00648e12004-10-12 04:52:52 +00003202 // If we have a memmove and the source operation is a constant global,
3203 // then the source and dest pointers can't alias, so we can change this
3204 // into a call to memcpy.
3205 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3206 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3207 if (GVSrc->isConstant()) {
3208 Module *M = CI.getParent()->getParent()->getParent();
3209 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3210 CI.getCalledFunction()->getFunctionType());
3211 CI.setOperand(0, MemCpy);
3212 Changed = true;
3213 }
3214
3215 if (Changed) return &CI;
3216 }
3217
Chris Lattneraec3d942003-10-07 22:32:43 +00003218 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003219}
3220
3221// InvokeInst simplification
3222//
3223Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003224 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003225}
3226
Chris Lattneraec3d942003-10-07 22:32:43 +00003227// visitCallSite - Improvements for call and invoke instructions.
3228//
3229Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003230 bool Changed = false;
3231
3232 // If the callee is a constexpr cast of a function, attempt to move the cast
3233 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003234 if (transformConstExprCastCall(CS)) return 0;
3235
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003236 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00003237
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003238 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3239 // This instruction is not reachable, just remove it. We insert a store to
3240 // undef so that we know that this code is not reachable, despite the fact
3241 // that we can't modify the CFG here.
3242 new StoreInst(ConstantBool::True,
3243 UndefValue::get(PointerType::get(Type::BoolTy)),
3244 CS.getInstruction());
3245
3246 if (!CS.getInstruction()->use_empty())
3247 CS.getInstruction()->
3248 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3249
3250 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3251 // Don't break the CFG, insert a dummy cond branch.
3252 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3253 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00003254 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003255 return EraseInstFromFunction(*CS.getInstruction());
3256 }
Chris Lattner81a7a232004-10-16 18:11:37 +00003257
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003258 const PointerType *PTy = cast<PointerType>(Callee->getType());
3259 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3260 if (FTy->isVarArg()) {
3261 // See if we can optimize any arguments passed through the varargs area of
3262 // the call.
3263 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3264 E = CS.arg_end(); I != E; ++I)
3265 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3266 // If this cast does not effect the value passed through the varargs
3267 // area, we can eliminate the use of the cast.
3268 Value *Op = CI->getOperand(0);
3269 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3270 *I = Op;
3271 Changed = true;
3272 }
3273 }
3274 }
Chris Lattneraec3d942003-10-07 22:32:43 +00003275
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003276 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00003277}
3278
Chris Lattner970c33a2003-06-19 17:00:31 +00003279// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3280// attempt to move the cast to the arguments of the call/invoke.
3281//
3282bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3283 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3284 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00003285 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00003286 return false;
Reid Spencer87436872004-07-18 00:38:32 +00003287 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00003288 Instruction *Caller = CS.getInstruction();
3289
3290 // Okay, this is a cast from a function to a different type. Unless doing so
3291 // would cause a type conversion of one of our arguments, change this call to
3292 // be a direct call with arguments casted to the appropriate types.
3293 //
3294 const FunctionType *FT = Callee->getFunctionType();
3295 const Type *OldRetTy = Caller->getType();
3296
Chris Lattner1f7942f2004-01-14 06:06:08 +00003297 // Check to see if we are changing the return type...
3298 if (OldRetTy != FT->getReturnType()) {
3299 if (Callee->isExternal() &&
3300 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3301 !Caller->use_empty())
3302 return false; // Cannot transform this return value...
3303
3304 // If the callsite is an invoke instruction, and the return value is used by
3305 // a PHI node in a successor, we cannot change the return type of the call
3306 // because there is no place to put the cast instruction (without breaking
3307 // the critical edge). Bail out in this case.
3308 if (!Caller->use_empty())
3309 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3310 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3311 UI != E; ++UI)
3312 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3313 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003314 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00003315 return false;
3316 }
Chris Lattner970c33a2003-06-19 17:00:31 +00003317
3318 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3319 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3320
3321 CallSite::arg_iterator AI = CS.arg_begin();
3322 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3323 const Type *ParamTy = FT->getParamType(i);
3324 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3325 if (Callee->isExternal() && !isConvertible) return false;
3326 }
3327
3328 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3329 Callee->isExternal())
3330 return false; // Do not delete arguments unless we have a function body...
3331
3332 // Okay, we decided that this is a safe thing to do: go ahead and start
3333 // inserting cast instructions as necessary...
3334 std::vector<Value*> Args;
3335 Args.reserve(NumActualArgs);
3336
3337 AI = CS.arg_begin();
3338 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3339 const Type *ParamTy = FT->getParamType(i);
3340 if ((*AI)->getType() == ParamTy) {
3341 Args.push_back(*AI);
3342 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00003343 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3344 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00003345 }
3346 }
3347
3348 // If the function takes more arguments than the call was taking, add them
3349 // now...
3350 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3351 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3352
3353 // If we are removing arguments to the function, emit an obnoxious warning...
3354 if (FT->getNumParams() < NumActualArgs)
3355 if (!FT->isVarArg()) {
3356 std::cerr << "WARNING: While resolving call to function '"
3357 << Callee->getName() << "' arguments were dropped!\n";
3358 } else {
3359 // Add all of the arguments in their promoted form to the arg list...
3360 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3361 const Type *PTy = getPromotedType((*AI)->getType());
3362 if (PTy != (*AI)->getType()) {
3363 // Must promote to pass through va_arg area!
3364 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3365 InsertNewInstBefore(Cast, *Caller);
3366 Args.push_back(Cast);
3367 } else {
3368 Args.push_back(*AI);
3369 }
3370 }
3371 }
3372
3373 if (FT->getReturnType() == Type::VoidTy)
3374 Caller->setName(""); // Void type should not have a name...
3375
3376 Instruction *NC;
3377 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003378 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00003379 Args, Caller->getName(), Caller);
3380 } else {
3381 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3382 }
3383
3384 // Insert a cast of the return type as necessary...
3385 Value *NV = NC;
3386 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3387 if (NV->getType() != Type::VoidTy) {
3388 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00003389
3390 // If this is an invoke instruction, we should insert it after the first
3391 // non-phi, instruction in the normal successor block.
3392 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3393 BasicBlock::iterator I = II->getNormalDest()->begin();
3394 while (isa<PHINode>(I)) ++I;
3395 InsertNewInstBefore(NC, *I);
3396 } else {
3397 // Otherwise, it's a call, just insert cast right after the call instr
3398 InsertNewInstBefore(NC, *Caller);
3399 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003400 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00003401 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00003402 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00003403 }
3404 }
3405
3406 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3407 Caller->replaceAllUsesWith(NV);
3408 Caller->getParent()->getInstList().erase(Caller);
3409 removeFromWorkList(Caller);
3410 return true;
3411}
3412
3413
Chris Lattner48a44f72002-05-02 17:06:02 +00003414
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003415// PHINode simplification
3416//
Chris Lattner113f4f42002-06-25 16:13:24 +00003417Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnere29d6342004-10-17 21:22:38 +00003418 if (Value *V = hasConstantValue(&PN)) {
3419 // If V is an instruction, we have to be certain that it dominates PN.
3420 // However, because we don't have dom info, we can't do a perfect job.
3421 if (Instruction *I = dyn_cast<Instruction>(V)) {
3422 // We know that the instruction dominates the PHI if there are no undef
3423 // values coming in.
Chris Lattner3b92f172004-10-18 01:48:31 +00003424 if (I->getParent() != &I->getParent()->getParent()->front() ||
3425 isa<InvokeInst>(I))
Chris Lattner107c15c2004-10-17 21:31:34 +00003426 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3427 if (isa<UndefValue>(PN.getIncomingValue(i))) {
3428 V = 0;
3429 break;
3430 }
Chris Lattnere29d6342004-10-17 21:22:38 +00003431 }
3432
3433 if (V)
3434 return ReplaceInstUsesWith(PN, V);
3435 }
Chris Lattner4db2d222004-02-16 05:07:08 +00003436
3437 // If the only user of this instruction is a cast instruction, and all of the
3438 // incoming values are constants, change this PHI to merge together the casted
3439 // constants.
3440 if (PN.hasOneUse())
3441 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3442 if (CI->getType() != PN.getType()) { // noop casts will be folded
3443 bool AllConstant = true;
3444 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3445 if (!isa<Constant>(PN.getIncomingValue(i))) {
3446 AllConstant = false;
3447 break;
3448 }
3449 if (AllConstant) {
3450 // Make a new PHI with all casted values.
3451 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3452 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3453 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3454 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3455 PN.getIncomingBlock(i));
3456 }
3457
3458 // Update the cast instruction.
3459 CI->setOperand(0, New);
3460 WorkList.push_back(CI); // revisit the cast instruction to fold.
3461 WorkList.push_back(New); // Make sure to revisit the new Phi
3462 return &PN; // PN is now dead!
3463 }
3464 }
Chris Lattner91daeb52003-12-19 05:58:40 +00003465 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003466}
3467
Chris Lattner69193f92004-04-05 01:30:19 +00003468static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3469 Instruction *InsertPoint,
3470 InstCombiner *IC) {
3471 unsigned PS = IC->getTargetData().getPointerSize();
3472 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00003473 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3474 // We must insert a cast to ensure we sign-extend.
3475 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3476 V->getName()), *InsertPoint);
3477 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3478 *InsertPoint);
3479}
3480
Chris Lattner48a44f72002-05-02 17:06:02 +00003481
Chris Lattner113f4f42002-06-25 16:13:24 +00003482Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003483 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00003484 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00003485 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003486 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00003487 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003488
Chris Lattner81a7a232004-10-16 18:11:37 +00003489 if (isa<UndefValue>(GEP.getOperand(0)))
3490 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
3491
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003492 bool HasZeroPointerIndex = false;
3493 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3494 HasZeroPointerIndex = C->isNullValue();
3495
3496 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00003497 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00003498
Chris Lattner69193f92004-04-05 01:30:19 +00003499 // Eliminate unneeded casts for indices.
3500 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00003501 gep_type_iterator GTI = gep_type_begin(GEP);
3502 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3503 if (isa<SequentialType>(*GTI)) {
3504 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3505 Value *Src = CI->getOperand(0);
3506 const Type *SrcTy = Src->getType();
3507 const Type *DestTy = CI->getType();
3508 if (Src->getType()->isInteger()) {
3509 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3510 // We can always eliminate a cast from ulong or long to the other.
3511 // We can always eliminate a cast from uint to int or the other on
3512 // 32-bit pointer platforms.
3513 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3514 MadeChange = true;
3515 GEP.setOperand(i, Src);
3516 }
3517 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3518 SrcTy->getPrimitiveSize() == 4) {
3519 // We can always eliminate a cast from int to [u]long. We can
3520 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3521 // pointer target.
3522 if (SrcTy->isSigned() ||
3523 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3524 MadeChange = true;
3525 GEP.setOperand(i, Src);
3526 }
Chris Lattner69193f92004-04-05 01:30:19 +00003527 }
3528 }
3529 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00003530 // If we are using a wider index than needed for this platform, shrink it
3531 // to what we need. If the incoming value needs a cast instruction,
3532 // insert it. This explicit cast can make subsequent optimizations more
3533 // obvious.
3534 Value *Op = GEP.getOperand(i);
3535 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003536 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00003537 GEP.setOperand(i, ConstantExpr::getCast(C,
3538 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003539 MadeChange = true;
3540 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00003541 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3542 Op->getName()), GEP);
3543 GEP.setOperand(i, Op);
3544 MadeChange = true;
3545 }
Chris Lattner44d0b952004-07-20 01:48:15 +00003546
3547 // If this is a constant idx, make sure to canonicalize it to be a signed
3548 // operand, otherwise CSE and other optimizations are pessimized.
3549 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3550 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3551 CUI->getType()->getSignedVersion()));
3552 MadeChange = true;
3553 }
Chris Lattner69193f92004-04-05 01:30:19 +00003554 }
3555 if (MadeChange) return &GEP;
3556
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003557 // Combine Indices - If the source pointer to this getelementptr instruction
3558 // is a getelementptr instruction, combine the indices of the two
3559 // getelementptr instructions into a single instruction.
3560 //
Chris Lattner57c67b02004-03-25 22:59:29 +00003561 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00003562 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003563 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00003564 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003565 if (CE->getOpcode() == Instruction::GetElementPtr)
3566 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3567 }
3568
3569 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003570 // Note that if our source is a gep chain itself that we wait for that
3571 // chain to be resolved before we perform this transformation. This
3572 // avoids us creating a TON of code in some cases.
3573 //
3574 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3575 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3576 return 0; // Wait until our source is folded to completion.
3577
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003578 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00003579
3580 // Find out whether the last index in the source GEP is a sequential idx.
3581 bool EndsWithSequential = false;
3582 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3583 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00003584 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00003585
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003586 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00003587 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00003588 // Replace: gep (gep %P, long B), long A, ...
3589 // With: T = long A+B; gep %P, T, ...
3590 //
Chris Lattner5f667a62004-05-07 22:09:22 +00003591 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00003592 if (SO1 == Constant::getNullValue(SO1->getType())) {
3593 Sum = GO1;
3594 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3595 Sum = SO1;
3596 } else {
3597 // If they aren't the same type, convert both to an integer of the
3598 // target's pointer size.
3599 if (SO1->getType() != GO1->getType()) {
3600 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3601 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3602 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3603 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3604 } else {
3605 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00003606 if (SO1->getType()->getPrimitiveSize() == PS) {
3607 // Convert GO1 to SO1's type.
3608 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3609
3610 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3611 // Convert SO1 to GO1's type.
3612 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3613 } else {
3614 const Type *PT = TD->getIntPtrType();
3615 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3616 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3617 }
3618 }
3619 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003620 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3621 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3622 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003623 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3624 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00003625 }
Chris Lattner69193f92004-04-05 01:30:19 +00003626 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003627
3628 // Recycle the GEP we already have if possible.
3629 if (SrcGEPOperands.size() == 2) {
3630 GEP.setOperand(0, SrcGEPOperands[0]);
3631 GEP.setOperand(1, Sum);
3632 return &GEP;
3633 } else {
3634 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3635 SrcGEPOperands.end()-1);
3636 Indices.push_back(Sum);
3637 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3638 }
Chris Lattner69193f92004-04-05 01:30:19 +00003639 } else if (isa<Constant>(*GEP.idx_begin()) &&
3640 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00003641 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003642 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00003643 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3644 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003645 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3646 }
3647
3648 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00003649 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003650
Chris Lattner5f667a62004-05-07 22:09:22 +00003651 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003652 // GEP of global variable. If all of the indices for this GEP are
3653 // constants, we can promote this to a constexpr instead of an instruction.
3654
3655 // Scan for nonconstants...
3656 std::vector<Constant*> Indices;
3657 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3658 for (; I != E && isa<Constant>(*I); ++I)
3659 Indices.push_back(cast<Constant>(*I));
3660
3661 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00003662 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003663
3664 // Replace all uses of the GEP with the new constexpr...
3665 return ReplaceInstUsesWith(GEP, CE);
3666 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003667 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003668 if (CE->getOpcode() == Instruction::Cast) {
3669 if (HasZeroPointerIndex) {
3670 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3671 // into : GEP [10 x ubyte]* X, long 0, ...
3672 //
3673 // This occurs when the program declares an array extern like "int X[];"
3674 //
3675 Constant *X = CE->getOperand(0);
3676 const PointerType *CPTy = cast<PointerType>(CE->getType());
3677 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3678 if (const ArrayType *XATy =
3679 dyn_cast<ArrayType>(XTy->getElementType()))
3680 if (const ArrayType *CATy =
3681 dyn_cast<ArrayType>(CPTy->getElementType()))
3682 if (CATy->getElementType() == XATy->getElementType()) {
3683 // At this point, we know that the cast source type is a pointer
3684 // to an array of the same type as the destination pointer
3685 // array. Because the array type is never stepped over (there
3686 // is a leading zero) we can fold the cast into this GEP.
3687 GEP.setOperand(0, X);
3688 return &GEP;
3689 }
3690 }
3691 }
Chris Lattnerca081252001-12-14 16:52:21 +00003692 }
3693
Chris Lattnerca081252001-12-14 16:52:21 +00003694 return 0;
3695}
3696
Chris Lattner1085bdf2002-11-04 16:18:53 +00003697Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3698 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3699 if (AI.isArrayAllocation()) // Check C != 1
3700 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3701 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003702 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00003703
3704 // Create and insert the replacement instruction...
3705 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00003706 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003707 else {
3708 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00003709 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003710 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003711
3712 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003713
3714 // Scan to the end of the allocation instructions, to skip over a block of
3715 // allocas if possible...
3716 //
3717 BasicBlock::iterator It = New;
3718 while (isa<AllocationInst>(*It)) ++It;
3719
3720 // Now that I is pointing to the first non-allocation-inst in the block,
3721 // insert our getelementptr instruction...
3722 //
Chris Lattner69193f92004-04-05 01:30:19 +00003723 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003724 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3725
3726 // Now make everything use the getelementptr instead of the original
3727 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00003728 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00003729 } else if (isa<UndefValue>(AI.getArraySize())) {
3730 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003731 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003732
3733 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3734 // Note that we only do this for alloca's, because malloc should allocate and
3735 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00003736 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3737 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00003738 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3739
Chris Lattner1085bdf2002-11-04 16:18:53 +00003740 return 0;
3741}
3742
Chris Lattner8427bff2003-12-07 01:24:23 +00003743Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3744 Value *Op = FI.getOperand(0);
3745
3746 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3747 if (CastInst *CI = dyn_cast<CastInst>(Op))
3748 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3749 FI.setOperand(0, CI->getOperand(0));
3750 return &FI;
3751 }
3752
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003753 // free undef -> unreachable.
3754 if (isa<UndefValue>(Op)) {
3755 // Insert a new store to null because we cannot modify the CFG here.
3756 new StoreInst(ConstantBool::True,
3757 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
3758 return EraseInstFromFunction(FI);
3759 }
3760
Chris Lattnerf3a36602004-02-28 04:57:37 +00003761 // If we have 'free null' delete the instruction. This can happen in stl code
3762 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003763 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00003764 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00003765
Chris Lattner8427bff2003-12-07 01:24:23 +00003766 return 0;
3767}
3768
3769
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003770/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3771/// constantexpr, return the constant value being addressed by the constant
3772/// expression, or null if something is funny.
3773///
3774static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00003775 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003776 return 0; // Do not allow stepping over the value!
3777
3778 // Loop over all of the operands, tracking down which value we are
3779 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00003780 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3781 for (++I; I != E; ++I)
3782 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3783 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3784 assert(CU->getValue() < STy->getNumElements() &&
3785 "Struct index out of range!");
3786 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003787 C = CS->getOperand(CU->getValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003788 } else if (isa<ConstantAggregateZero>(C)) {
3789 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003790 } else if (isa<UndefValue>(C)) {
3791 C = UndefValue::get(STy->getElementType(CU->getValue()));
Chris Lattnered79d8a2004-05-27 17:30:27 +00003792 } else {
3793 return 0;
3794 }
3795 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3796 const ArrayType *ATy = cast<ArrayType>(*I);
3797 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3798 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003799 C = CA->getOperand(CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003800 else if (isa<ConstantAggregateZero>(C))
3801 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00003802 else if (isa<UndefValue>(C))
3803 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003804 else
3805 return 0;
3806 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003807 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00003808 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003809 return C;
3810}
3811
Chris Lattner35e24772004-07-13 01:49:43 +00003812static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3813 User *CI = cast<User>(LI.getOperand(0));
3814
3815 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3816 if (const PointerType *SrcTy =
3817 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3818 const Type *SrcPTy = SrcTy->getElementType();
3819 if (SrcPTy->isSized() && DestPTy->isSized() &&
3820 IC.getTargetData().getTypeSize(SrcPTy) ==
3821 IC.getTargetData().getTypeSize(DestPTy) &&
3822 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3823 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3824 // Okay, we are casting from one integer or pointer type to another of
3825 // the same size. Instead of casting the pointer before the load, cast
3826 // the result of the loaded value.
3827 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003828 CI->getName(),
3829 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00003830 // Now cast the result of the load.
3831 return new CastInst(NewLoad, LI.getType());
3832 }
3833 }
3834 return 0;
3835}
3836
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003837/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00003838/// from this value cannot trap. If it is not obviously safe to load from the
3839/// specified pointer, we do a quick local scan of the basic block containing
3840/// ScanFrom, to determine if the address is already accessed.
3841static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3842 // If it is an alloca or global variable, it is always safe to load from.
3843 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3844
3845 // Otherwise, be a little bit agressive by scanning the local block where we
3846 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003847 // from/to. If so, the previous load or store would have already trapped,
3848 // so there is no harm doing an extra load (also, CSE will later eliminate
3849 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00003850 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3851
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003852 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00003853 --BBI;
3854
3855 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3856 if (LI->getOperand(0) == V) return true;
3857 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3858 if (SI->getOperand(1) == V) return true;
3859
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003860 }
Chris Lattnere6f13092004-09-19 19:18:10 +00003861 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003862}
3863
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003864Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3865 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00003866
Chris Lattner81a7a232004-10-16 18:11:37 +00003867 if (Constant *C = dyn_cast<Constant>(Op)) {
3868 if ((C->isNullValue() || isa<UndefValue>(C)) &&
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003869 !LI.isVolatile()) { // load null/undef -> undef
3870 // Insert a new store to null instruction before the load to indicate that
3871 // this code is not reachable. We do this instead of inserting an
3872 // unreachable instruction directly because we cannot modify the CFG.
3873 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00003874 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003875 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003876
Chris Lattner81a7a232004-10-16 18:11:37 +00003877 // Instcombine load (constant global) into the value loaded.
3878 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
3879 if (GV->isConstant() && !GV->isExternal())
3880 return ReplaceInstUsesWith(LI, GV->getInitializer());
3881
3882 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
3883 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
3884 if (CE->getOpcode() == Instruction::GetElementPtr) {
3885 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3886 if (GV->isConstant() && !GV->isExternal())
3887 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3888 return ReplaceInstUsesWith(LI, V);
3889 } else if (CE->getOpcode() == Instruction::Cast) {
3890 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3891 return Res;
3892 }
3893 }
Chris Lattnere228ee52004-04-08 20:39:49 +00003894
3895 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00003896 if (CastInst *CI = dyn_cast<CastInst>(Op))
3897 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3898 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00003899
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003900 if (!LI.isVolatile() && Op->hasOneUse()) {
3901 // Change select and PHI nodes to select values instead of addresses: this
3902 // helps alias analysis out a lot, allows many others simplifications, and
3903 // exposes redundancy in the code.
3904 //
3905 // Note that we cannot do the transformation unless we know that the
3906 // introduced loads cannot trap! Something like this is valid as long as
3907 // the condition is always false: load (select bool %C, int* null, int* %G),
3908 // but it would not be valid if we transformed it to load from null
3909 // unconditionally.
3910 //
3911 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3912 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00003913 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3914 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003915 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00003916 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003917 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00003918 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003919 return new SelectInst(SI->getCondition(), V1, V2);
3920 }
3921
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00003922 // load (select (cond, null, P)) -> load P
3923 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3924 if (C->isNullValue()) {
3925 LI.setOperand(0, SI->getOperand(2));
3926 return &LI;
3927 }
3928
3929 // load (select (cond, P, null)) -> load P
3930 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3931 if (C->isNullValue()) {
3932 LI.setOperand(0, SI->getOperand(1));
3933 return &LI;
3934 }
3935
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003936 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3937 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00003938 bool Safe = PN->getParent() == LI.getParent();
3939
3940 // Scan all of the instructions between the PHI and the load to make
3941 // sure there are no instructions that might possibly alter the value
3942 // loaded from the PHI.
3943 if (Safe) {
3944 BasicBlock::iterator I = &LI;
3945 for (--I; !isa<PHINode>(I); --I)
3946 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3947 Safe = false;
3948 break;
3949 }
3950 }
3951
3952 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00003953 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00003954 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003955 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00003956
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003957 if (Safe) {
3958 // Create the PHI.
3959 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3960 InsertNewInstBefore(NewPN, *PN);
3961 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3962
3963 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3964 BasicBlock *BB = PN->getIncomingBlock(i);
3965 Value *&TheLoad = LoadMap[BB];
3966 if (TheLoad == 0) {
3967 Value *InVal = PN->getIncomingValue(i);
3968 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3969 InVal->getName()+".val"),
3970 *BB->getTerminator());
3971 }
3972 NewPN->addIncoming(TheLoad, BB);
3973 }
3974 return ReplaceInstUsesWith(LI, NewPN);
3975 }
3976 }
3977 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003978 return 0;
3979}
3980
Chris Lattner9eef8a72003-06-04 04:46:00 +00003981Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3982 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00003983 Value *X;
3984 BasicBlock *TrueDest;
3985 BasicBlock *FalseDest;
3986 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3987 !isa<Constant>(X)) {
3988 // Swap Destinations and condition...
3989 BI.setCondition(X);
3990 BI.setSuccessor(0, FalseDest);
3991 BI.setSuccessor(1, TrueDest);
3992 return &BI;
3993 }
3994
3995 // Cannonicalize setne -> seteq
3996 Instruction::BinaryOps Op; Value *Y;
3997 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3998 TrueDest, FalseDest)))
3999 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
4000 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
4001 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
4002 std::string Name = I->getName(); I->setName("");
4003 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
4004 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00004005 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00004006 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00004007 BI.setSuccessor(0, FalseDest);
4008 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004009 removeFromWorkList(I);
4010 I->getParent()->getInstList().erase(I);
4011 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00004012 return &BI;
4013 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00004014
Chris Lattner9eef8a72003-06-04 04:46:00 +00004015 return 0;
4016}
Chris Lattner1085bdf2002-11-04 16:18:53 +00004017
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004018Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4019 Value *Cond = SI.getCondition();
4020 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4021 if (I->getOpcode() == Instruction::Add)
4022 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4023 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4024 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00004025 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004026 AddRHS));
4027 SI.setOperand(0, I->getOperand(0));
4028 WorkList.push_back(I);
4029 return &SI;
4030 }
4031 }
4032 return 0;
4033}
4034
Chris Lattnerca081252001-12-14 16:52:21 +00004035
Chris Lattner99f48c62002-09-02 04:59:56 +00004036void InstCombiner::removeFromWorkList(Instruction *I) {
4037 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4038 WorkList.end());
4039}
4040
Chris Lattner113f4f42002-06-25 16:13:24 +00004041bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00004042 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004043 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00004044
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004045 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
4046 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00004047
Chris Lattnerca081252001-12-14 16:52:21 +00004048
4049 while (!WorkList.empty()) {
4050 Instruction *I = WorkList.back(); // Get an instruction from the worklist
4051 WorkList.pop_back();
4052
Misha Brukman632df282002-10-29 23:06:16 +00004053 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00004054 // Check to see if we can DIE the instruction...
4055 if (isInstructionTriviallyDead(I)) {
4056 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004057 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00004058 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00004059 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004060
4061 I->getParent()->getInstList().erase(I);
4062 removeFromWorkList(I);
4063 continue;
4064 }
Chris Lattner99f48c62002-09-02 04:59:56 +00004065
Misha Brukman632df282002-10-29 23:06:16 +00004066 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00004067 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner6580e092004-10-16 19:44:59 +00004068 if (isa<GetElementPtrInst>(I) &&
4069 cast<Constant>(I->getOperand(0))->isNullValue() &&
4070 !isa<ConstantPointerNull>(C)) {
4071 // If this is a constant expr gep that is effectively computing an
4072 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
4073 bool isFoldableGEP = true;
4074 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
4075 if (!isa<ConstantInt>(I->getOperand(i)))
4076 isFoldableGEP = false;
4077 if (isFoldableGEP) {
4078 uint64_t Offset = TD->getIndexedOffset(I->getOperand(0)->getType(),
4079 std::vector<Value*>(I->op_begin()+1, I->op_end()));
4080 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00004081 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00004082 C = ConstantExpr::getCast(C, I->getType());
4083 }
4084 }
4085
Chris Lattner99f48c62002-09-02 04:59:56 +00004086 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00004087 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00004088 ReplaceInstUsesWith(*I, C);
4089
Chris Lattner99f48c62002-09-02 04:59:56 +00004090 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004091 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00004092 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004093 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00004094 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004095
Chris Lattnerca081252001-12-14 16:52:21 +00004096 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004097 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00004098 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00004099 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00004100 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004101 DEBUG(std::cerr << "IC: Old = " << *I
4102 << " New = " << *Result);
4103
Chris Lattner396dbfe2004-06-09 05:08:07 +00004104 // Everything uses the new instruction now.
4105 I->replaceAllUsesWith(Result);
4106
4107 // Push the new instruction and any users onto the worklist.
4108 WorkList.push_back(Result);
4109 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004110
4111 // Move the name to the new instruction first...
4112 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00004113 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004114
4115 // Insert the new instruction into the basic block...
4116 BasicBlock *InstParent = I->getParent();
4117 InstParent->getInstList().insert(I, Result);
4118
Chris Lattner63d75af2004-05-01 23:27:23 +00004119 // Make sure that we reprocess all operands now that we reduced their
4120 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004121 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4122 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4123 WorkList.push_back(OpI);
4124
Chris Lattner396dbfe2004-06-09 05:08:07 +00004125 // Instructions can end up on the worklist more than once. Make sure
4126 // we do not process an instruction that has been deleted.
4127 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004128
4129 // Erase the old instruction.
4130 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004131 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004132 DEBUG(std::cerr << "IC: MOD = " << *I);
4133
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004134 // If the instruction was modified, it's possible that it is now dead.
4135 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00004136 if (isInstructionTriviallyDead(I)) {
4137 // Make sure we process all operands now that we are reducing their
4138 // use counts.
4139 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4140 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4141 WorkList.push_back(OpI);
4142
4143 // Instructions may end up in the worklist more than once. Erase all
4144 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00004145 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00004146 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00004147 } else {
4148 WorkList.push_back(Result);
4149 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004150 }
Chris Lattner053c0932002-05-14 15:24:07 +00004151 }
Chris Lattner260ab202002-04-18 17:39:14 +00004152 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00004153 }
4154 }
4155
Chris Lattner260ab202002-04-18 17:39:14 +00004156 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00004157}
4158
Brian Gaeke38b79e82004-07-27 17:43:21 +00004159FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00004160 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00004161}
Brian Gaeke960707c2003-11-11 22:41:34 +00004162