blob: f8f0573395dfc85473057efa11faa588596c95fc [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;
575 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 Lattnerb9cde762003-10-02 15:11:26 +0000621 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000622 Value *X;
623 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
624 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
625 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000626 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000627
Chris Lattnerbff91d92004-10-08 05:07:56 +0000628 // (X & FF00) + xx00 -> (X+xx00) & FF00
629 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
630 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
631 if (Anded == CRHS) {
632 // See if all bits from the first bit set in the Add RHS up are included
633 // in the mask. First, get the rightmost bit.
634 uint64_t AddRHSV = CRHS->getRawValue();
635
636 // Form a mask of all bits from the lowest bit added through the top.
637 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
638 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
639
640 // See if the and mask includes all of these bits.
641 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
642
643 if (AddRHSHighBits == AddRHSHighBitsAnd) {
644 // Okay, the xform is safe. Insert the new add pronto.
645 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
646 LHS->getName()), I);
647 return BinaryOperator::createAnd(NewAdd, C2);
648 }
649 }
650 }
651
652
Chris Lattnerd4252a72004-07-30 07:50:03 +0000653 // Try to fold constant add into select arguments.
654 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
655 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
656 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000657 }
658
Chris Lattner113f4f42002-06-25 16:13:24 +0000659 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000660}
661
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000662// isSignBit - Return true if the value represented by the constant only has the
663// highest order bit set.
664static bool isSignBit(ConstantInt *CI) {
665 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
666 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
667}
668
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000669static unsigned getTypeSizeInBits(const Type *Ty) {
670 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
671}
672
Chris Lattner022167f2004-03-13 00:11:49 +0000673/// RemoveNoopCast - Strip off nonconverting casts from the value.
674///
675static Value *RemoveNoopCast(Value *V) {
676 if (CastInst *CI = dyn_cast<CastInst>(V)) {
677 const Type *CTy = CI->getType();
678 const Type *OpTy = CI->getOperand(0)->getType();
679 if (CTy->isInteger() && OpTy->isInteger()) {
680 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
681 return RemoveNoopCast(CI->getOperand(0));
682 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
683 return RemoveNoopCast(CI->getOperand(0));
684 }
685 return V;
686}
687
Chris Lattner113f4f42002-06-25 16:13:24 +0000688Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000689 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000690
Chris Lattnere6794492002-08-12 21:17:25 +0000691 if (Op0 == Op1) // sub X, X -> 0
692 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000693
Chris Lattnere6794492002-08-12 21:17:25 +0000694 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000695 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000696 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000697
Chris Lattner81a7a232004-10-16 18:11:37 +0000698 if (isa<UndefValue>(Op0))
699 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
700 if (isa<UndefValue>(Op1))
701 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
702
Chris Lattner8f2f5982003-11-05 01:06:05 +0000703 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
704 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000705 if (C->isAllOnesValue())
706 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000707
Chris Lattner8f2f5982003-11-05 01:06:05 +0000708 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000709 Value *X;
710 if (match(Op1, m_Not(m_Value(X))))
711 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000712 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000713 // -((uint)X >> 31) -> ((int)X >> 31)
714 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000715 if (C->isNullValue()) {
716 Value *NoopCastedRHS = RemoveNoopCast(Op1);
717 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000718 if (SI->getOpcode() == Instruction::Shr)
719 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
720 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000721 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000722 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000723 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000724 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000725 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000726 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000727 // Ok, the transformation is safe. Insert a cast of the incoming
728 // value, then the new shift, then the new cast.
729 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
730 SI->getOperand(0)->getName());
731 Value *InV = InsertNewInstBefore(FirstCast, I);
732 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
733 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000734 if (NewShift->getType() == I.getType())
735 return NewShift;
736 else {
737 InV = InsertNewInstBefore(NewShift, I);
738 return new CastInst(NewShift, I.getType());
739 }
Chris Lattner92295c52004-03-12 23:53:13 +0000740 }
741 }
Chris Lattner022167f2004-03-13 00:11:49 +0000742 }
Chris Lattner183b3362004-04-09 19:05:30 +0000743
744 // Try to fold constant sub into select arguments.
745 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
746 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
747 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000748
749 if (isa<PHINode>(Op0))
750 if (Instruction *NV = FoldOpIntoPhi(I))
751 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000752 }
753
Chris Lattner3082c5a2003-02-18 19:28:33 +0000754 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000755 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000756 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
757 // is not used by anyone else...
758 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000759 if (Op1I->getOpcode() == Instruction::Sub &&
760 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000761 // Swap the two operands of the subexpr...
762 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
763 Op1I->setOperand(0, IIOp1);
764 Op1I->setOperand(1, IIOp0);
765
766 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000767 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000768 }
769
770 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
771 //
772 if (Op1I->getOpcode() == Instruction::And &&
773 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
774 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
775
Chris Lattner396dbfe2004-06-09 05:08:07 +0000776 Value *NewNot =
777 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000778 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000779 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000780
Chris Lattner0aee4b72004-10-06 15:08:25 +0000781 // -(X sdiv C) -> (X sdiv -C)
782 if (Op1I->getOpcode() == Instruction::Div)
783 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
784 if (CSI->getValue() == 0)
785 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
786 return BinaryOperator::createDiv(Op1I->getOperand(0),
787 ConstantExpr::getNeg(DivRHS));
788
Chris Lattner57c8d992003-02-18 19:57:07 +0000789 // X - X*C --> X * (1-C)
790 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000791 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000792 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner34428442003-05-27 16:40:51 +0000793 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000794 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000795 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000796 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000797 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000798
Chris Lattner57c8d992003-02-18 19:57:07 +0000799 // X*C - X --> X * (C-1)
800 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000801 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000802 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner34428442003-05-27 16:40:51 +0000803 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000804 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000805 return BinaryOperator::createMul(Op1, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000806 }
807
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000808 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000809}
810
Chris Lattnere79e8542004-02-23 06:38:22 +0000811/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
812/// really just returns true if the most significant (sign) bit is set.
813static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
814 if (RHS->getType()->isSigned()) {
815 // True if source is LHS < 0 or LHS <= -1
816 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
817 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
818 } else {
819 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
820 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
821 // the size of the integer type.
822 if (Opcode == Instruction::SetGE)
823 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
824 if (Opcode == Instruction::SetGT)
825 return RHSC->getValue() ==
826 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
827 }
828 return false;
829}
830
Chris Lattner113f4f42002-06-25 16:13:24 +0000831Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000832 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000833 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000834
Chris Lattner81a7a232004-10-16 18:11:37 +0000835 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
836 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
837
Chris Lattnere6794492002-08-12 21:17:25 +0000838 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000839 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
840 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000841
842 // ((X << C1)*C2) == (X * (C2 << C1))
843 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
844 if (SI->getOpcode() == Instruction::Shl)
845 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000846 return BinaryOperator::createMul(SI->getOperand(0),
847 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000848
Chris Lattnercce81be2003-09-11 22:24:54 +0000849 if (CI->isNullValue())
850 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
851 if (CI->equalsInt(1)) // X * 1 == X
852 return ReplaceInstUsesWith(I, Op0);
853 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000854 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000855
Chris Lattnercce81be2003-09-11 22:24:54 +0000856 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000857 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
858 return new ShiftInst(Instruction::Shl, Op0,
859 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000860 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000861 if (Op1F->isNullValue())
862 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000863
Chris Lattner3082c5a2003-02-18 19:28:33 +0000864 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
865 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
866 if (Op1F->getValue() == 1.0)
867 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
868 }
Chris Lattner183b3362004-04-09 19:05:30 +0000869
870 // Try to fold constant mul into select arguments.
871 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
872 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
873 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000874
875 if (isa<PHINode>(Op0))
876 if (Instruction *NV = FoldOpIntoPhi(I))
877 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000878 }
879
Chris Lattner934a64cf2003-03-10 23:23:04 +0000880 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
881 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000882 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000883
Chris Lattner2635b522004-02-23 05:39:21 +0000884 // If one of the operands of the multiply is a cast from a boolean value, then
885 // we know the bool is either zero or one, so this is a 'masking' multiply.
886 // See if we can simplify things based on how the boolean was originally
887 // formed.
888 CastInst *BoolCast = 0;
889 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
890 if (CI->getOperand(0)->getType() == Type::BoolTy)
891 BoolCast = CI;
892 if (!BoolCast)
893 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
894 if (CI->getOperand(0)->getType() == Type::BoolTy)
895 BoolCast = CI;
896 if (BoolCast) {
897 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
898 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
899 const Type *SCOpTy = SCIOp0->getType();
900
Chris Lattnere79e8542004-02-23 06:38:22 +0000901 // If the setcc is true iff the sign bit of X is set, then convert this
902 // multiply into a shift/and combination.
903 if (isa<ConstantInt>(SCIOp1) &&
904 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000905 // Shift the X value right to turn it into "all signbits".
906 Constant *Amt = ConstantUInt::get(Type::UByteTy,
907 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000908 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000909 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000910 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
911 SCIOp0->getName()), I);
912 }
913
914 Value *V =
915 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
916 BoolCast->getOperand(0)->getName()+
917 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000918
919 // If the multiply type is not the same as the source type, sign extend
920 // or truncate to the multiply type.
921 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000922 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000923
924 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000925 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000926 }
927 }
928 }
929
Chris Lattner113f4f42002-06-25 16:13:24 +0000930 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000931}
932
Chris Lattner113f4f42002-06-25 16:13:24 +0000933Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000934 if (isa<UndefValue>(I.getOperand(0))) // undef / X -> 0
935 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
936 if (isa<UndefValue>(I.getOperand(1)))
937 return ReplaceInstUsesWith(I, I.getOperand(1)); // X / undef -> undef
938
Chris Lattner3082c5a2003-02-18 19:28:33 +0000939 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000940 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000941 if (RHS->equalsInt(1))
942 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000943
Chris Lattnere20c3342004-04-26 14:01:59 +0000944 // div X, -1 == -X
945 if (RHS->isAllOnesValue())
946 return BinaryOperator::createNeg(I.getOperand(0));
947
Chris Lattner272d5ca2004-09-28 18:22:15 +0000948 if (Instruction *LHS = dyn_cast<Instruction>(I.getOperand(0)))
949 if (LHS->getOpcode() == Instruction::Div)
950 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +0000951 // (X / C1) / C2 -> X / (C1*C2)
952 return BinaryOperator::createDiv(LHS->getOperand(0),
953 ConstantExpr::getMul(RHS, LHSRHS));
954 }
955
Chris Lattner3082c5a2003-02-18 19:28:33 +0000956 // Check to see if this is an unsigned division with an exact power of 2,
957 // if so, convert to a right shift.
958 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
959 if (uint64_t Val = C->getValue()) // Don't break X / 0
960 if (uint64_t C = Log2(Val))
961 return new ShiftInst(Instruction::Shr, I.getOperand(0),
962 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000963
Chris Lattner4ad08352004-10-09 02:50:40 +0000964 // -X/C -> X/-C
965 if (RHS->getType()->isSigned())
966 if (Value *LHSNeg = dyn_castNegVal(I.getOperand(0)))
967 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
968
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000969 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
970 if (Instruction *NV = FoldOpIntoPhi(I))
971 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000972 }
973
974 // 0 / X == 0, we don't need to preserve faults!
975 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
976 if (LHS->equalsInt(0))
977 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
978
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000979 return 0;
980}
981
982
Chris Lattner113f4f42002-06-25 16:13:24 +0000983Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000984 if (I.getType()->isSigned())
985 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner98c6bdf2004-07-06 07:11:42 +0000986 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +0000987 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000988 // X % -Y -> X % Y
989 AddUsesToWorkList(I);
990 I.setOperand(1, RHSNeg);
991 return &I;
992 }
993
Chris Lattner81a7a232004-10-16 18:11:37 +0000994 if (isa<UndefValue>(I.getOperand(0))) // undef % X -> 0
995 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
996 if (isa<UndefValue>(I.getOperand(1)))
997 return ReplaceInstUsesWith(I, I.getOperand(1)); // X % undef -> undef
998
Chris Lattner3082c5a2003-02-18 19:28:33 +0000999 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
1000 if (RHS->equalsInt(1)) // X % 1 == 0
1001 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1002
1003 // Check to see if this is an unsigned remainder with an exact power of 2,
1004 // if so, convert to a bitwise and.
1005 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1006 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001007 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001008 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattner3082c5a2003-02-18 19:28:33 +00001009 ConstantUInt::get(I.getType(), Val-1));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001010 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
1011 if (Instruction *NV = FoldOpIntoPhi(I))
1012 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +00001013 }
1014
1015 // 0 % X == 0, we don't need to preserve faults!
1016 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
1017 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001018 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1019
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001020 return 0;
1021}
1022
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001023// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001024static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001025 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1026 // Calculate -1 casted to the right type...
1027 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1028 uint64_t Val = ~0ULL; // All ones
1029 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1030 return CU->getValue() == Val-1;
1031 }
1032
1033 const ConstantSInt *CS = cast<ConstantSInt>(C);
1034
1035 // Calculate 0111111111..11111
1036 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1037 int64_t Val = INT64_MAX; // All ones
1038 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1039 return CS->getValue() == Val-1;
1040}
1041
1042// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001043static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001044 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1045 return CU->getValue() == 1;
1046
1047 const ConstantSInt *CS = cast<ConstantSInt>(C);
1048
1049 // Calculate 1111111111000000000000
1050 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1051 int64_t Val = -1; // All ones
1052 Val <<= TypeBits-1; // Shift over to the right spot
1053 return CS->getValue() == Val+1;
1054}
1055
Chris Lattner35167c32004-06-09 07:59:58 +00001056// isOneBitSet - Return true if there is exactly one bit set in the specified
1057// constant.
1058static bool isOneBitSet(const ConstantInt *CI) {
1059 uint64_t V = CI->getRawValue();
1060 return V && (V & (V-1)) == 0;
1061}
1062
Chris Lattner8fc5af42004-09-23 21:46:38 +00001063#if 0 // Currently unused
1064// isLowOnes - Return true if the constant is of the form 0+1+.
1065static bool isLowOnes(const ConstantInt *CI) {
1066 uint64_t V = CI->getRawValue();
1067
1068 // There won't be bits set in parts that the type doesn't contain.
1069 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1070
1071 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1072 return U && V && (U & V) == 0;
1073}
1074#endif
1075
1076// isHighOnes - Return true if the constant is of the form 1+0+.
1077// This is the same as lowones(~X).
1078static bool isHighOnes(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
1088
Chris Lattner3ac7c262003-08-13 20:16:26 +00001089/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1090/// are carefully arranged to allow folding of expressions such as:
1091///
1092/// (A < B) | (A > B) --> (A != B)
1093///
1094/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1095/// represents that the comparison is true if A == B, and bit value '1' is true
1096/// if A < B.
1097///
1098static unsigned getSetCondCode(const SetCondInst *SCI) {
1099 switch (SCI->getOpcode()) {
1100 // False -> 0
1101 case Instruction::SetGT: return 1;
1102 case Instruction::SetEQ: return 2;
1103 case Instruction::SetGE: return 3;
1104 case Instruction::SetLT: return 4;
1105 case Instruction::SetNE: return 5;
1106 case Instruction::SetLE: return 6;
1107 // True -> 7
1108 default:
1109 assert(0 && "Invalid SetCC opcode!");
1110 return 0;
1111 }
1112}
1113
1114/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1115/// opcode and two operands into either a constant true or false, or a brand new
1116/// SetCC instruction.
1117static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1118 switch (Opcode) {
1119 case 0: return ConstantBool::False;
1120 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1121 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1122 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1123 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1124 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1125 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1126 case 7: return ConstantBool::True;
1127 default: assert(0 && "Illegal SetCCCode!"); return 0;
1128 }
1129}
1130
1131// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1132struct FoldSetCCLogical {
1133 InstCombiner &IC;
1134 Value *LHS, *RHS;
1135 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1136 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1137 bool shouldApply(Value *V) const {
1138 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1139 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1140 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1141 return false;
1142 }
1143 Instruction *apply(BinaryOperator &Log) const {
1144 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1145 if (SCI->getOperand(0) != LHS) {
1146 assert(SCI->getOperand(1) == LHS);
1147 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1148 }
1149
1150 unsigned LHSCode = getSetCondCode(SCI);
1151 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1152 unsigned Code;
1153 switch (Log.getOpcode()) {
1154 case Instruction::And: Code = LHSCode & RHSCode; break;
1155 case Instruction::Or: Code = LHSCode | RHSCode; break;
1156 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001157 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001158 }
1159
1160 Value *RV = getSetCCValue(Code, LHS, RHS);
1161 if (Instruction *I = dyn_cast<Instruction>(RV))
1162 return I;
1163 // Otherwise, it's a constant boolean value...
1164 return IC.ReplaceInstUsesWith(Log, RV);
1165 }
1166};
1167
1168
Chris Lattnerba1cb382003-09-19 17:17:26 +00001169// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1170// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1171// guaranteed to be either a shift instruction or a binary operator.
1172Instruction *InstCombiner::OptAndOp(Instruction *Op,
1173 ConstantIntegral *OpRHS,
1174 ConstantIntegral *AndRHS,
1175 BinaryOperator &TheAnd) {
1176 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001177 Constant *Together = 0;
1178 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001179 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001180
Chris Lattnerba1cb382003-09-19 17:17:26 +00001181 switch (Op->getOpcode()) {
1182 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001183 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001184 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001185 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001186 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001187 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1188 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001189 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001190 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001191 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001192 }
1193 break;
1194 case Instruction::Or:
1195 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001196 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001197 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001198 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001199 if (Together == AndRHS) // (X | C) & C --> C
1200 return ReplaceInstUsesWith(TheAnd, AndRHS);
1201
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001202 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001203 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1204 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001205 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001206 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001207 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001208 }
1209 }
1210 break;
1211 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001212 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001213 // Adding a one to a single bit bit-field should be turned into an XOR
1214 // of the bit. First thing to check is to see if this AND is with a
1215 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001216 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001217
1218 // Clear bits that are not part of the constant.
1219 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1220
1221 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001222 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001223 // Ok, at this point, we know that we are masking the result of the
1224 // ADD down to exactly one bit. If the constant we are adding has
1225 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001226 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001227
1228 // Check to see if any bits below the one bit set in AndRHSV are set.
1229 if ((AddRHS & (AndRHSV-1)) == 0) {
1230 // If not, the only thing that can effect the output of the AND is
1231 // the bit specified by AndRHSV. If that bit is set, the effect of
1232 // the XOR is to toggle the bit. If it is clear, then the ADD has
1233 // no effect.
1234 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1235 TheAnd.setOperand(0, X);
1236 return &TheAnd;
1237 } else {
1238 std::string Name = Op->getName(); Op->setName("");
1239 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001240 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001241 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001242 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001243 }
1244 }
1245 }
1246 }
1247 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001248
1249 case Instruction::Shl: {
1250 // We know that the AND will not produce any of the bits shifted in, so if
1251 // the anded constant includes them, clear them now!
1252 //
1253 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001254 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1255 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1256
1257 if (CI == ShlMask) { // Masking out bits that the shift already masks
1258 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1259 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001260 TheAnd.setOperand(1, CI);
1261 return &TheAnd;
1262 }
1263 break;
1264 }
1265 case Instruction::Shr:
1266 // We know that the AND will not produce any of the bits shifted in, so if
1267 // the anded constant includes them, clear them now! This only applies to
1268 // unsigned shifts, because a signed shr may bring in set bits!
1269 //
1270 if (AndRHS->getType()->isUnsigned()) {
1271 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001272 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1273 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1274
1275 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1276 return ReplaceInstUsesWith(TheAnd, Op);
1277 } else if (CI != AndRHS) {
1278 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001279 return &TheAnd;
1280 }
Chris Lattner7e794272004-09-24 15:21:34 +00001281 } else { // Signed shr.
1282 // See if this is shifting in some sign extension, then masking it out
1283 // with an and.
1284 if (Op->hasOneUse()) {
1285 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1286 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1287 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001288 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001289 // Make the argument unsigned.
1290 Value *ShVal = Op->getOperand(0);
1291 ShVal = InsertCastBefore(ShVal,
1292 ShVal->getType()->getUnsignedVersion(),
1293 TheAnd);
1294 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1295 OpRHS, Op->getName()),
1296 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001297 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1298 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1299 TheAnd.getName()),
1300 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001301 return new CastInst(ShVal, Op->getType());
1302 }
1303 }
Chris Lattner2da29172003-09-19 19:05:02 +00001304 }
1305 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001306 }
1307 return 0;
1308}
1309
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001310
Chris Lattner6862fbd2004-09-29 17:40:11 +00001311/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1312/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1313/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1314/// insert new instructions.
1315Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1316 bool Inside, Instruction &IB) {
1317 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1318 "Lo is not <= Hi in range emission code!");
1319 if (Inside) {
1320 if (Lo == Hi) // Trivially false.
1321 return new SetCondInst(Instruction::SetNE, V, V);
1322 if (cast<ConstantIntegral>(Lo)->isMinValue())
1323 return new SetCondInst(Instruction::SetLT, V, Hi);
1324
1325 Constant *AddCST = ConstantExpr::getNeg(Lo);
1326 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1327 InsertNewInstBefore(Add, IB);
1328 // Convert to unsigned for the comparison.
1329 const Type *UnsType = Add->getType()->getUnsignedVersion();
1330 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1331 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1332 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1333 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1334 }
1335
1336 if (Lo == Hi) // Trivially true.
1337 return new SetCondInst(Instruction::SetEQ, V, V);
1338
1339 Hi = SubOne(cast<ConstantInt>(Hi));
1340 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1341 return new SetCondInst(Instruction::SetGT, V, Hi);
1342
1343 // Emit X-Lo > Hi-Lo-1
1344 Constant *AddCST = ConstantExpr::getNeg(Lo);
1345 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1346 InsertNewInstBefore(Add, IB);
1347 // Convert to unsigned for the comparison.
1348 const Type *UnsType = Add->getType()->getUnsignedVersion();
1349 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1350 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1351 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1352 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1353}
1354
1355
Chris Lattner113f4f42002-06-25 16:13:24 +00001356Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001357 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001358 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001359
Chris Lattner81a7a232004-10-16 18:11:37 +00001360 if (isa<UndefValue>(Op1)) // X & undef -> 0
1361 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1362
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001363 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001364 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1365 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001366
1367 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001368 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001369 if (RHS->isAllOnesValue())
1370 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001371
Chris Lattnerba1cb382003-09-19 17:17:26 +00001372 // Optimize a variety of ((val OP C1) & C2) combinations...
1373 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1374 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001375 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001376 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001377 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1378 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001379 }
Chris Lattner183b3362004-04-09 19:05:30 +00001380
1381 // Try to fold constant and into select arguments.
1382 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1383 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1384 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001385 if (isa<PHINode>(Op0))
1386 if (Instruction *NV = FoldOpIntoPhi(I))
1387 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001388 }
1389
Chris Lattnerbb74e222003-03-10 23:06:50 +00001390 Value *Op0NotVal = dyn_castNotVal(Op0);
1391 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001392
Chris Lattner023a4832004-06-18 06:07:51 +00001393 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1394 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1395
Misha Brukman9c003d82004-07-30 12:50:08 +00001396 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001397 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001398 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1399 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001400 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001401 return BinaryOperator::createNot(Or);
1402 }
1403
Chris Lattner623826c2004-09-28 21:48:02 +00001404 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1405 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001406 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1407 return R;
1408
Chris Lattner623826c2004-09-28 21:48:02 +00001409 Value *LHSVal, *RHSVal;
1410 ConstantInt *LHSCst, *RHSCst;
1411 Instruction::BinaryOps LHSCC, RHSCC;
1412 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1413 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1414 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1415 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1416 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1417 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1418 // Ensure that the larger constant is on the RHS.
1419 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1420 SetCondInst *LHS = cast<SetCondInst>(Op0);
1421 if (cast<ConstantBool>(Cmp)->getValue()) {
1422 std::swap(LHS, RHS);
1423 std::swap(LHSCst, RHSCst);
1424 std::swap(LHSCC, RHSCC);
1425 }
1426
1427 // At this point, we know we have have two setcc instructions
1428 // comparing a value against two constants and and'ing the result
1429 // together. Because of the above check, we know that we only have
1430 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1431 // FoldSetCCLogical check above), that the two constants are not
1432 // equal.
1433 assert(LHSCst != RHSCst && "Compares not folded above?");
1434
1435 switch (LHSCC) {
1436 default: assert(0 && "Unknown integer condition code!");
1437 case Instruction::SetEQ:
1438 switch (RHSCC) {
1439 default: assert(0 && "Unknown integer condition code!");
1440 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1441 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1442 return ReplaceInstUsesWith(I, ConstantBool::False);
1443 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1444 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1445 return ReplaceInstUsesWith(I, LHS);
1446 }
1447 case Instruction::SetNE:
1448 switch (RHSCC) {
1449 default: assert(0 && "Unknown integer condition code!");
1450 case Instruction::SetLT:
1451 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1452 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1453 break; // (X != 13 & X < 15) -> no change
1454 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1455 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1456 return ReplaceInstUsesWith(I, RHS);
1457 case Instruction::SetNE:
1458 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1459 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1460 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1461 LHSVal->getName()+".off");
1462 InsertNewInstBefore(Add, I);
1463 const Type *UnsType = Add->getType()->getUnsignedVersion();
1464 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1465 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1466 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1467 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1468 }
1469 break; // (X != 13 & X != 15) -> no change
1470 }
1471 break;
1472 case Instruction::SetLT:
1473 switch (RHSCC) {
1474 default: assert(0 && "Unknown integer condition code!");
1475 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1476 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1477 return ReplaceInstUsesWith(I, ConstantBool::False);
1478 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1479 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1480 return ReplaceInstUsesWith(I, LHS);
1481 }
1482 case Instruction::SetGT:
1483 switch (RHSCC) {
1484 default: assert(0 && "Unknown integer condition code!");
1485 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1486 return ReplaceInstUsesWith(I, LHS);
1487 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1488 return ReplaceInstUsesWith(I, RHS);
1489 case Instruction::SetNE:
1490 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1491 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1492 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001493 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1494 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001495 }
1496 }
1497 }
1498 }
1499
Chris Lattner113f4f42002-06-25 16:13:24 +00001500 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001501}
1502
Chris Lattner113f4f42002-06-25 16:13:24 +00001503Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001504 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001505 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001506
Chris Lattner81a7a232004-10-16 18:11:37 +00001507 if (isa<UndefValue>(Op1))
1508 return ReplaceInstUsesWith(I, // X | undef -> -1
1509 ConstantIntegral::getAllOnesValue(I.getType()));
1510
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001511 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001512 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1513 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001514
1515 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001516 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001517 if (RHS->isAllOnesValue())
1518 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001519
Chris Lattnerd4252a72004-07-30 07:50:03 +00001520 ConstantInt *C1; Value *X;
1521 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1522 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1523 std::string Op0Name = Op0->getName(); Op0->setName("");
1524 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1525 InsertNewInstBefore(Or, I);
1526 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1527 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001528
Chris Lattnerd4252a72004-07-30 07:50:03 +00001529 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1530 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1531 std::string Op0Name = Op0->getName(); Op0->setName("");
1532 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1533 InsertNewInstBefore(Or, I);
1534 return BinaryOperator::createXor(Or,
1535 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001536 }
Chris Lattner183b3362004-04-09 19:05:30 +00001537
1538 // Try to fold constant and into select arguments.
1539 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1540 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1541 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001542 if (isa<PHINode>(Op0))
1543 if (Instruction *NV = FoldOpIntoPhi(I))
1544 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001545 }
1546
Chris Lattner812aab72003-08-12 19:11:07 +00001547 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001548 Value *A, *B; ConstantInt *C1, *C2;
1549 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1550 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1551 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001552
Chris Lattnerd4252a72004-07-30 07:50:03 +00001553 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1554 if (A == Op1) // ~A | A == -1
1555 return ReplaceInstUsesWith(I,
1556 ConstantIntegral::getAllOnesValue(I.getType()));
1557 } else {
1558 A = 0;
1559 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001560
Chris Lattnerd4252a72004-07-30 07:50:03 +00001561 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1562 if (Op0 == B)
1563 return ReplaceInstUsesWith(I,
1564 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001565
Misha Brukman9c003d82004-07-30 12:50:08 +00001566 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001567 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1568 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1569 I.getName()+".demorgan"), I);
1570 return BinaryOperator::createNot(And);
1571 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001572 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001573
Chris Lattner3ac7c262003-08-13 20:16:26 +00001574 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001575 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001576 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1577 return R;
1578
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001579 Value *LHSVal, *RHSVal;
1580 ConstantInt *LHSCst, *RHSCst;
1581 Instruction::BinaryOps LHSCC, RHSCC;
1582 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1583 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1584 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1585 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1586 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1587 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1588 // Ensure that the larger constant is on the RHS.
1589 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1590 SetCondInst *LHS = cast<SetCondInst>(Op0);
1591 if (cast<ConstantBool>(Cmp)->getValue()) {
1592 std::swap(LHS, RHS);
1593 std::swap(LHSCst, RHSCst);
1594 std::swap(LHSCC, RHSCC);
1595 }
1596
1597 // At this point, we know we have have two setcc instructions
1598 // comparing a value against two constants and or'ing the result
1599 // together. Because of the above check, we know that we only have
1600 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1601 // FoldSetCCLogical check above), that the two constants are not
1602 // equal.
1603 assert(LHSCst != RHSCst && "Compares not folded above?");
1604
1605 switch (LHSCC) {
1606 default: assert(0 && "Unknown integer condition code!");
1607 case Instruction::SetEQ:
1608 switch (RHSCC) {
1609 default: assert(0 && "Unknown integer condition code!");
1610 case Instruction::SetEQ:
1611 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1612 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1613 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1614 LHSVal->getName()+".off");
1615 InsertNewInstBefore(Add, I);
1616 const Type *UnsType = Add->getType()->getUnsignedVersion();
1617 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1618 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1619 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1620 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1621 }
1622 break; // (X == 13 | X == 15) -> no change
1623
1624 case Instruction::SetGT:
1625 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1626 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1627 break; // (X == 13 | X > 15) -> no change
1628 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1629 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1630 return ReplaceInstUsesWith(I, RHS);
1631 }
1632 break;
1633 case Instruction::SetNE:
1634 switch (RHSCC) {
1635 default: assert(0 && "Unknown integer condition code!");
1636 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1637 return ReplaceInstUsesWith(I, RHS);
1638 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1639 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1640 return ReplaceInstUsesWith(I, LHS);
1641 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1642 return ReplaceInstUsesWith(I, ConstantBool::True);
1643 }
1644 break;
1645 case Instruction::SetLT:
1646 switch (RHSCC) {
1647 default: assert(0 && "Unknown integer condition code!");
1648 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1649 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001650 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1651 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001652 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1653 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1654 return ReplaceInstUsesWith(I, RHS);
1655 }
1656 break;
1657 case Instruction::SetGT:
1658 switch (RHSCC) {
1659 default: assert(0 && "Unknown integer condition code!");
1660 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1661 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1662 return ReplaceInstUsesWith(I, LHS);
1663 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1664 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1665 return ReplaceInstUsesWith(I, ConstantBool::True);
1666 }
1667 }
1668 }
1669 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001670 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001671}
1672
Chris Lattnerc2076352004-02-16 01:20:27 +00001673// XorSelf - Implements: X ^ X --> 0
1674struct XorSelf {
1675 Value *RHS;
1676 XorSelf(Value *rhs) : RHS(rhs) {}
1677 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1678 Instruction *apply(BinaryOperator &Xor) const {
1679 return &Xor;
1680 }
1681};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001682
1683
Chris Lattner113f4f42002-06-25 16:13:24 +00001684Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001685 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001686 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001687
Chris Lattner81a7a232004-10-16 18:11:37 +00001688 if (isa<UndefValue>(Op1))
1689 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1690
Chris Lattnerc2076352004-02-16 01:20:27 +00001691 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1692 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1693 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001694 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001695 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001696
Chris Lattner97638592003-07-23 21:37:07 +00001697 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001698 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001699 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001700 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001701
Chris Lattner97638592003-07-23 21:37:07 +00001702 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001703 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001704 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001705 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001706 return new SetCondInst(SCI->getInverseCondition(),
1707 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001708
Chris Lattner8f2f5982003-11-05 01:06:05 +00001709 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001710 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1711 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001712 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1713 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001714 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001715 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001716 }
Chris Lattner023a4832004-06-18 06:07:51 +00001717
1718 // ~(~X & Y) --> (X | ~Y)
1719 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1720 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1721 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1722 Instruction *NotY =
1723 BinaryOperator::createNot(Op0I->getOperand(1),
1724 Op0I->getOperand(1)->getName()+".not");
1725 InsertNewInstBefore(NotY, I);
1726 return BinaryOperator::createOr(Op0NotVal, NotY);
1727 }
1728 }
Chris Lattner97638592003-07-23 21:37:07 +00001729
1730 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001731 switch (Op0I->getOpcode()) {
1732 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001733 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001734 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001735 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1736 return BinaryOperator::createSub(
1737 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001738 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001739 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001740 }
Chris Lattnere5806662003-11-04 23:50:51 +00001741 break;
1742 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001743 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001744 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1745 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001746 break;
1747 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001748 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001749 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001750 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001751 break;
1752 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001753 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001754 }
Chris Lattner183b3362004-04-09 19:05:30 +00001755
1756 // Try to fold constant and into select arguments.
1757 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1758 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1759 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001760 if (isa<PHINode>(Op0))
1761 if (Instruction *NV = FoldOpIntoPhi(I))
1762 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001763 }
1764
Chris Lattnerbb74e222003-03-10 23:06:50 +00001765 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001766 if (X == Op1)
1767 return ReplaceInstUsesWith(I,
1768 ConstantIntegral::getAllOnesValue(I.getType()));
1769
Chris Lattnerbb74e222003-03-10 23:06:50 +00001770 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001771 if (X == Op0)
1772 return ReplaceInstUsesWith(I,
1773 ConstantIntegral::getAllOnesValue(I.getType()));
1774
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001775 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001776 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001777 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1778 cast<BinaryOperator>(Op1I)->swapOperands();
1779 I.swapOperands();
1780 std::swap(Op0, Op1);
1781 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1782 I.swapOperands();
1783 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001784 }
1785 } else if (Op1I->getOpcode() == Instruction::Xor) {
1786 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1787 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1788 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1789 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1790 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001791
1792 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001793 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001794 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1795 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001796 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001797 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1798 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001799 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001800 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001801 } else if (Op0I->getOpcode() == Instruction::Xor) {
1802 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1803 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1804 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1805 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001806 }
1807
Chris Lattner7aa2d472004-08-01 19:42:59 +00001808 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001809 Value *A, *B; ConstantInt *C1, *C2;
1810 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1811 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00001812 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00001813 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001814
Chris Lattner3ac7c262003-08-13 20:16:26 +00001815 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1816 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1817 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1818 return R;
1819
Chris Lattner113f4f42002-06-25 16:13:24 +00001820 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001821}
1822
Chris Lattner6862fbd2004-09-29 17:40:11 +00001823/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1824/// overflowed for this type.
1825static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1826 ConstantInt *In2) {
1827 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1828 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1829}
1830
1831static bool isPositive(ConstantInt *C) {
1832 return cast<ConstantSInt>(C)->getValue() >= 0;
1833}
1834
1835/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1836/// overflowed for this type.
1837static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1838 ConstantInt *In2) {
1839 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1840
1841 if (In1->getType()->isUnsigned())
1842 return cast<ConstantUInt>(Result)->getValue() <
1843 cast<ConstantUInt>(In1)->getValue();
1844 if (isPositive(In1) != isPositive(In2))
1845 return false;
1846 if (isPositive(In1))
1847 return cast<ConstantSInt>(Result)->getValue() <
1848 cast<ConstantSInt>(In1)->getValue();
1849 return cast<ConstantSInt>(Result)->getValue() >
1850 cast<ConstantSInt>(In1)->getValue();
1851}
1852
Chris Lattner113f4f42002-06-25 16:13:24 +00001853Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001854 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001855 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1856 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001857
1858 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001859 if (Op0 == Op1)
1860 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001861
Chris Lattner81a7a232004-10-16 18:11:37 +00001862 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
1863 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
1864
Chris Lattnerd07283a2003-08-13 05:38:46 +00001865 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1866 if (isa<ConstantPointerNull>(Op1) &&
1867 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001868 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1869
Chris Lattnerd07283a2003-08-13 05:38:46 +00001870
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001871 // setcc's with boolean values can always be turned into bitwise operations
1872 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00001873 switch (I.getOpcode()) {
1874 default: assert(0 && "Invalid setcc instruction!");
1875 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001876 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001877 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001878 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001879 }
Chris Lattner4456da62004-08-11 00:50:51 +00001880 case Instruction::SetNE:
1881 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001882
Chris Lattner4456da62004-08-11 00:50:51 +00001883 case Instruction::SetGT:
1884 std::swap(Op0, Op1); // Change setgt -> setlt
1885 // FALL THROUGH
1886 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1887 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1888 InsertNewInstBefore(Not, I);
1889 return BinaryOperator::createAnd(Not, Op1);
1890 }
1891 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001892 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00001893 // FALL THROUGH
1894 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1895 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1896 InsertNewInstBefore(Not, I);
1897 return BinaryOperator::createOr(Not, Op1);
1898 }
1899 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001900 }
1901
Chris Lattner2dd01742004-06-09 04:24:29 +00001902 // See if we are doing a comparison between a constant and an instruction that
1903 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001904 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00001905 // Check to see if we are comparing against the minimum or maximum value...
1906 if (CI->isMinValue()) {
1907 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1908 return ReplaceInstUsesWith(I, ConstantBool::False);
1909 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1910 return ReplaceInstUsesWith(I, ConstantBool::True);
1911 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1912 return BinaryOperator::createSetEQ(Op0, Op1);
1913 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1914 return BinaryOperator::createSetNE(Op0, Op1);
1915
1916 } else if (CI->isMaxValue()) {
1917 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1918 return ReplaceInstUsesWith(I, ConstantBool::False);
1919 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1920 return ReplaceInstUsesWith(I, ConstantBool::True);
1921 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1922 return BinaryOperator::createSetEQ(Op0, Op1);
1923 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1924 return BinaryOperator::createSetNE(Op0, Op1);
1925
1926 // Comparing against a value really close to min or max?
1927 } else if (isMinValuePlusOne(CI)) {
1928 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1929 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
1930 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1931 return BinaryOperator::createSetNE(Op0, SubOne(CI));
1932
1933 } else if (isMaxValueMinusOne(CI)) {
1934 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1935 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
1936 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1937 return BinaryOperator::createSetNE(Op0, AddOne(CI));
1938 }
1939
1940 // If we still have a setle or setge instruction, turn it into the
1941 // appropriate setlt or setgt instruction. Since the border cases have
1942 // already been handled above, this requires little checking.
1943 //
1944 if (I.getOpcode() == Instruction::SetLE)
1945 return BinaryOperator::createSetLT(Op0, AddOne(CI));
1946 if (I.getOpcode() == Instruction::SetGE)
1947 return BinaryOperator::createSetGT(Op0, SubOne(CI));
1948
Chris Lattnere1e10e12004-05-25 06:32:08 +00001949 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001950 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001951 case Instruction::PHI:
1952 if (Instruction *NV = FoldOpIntoPhi(I))
1953 return NV;
1954 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001955 case Instruction::And:
1956 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1957 LHSI->getOperand(0)->hasOneUse()) {
1958 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1959 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1960 // happens a LOT in code produced by the C front-end, for bitfield
1961 // access.
1962 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1963 ConstantUInt *ShAmt;
1964 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1965 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1966 const Type *Ty = LHSI->getType();
1967
1968 // We can fold this as long as we can't shift unknown bits
1969 // into the mask. This can only happen with signed shift
1970 // rights, as they sign-extend.
1971 if (ShAmt) {
1972 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00001973 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001974 if (!CanFold) {
1975 // To test for the bad case of the signed shr, see if any
1976 // of the bits shifted in could be tested after the mask.
1977 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00001978 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001979 Constant *ShVal =
1980 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1981 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1982 CanFold = true;
1983 }
1984
1985 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00001986 Constant *NewCst;
1987 if (Shift->getOpcode() == Instruction::Shl)
1988 NewCst = ConstantExpr::getUShr(CI, ShAmt);
1989 else
1990 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00001991
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001992 // Check to see if we are shifting out any of the bits being
1993 // compared.
1994 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1995 // If we shifted bits out, the fold is not going to work out.
1996 // As a special case, check to see if this means that the
1997 // result is always true or false now.
1998 if (I.getOpcode() == Instruction::SetEQ)
1999 return ReplaceInstUsesWith(I, ConstantBool::False);
2000 if (I.getOpcode() == Instruction::SetNE)
2001 return ReplaceInstUsesWith(I, ConstantBool::True);
2002 } else {
2003 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002004 Constant *NewAndCST;
2005 if (Shift->getOpcode() == Instruction::Shl)
2006 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2007 else
2008 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2009 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002010 LHSI->setOperand(0, Shift->getOperand(0));
2011 WorkList.push_back(Shift); // Shift is dead.
2012 AddUsesToWorkList(I);
2013 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002014 }
2015 }
Chris Lattner35167c32004-06-09 07:59:58 +00002016 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002017 }
2018 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002019
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002020 case Instruction::Cast: { // (setcc (cast X to larger), CI)
2021 const Type *SrcTy = LHSI->getOperand(0)->getType();
2022 if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) {
Chris Lattnerc9491282004-09-29 03:16:24 +00002023 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002024 if (SrcTy == Type::BoolTy) SrcBits = 1;
Chris Lattnerc9491282004-09-29 03:16:24 +00002025 unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002026 if (LHSI->getType() == Type::BoolTy) DestBits = 1;
2027 if (SrcBits < DestBits) {
2028 // Check to see if the comparison is always true or false.
2029 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
2030 if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
2031 Constant *Min = ConstantIntegral::getMinValue(SrcTy);
2032 Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
2033 Min = ConstantExpr::getCast(Min, LHSI->getType());
2034 Max = ConstantExpr::getCast(Max, LHSI->getType());
2035 switch (I.getOpcode()) {
2036 default: assert(0 && "unknown integer comparison");
2037 case Instruction::SetEQ:
2038 return ReplaceInstUsesWith(I, ConstantBool::False);
2039 case Instruction::SetNE:
2040 return ReplaceInstUsesWith(I, ConstantBool::True);
2041 case Instruction::SetLT:
2042 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002043 case Instruction::SetGT:
2044 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002045 }
2046 }
2047
2048 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
2049 ConstantExpr::getCast(CI, SrcTy));
2050 }
2051 }
2052 break;
2053 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00002054 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2055 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2056 switch (I.getOpcode()) {
2057 default: break;
2058 case Instruction::SetEQ:
2059 case Instruction::SetNE: {
2060 // If we are comparing against bits always shifted out, the
2061 // comparison cannot succeed.
2062 Constant *Comp =
2063 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2064 if (Comp != CI) {// Comparing against a bit that we know is zero.
2065 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2066 Constant *Cst = ConstantBool::get(IsSetNE);
2067 return ReplaceInstUsesWith(I, Cst);
2068 }
2069
2070 if (LHSI->hasOneUse()) {
2071 // Otherwise strength reduce the shift into an and.
2072 unsigned ShAmtVal = ShAmt->getValue();
2073 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2074 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2075
2076 Constant *Mask;
2077 if (CI->getType()->isUnsigned()) {
2078 Mask = ConstantUInt::get(CI->getType(), Val);
2079 } else if (ShAmtVal != 0) {
2080 Mask = ConstantSInt::get(CI->getType(), Val);
2081 } else {
2082 Mask = ConstantInt::getAllOnesValue(CI->getType());
2083 }
2084
2085 Instruction *AndI =
2086 BinaryOperator::createAnd(LHSI->getOperand(0),
2087 Mask, LHSI->getName()+".mask");
2088 Value *And = InsertNewInstBefore(AndI, I);
2089 return new SetCondInst(I.getOpcode(), And,
2090 ConstantExpr::getUShr(CI, ShAmt));
2091 }
2092 }
2093 }
2094 }
2095 break;
2096
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002097 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002098 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002099 switch (I.getOpcode()) {
2100 default: break;
2101 case Instruction::SetEQ:
2102 case Instruction::SetNE: {
2103 // If we are comparing against bits always shifted out, the
2104 // comparison cannot succeed.
2105 Constant *Comp =
2106 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2107
2108 if (Comp != CI) {// Comparing against a bit that we know is zero.
2109 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2110 Constant *Cst = ConstantBool::get(IsSetNE);
2111 return ReplaceInstUsesWith(I, Cst);
2112 }
2113
2114 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00002115 unsigned ShAmtVal = ShAmt->getValue();
2116
Chris Lattner1023b872004-09-27 16:18:50 +00002117 // Otherwise strength reduce the shift into an and.
2118 uint64_t Val = ~0ULL; // All ones.
2119 Val <<= ShAmtVal; // Shift over to the right spot.
2120
2121 Constant *Mask;
2122 if (CI->getType()->isUnsigned()) {
2123 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2124 Val &= (1ULL << TypeBits)-1;
2125 Mask = ConstantUInt::get(CI->getType(), Val);
2126 } else {
2127 Mask = ConstantSInt::get(CI->getType(), Val);
2128 }
2129
2130 Instruction *AndI =
2131 BinaryOperator::createAnd(LHSI->getOperand(0),
2132 Mask, LHSI->getName()+".mask");
2133 Value *And = InsertNewInstBefore(AndI, I);
2134 return new SetCondInst(I.getOpcode(), And,
2135 ConstantExpr::getShl(CI, ShAmt));
2136 }
2137 break;
2138 }
2139 }
2140 }
2141 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002142
Chris Lattner6862fbd2004-09-29 17:40:11 +00002143 case Instruction::Div:
2144 // Fold: (div X, C1) op C2 -> range check
2145 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2146 // Fold this div into the comparison, producing a range check.
2147 // Determine, based on the divide type, what the range is being
2148 // checked. If there is an overflow on the low or high side, remember
2149 // it, otherwise compute the range [low, hi) bounding the new value.
2150 bool LoOverflow = false, HiOverflow = 0;
2151 ConstantInt *LoBound = 0, *HiBound = 0;
2152
2153 ConstantInt *Prod;
2154 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2155
Chris Lattnera92af962004-10-11 19:40:04 +00002156 Instruction::BinaryOps Opcode = I.getOpcode();
2157
Chris Lattner6862fbd2004-09-29 17:40:11 +00002158 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2159 } else if (LHSI->getType()->isUnsigned()) { // udiv
2160 LoBound = Prod;
2161 LoOverflow = ProdOV;
2162 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2163 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2164 if (CI->isNullValue()) { // (X / pos) op 0
2165 // Can't overflow.
2166 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2167 HiBound = DivRHS;
2168 } else if (isPositive(CI)) { // (X / pos) op pos
2169 LoBound = Prod;
2170 LoOverflow = ProdOV;
2171 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2172 } else { // (X / pos) op neg
2173 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2174 LoOverflow = AddWithOverflow(LoBound, Prod,
2175 cast<ConstantInt>(DivRHSH));
2176 HiBound = Prod;
2177 HiOverflow = ProdOV;
2178 }
2179 } else { // Divisor is < 0.
2180 if (CI->isNullValue()) { // (X / neg) op 0
2181 LoBound = AddOne(DivRHS);
2182 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2183 } else if (isPositive(CI)) { // (X / neg) op pos
2184 HiOverflow = LoOverflow = ProdOV;
2185 if (!LoOverflow)
2186 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2187 HiBound = AddOne(Prod);
2188 } else { // (X / neg) op neg
2189 LoBound = Prod;
2190 LoOverflow = HiOverflow = ProdOV;
2191 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2192 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002193
Chris Lattnera92af962004-10-11 19:40:04 +00002194 // Dividing by a negate swaps the condition.
2195 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002196 }
2197
2198 if (LoBound) {
2199 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002200 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002201 default: assert(0 && "Unhandled setcc opcode!");
2202 case Instruction::SetEQ:
2203 if (LoOverflow && HiOverflow)
2204 return ReplaceInstUsesWith(I, ConstantBool::False);
2205 else if (HiOverflow)
2206 return new SetCondInst(Instruction::SetGE, X, LoBound);
2207 else if (LoOverflow)
2208 return new SetCondInst(Instruction::SetLT, X, HiBound);
2209 else
2210 return InsertRangeTest(X, LoBound, HiBound, true, I);
2211 case Instruction::SetNE:
2212 if (LoOverflow && HiOverflow)
2213 return ReplaceInstUsesWith(I, ConstantBool::True);
2214 else if (HiOverflow)
2215 return new SetCondInst(Instruction::SetLT, X, LoBound);
2216 else if (LoOverflow)
2217 return new SetCondInst(Instruction::SetGE, X, HiBound);
2218 else
2219 return InsertRangeTest(X, LoBound, HiBound, false, I);
2220 case Instruction::SetLT:
2221 if (LoOverflow)
2222 return ReplaceInstUsesWith(I, ConstantBool::False);
2223 return new SetCondInst(Instruction::SetLT, X, LoBound);
2224 case Instruction::SetGT:
2225 if (HiOverflow)
2226 return ReplaceInstUsesWith(I, ConstantBool::False);
2227 return new SetCondInst(Instruction::SetGE, X, HiBound);
2228 }
2229 }
2230 }
2231 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002232 case Instruction::Select:
2233 // If either operand of the select is a constant, we can fold the
2234 // comparison into the select arms, which will cause one to be
2235 // constant folded and the select turned into a bitwise or.
2236 Value *Op1 = 0, *Op2 = 0;
2237 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00002238 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002239 // Fold the known value into the constant operand.
2240 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2241 // Insert a new SetCC of the other select operand.
2242 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002243 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002244 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00002245 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002246 // Fold the known value into the constant operand.
2247 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2248 // Insert a new SetCC of the other select operand.
2249 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002250 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002251 I.getName()), I);
2252 }
Chris Lattner2dd01742004-06-09 04:24:29 +00002253 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002254
2255 if (Op1)
2256 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2257 break;
2258 }
2259
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002260 // Simplify seteq and setne instructions...
2261 if (I.getOpcode() == Instruction::SetEQ ||
2262 I.getOpcode() == Instruction::SetNE) {
2263 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2264
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002265 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002266 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002267 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2268 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002269 case Instruction::Rem:
2270 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2271 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2272 BO->hasOneUse() &&
2273 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2274 if (unsigned L2 =
2275 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2276 const Type *UTy = BO->getType()->getUnsignedVersion();
2277 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2278 UTy, "tmp"), I);
2279 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2280 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2281 RHSCst, BO->getName()), I);
2282 return BinaryOperator::create(I.getOpcode(), NewRem,
2283 Constant::getNullValue(UTy));
2284 }
2285 break;
2286
Chris Lattnerc992add2003-08-13 05:33:12 +00002287 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002288 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2289 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002290 if (BO->hasOneUse())
2291 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2292 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002293 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002294 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2295 // efficiently invertible, or if the add has just this one use.
2296 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00002297
Chris Lattnerc992add2003-08-13 05:33:12 +00002298 if (Value *NegVal = dyn_castNegVal(BOp1))
2299 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2300 else if (Value *NegVal = dyn_castNegVal(BOp0))
2301 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002302 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002303 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2304 BO->setName("");
2305 InsertNewInstBefore(Neg, I);
2306 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2307 }
2308 }
2309 break;
2310 case Instruction::Xor:
2311 // For the xor case, we can xor two constants together, eliminating
2312 // the explicit xor.
2313 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2314 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002315 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002316
2317 // FALLTHROUGH
2318 case Instruction::Sub:
2319 // Replace (([sub|xor] A, B) != 0) with (A != B)
2320 if (CI->isNullValue())
2321 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2322 BO->getOperand(1));
2323 break;
2324
2325 case Instruction::Or:
2326 // If bits are being or'd in that are not present in the constant we
2327 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002328 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002329 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002330 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002331 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002332 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002333 break;
2334
2335 case Instruction::And:
2336 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002337 // If bits are being compared against that are and'd out, then the
2338 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002339 if (!ConstantExpr::getAnd(CI,
2340 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002341 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002342
Chris Lattner35167c32004-06-09 07:59:58 +00002343 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002344 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002345 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2346 Instruction::SetNE, Op0,
2347 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002348
Chris Lattnerc992add2003-08-13 05:33:12 +00002349 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2350 // to be a signed value as appropriate.
2351 if (isSignBit(BOC)) {
2352 Value *X = BO->getOperand(0);
2353 // If 'X' is not signed, insert a cast now...
2354 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002355 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002356 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002357 }
2358 return new SetCondInst(isSetNE ? Instruction::SetLT :
2359 Instruction::SetGE, X,
2360 Constant::getNullValue(X->getType()));
2361 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002362
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002363 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002364 if (CI->isNullValue() && isHighOnes(BOC)) {
2365 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002366 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002367
2368 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002369 if (NegX->getType()->isSigned()) {
2370 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2371 X = InsertCastBefore(X, DestTy, I);
2372 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002373 }
2374
2375 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002376 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002377 }
2378
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002379 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002380 default: break;
2381 }
2382 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002383 } else { // Not a SetEQ/SetNE
2384 // If the LHS is a cast from an integral value of the same size,
2385 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2386 Value *CastOp = Cast->getOperand(0);
2387 const Type *SrcTy = CastOp->getType();
2388 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2389 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2390 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2391 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2392 "Source and destination signednesses should differ!");
2393 if (Cast->getType()->isSigned()) {
2394 // If this is a signed comparison, check for comparisons in the
2395 // vicinity of zero.
2396 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2397 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002398 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002399 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2400 else if (I.getOpcode() == Instruction::SetGT &&
2401 cast<ConstantSInt>(CI)->getValue() == -1)
2402 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002403 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002404 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2405 } else {
2406 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2407 if (I.getOpcode() == Instruction::SetLT &&
2408 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2409 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002410 return BinaryOperator::createSetGT(CastOp,
2411 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002412 else if (I.getOpcode() == Instruction::SetGT &&
2413 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2414 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002415 return BinaryOperator::createSetLT(CastOp,
2416 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002417 }
2418 }
2419 }
Chris Lattnere967b342003-06-04 05:10:11 +00002420 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002421 }
2422
Chris Lattner16930792003-11-03 04:25:02 +00002423 // Test to see if the operands of the setcc are casted versions of other
2424 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002425 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2426 Value *CastOp0 = CI->getOperand(0);
2427 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002428 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002429 (I.getOpcode() == Instruction::SetEQ ||
2430 I.getOpcode() == Instruction::SetNE)) {
2431 // We keep moving the cast from the left operand over to the right
2432 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002433 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002434
2435 // If operand #1 is a cast instruction, see if we can eliminate it as
2436 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002437 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2438 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002439 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002440 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002441
2442 // If Op1 is a constant, we can fold the cast into the constant.
2443 if (Op1->getType() != Op0->getType())
2444 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2445 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2446 } else {
2447 // Otherwise, cast the RHS right before the setcc
2448 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2449 InsertNewInstBefore(cast<Instruction>(Op1), I);
2450 }
2451 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2452 }
2453
Chris Lattner6444c372003-11-03 05:17:03 +00002454 // Handle the special case of: setcc (cast bool to X), <cst>
2455 // This comes up when you have code like
2456 // int X = A < B;
2457 // if (X) ...
2458 // For generality, we handle any zero-extension of any operand comparison
2459 // with a constant.
2460 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2461 const Type *SrcTy = CastOp0->getType();
2462 const Type *DestTy = Op0->getType();
2463 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2464 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2465 // Ok, we have an expansion of operand 0 into a new type. Get the
2466 // constant value, masink off bits which are not set in the RHS. These
2467 // could be set if the destination value is signed.
2468 uint64_t ConstVal = ConstantRHS->getRawValue();
2469 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2470
2471 // If the constant we are comparing it with has high bits set, which
2472 // don't exist in the original value, the values could never be equal,
2473 // because the source would be zero extended.
2474 unsigned SrcBits =
2475 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002476 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2477 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002478 switch (I.getOpcode()) {
2479 default: assert(0 && "Unknown comparison type!");
2480 case Instruction::SetEQ:
2481 return ReplaceInstUsesWith(I, ConstantBool::False);
2482 case Instruction::SetNE:
2483 return ReplaceInstUsesWith(I, ConstantBool::True);
2484 case Instruction::SetLT:
2485 case Instruction::SetLE:
2486 if (DestTy->isSigned() && HasSignBit)
2487 return ReplaceInstUsesWith(I, ConstantBool::False);
2488 return ReplaceInstUsesWith(I, ConstantBool::True);
2489 case Instruction::SetGT:
2490 case Instruction::SetGE:
2491 if (DestTy->isSigned() && HasSignBit)
2492 return ReplaceInstUsesWith(I, ConstantBool::True);
2493 return ReplaceInstUsesWith(I, ConstantBool::False);
2494 }
2495 }
2496
2497 // Otherwise, we can replace the setcc with a setcc of the smaller
2498 // operand value.
2499 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2500 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2501 }
2502 }
2503 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002504 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002505}
2506
2507
2508
Chris Lattnere8d6c602003-03-10 19:16:08 +00002509Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002510 assert(I.getOperand(1)->getType() == Type::UByteTy);
2511 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002512 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002513
2514 // shl X, 0 == X and shr X, 0 == X
2515 // shl 0, X == 0 and shr 0, X == 0
2516 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00002517 Op0 == Constant::getNullValue(Op0->getType()))
2518 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002519
Chris Lattner81a7a232004-10-16 18:11:37 +00002520 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
2521 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00002522 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00002523 else // undef << X -> 0 AND undef >>u X -> 0
2524 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2525 }
2526 if (isa<UndefValue>(Op1)) {
2527 if (isLeftShift || I.getType()->isUnsigned())
2528 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2529 else
2530 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
2531 }
2532
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002533 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2534 if (!isLeftShift)
2535 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2536 if (CSI->isAllOnesValue())
2537 return ReplaceInstUsesWith(I, CSI);
2538
Chris Lattner183b3362004-04-09 19:05:30 +00002539 // Try to fold constant and into select arguments.
2540 if (isa<Constant>(Op0))
2541 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2542 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2543 return R;
2544
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002545 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002546 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2547 // of a signed value.
2548 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00002549 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002550 if (CUI->getValue() >= TypeBits) {
2551 if (!Op0->getType()->isSigned() || isLeftShift)
2552 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2553 else {
2554 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2555 return &I;
2556 }
2557 }
Chris Lattner55f3d942002-09-10 23:04:09 +00002558
Chris Lattnerede3fe02003-08-13 04:18:28 +00002559 // ((X*C1) << C2) == (X * (C1 << C2))
2560 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2561 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2562 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002563 return BinaryOperator::createMul(BO->getOperand(0),
2564 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00002565
Chris Lattner183b3362004-04-09 19:05:30 +00002566 // Try to fold constant and into select arguments.
2567 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2568 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2569 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002570 if (isa<PHINode>(Op0))
2571 if (Instruction *NV = FoldOpIntoPhi(I))
2572 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00002573
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002574 // If the operand is an bitwise operator with a constant RHS, and the
2575 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002576 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002577 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2578 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2579 bool isValid = true; // Valid only for And, Or, Xor
2580 bool highBitSet = false; // Transform if high bit of constant set?
2581
2582 switch (Op0BO->getOpcode()) {
2583 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00002584 case Instruction::Add:
2585 isValid = isLeftShift;
2586 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002587 case Instruction::Or:
2588 case Instruction::Xor:
2589 highBitSet = false;
2590 break;
2591 case Instruction::And:
2592 highBitSet = true;
2593 break;
2594 }
2595
2596 // If this is a signed shift right, and the high bit is modified
2597 // by the logical operation, do not perform the transformation.
2598 // The highBitSet boolean indicates the value of the high bit of
2599 // the constant which would cause it to be modified for this
2600 // operation.
2601 //
2602 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2603 uint64_t Val = Op0C->getRawValue();
2604 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2605 }
2606
2607 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002608 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002609
2610 Instruction *NewShift =
2611 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2612 Op0BO->getName());
2613 Op0BO->setName("");
2614 InsertNewInstBefore(NewShift, I);
2615
2616 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2617 NewRHS);
2618 }
2619 }
2620
Chris Lattner3204d4e2003-07-24 17:52:58 +00002621 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002622 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00002623 if (ConstantUInt *ShiftAmt1C =
2624 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002625 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2626 unsigned ShiftAmt2 = CUI->getValue();
2627
2628 // Check for (A << c1) << c2 and (A >> c1) >> c2
2629 if (I.getOpcode() == Op0SI->getOpcode()) {
2630 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002631 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2632 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00002633 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2634 ConstantUInt::get(Type::UByteTy, Amt));
2635 }
2636
Chris Lattnerab780df2003-07-24 18:38:56 +00002637 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2638 // signed types, we can only support the (A >> c1) << c2 configuration,
2639 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002640 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002641 // Calculate bitmask for what gets shifted off the edge...
2642 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002643 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002644 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002645 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002646 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00002647
2648 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002649 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2650 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00002651 InsertNewInstBefore(Mask, I);
2652
2653 // Figure out what flavor of shift we should use...
2654 if (ShiftAmt1 == ShiftAmt2)
2655 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2656 else if (ShiftAmt1 < ShiftAmt2) {
2657 return new ShiftInst(I.getOpcode(), Mask,
2658 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2659 } else {
2660 return new ShiftInst(Op0SI->getOpcode(), Mask,
2661 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2662 }
2663 }
2664 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002665 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00002666
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002667 return 0;
2668}
2669
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002670enum CastType {
2671 Noop = 0,
2672 Truncate = 1,
2673 Signext = 2,
2674 Zeroext = 3
2675};
2676
2677/// getCastType - In the future, we will split the cast instruction into these
2678/// various types. Until then, we have to do the analysis here.
2679static CastType getCastType(const Type *Src, const Type *Dest) {
2680 assert(Src->isIntegral() && Dest->isIntegral() &&
2681 "Only works on integral types!");
2682 unsigned SrcSize = Src->getPrimitiveSize()*8;
2683 if (Src == Type::BoolTy) SrcSize = 1;
2684 unsigned DestSize = Dest->getPrimitiveSize()*8;
2685 if (Dest == Type::BoolTy) DestSize = 1;
2686
2687 if (SrcSize == DestSize) return Noop;
2688 if (SrcSize > DestSize) return Truncate;
2689 if (Src->isSigned()) return Signext;
2690 return Zeroext;
2691}
2692
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002693
Chris Lattner48a44f72002-05-02 17:06:02 +00002694// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2695// instruction.
2696//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002697static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00002698 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002699
Chris Lattner650b6da2002-08-02 20:00:25 +00002700 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2701 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00002702 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00002703 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00002704 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00002705
Chris Lattner4fbad962004-07-21 04:27:24 +00002706 // If we are casting between pointer and integer types, treat pointers as
2707 // integers of the appropriate size for the code below.
2708 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2709 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2710 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00002711
Chris Lattner48a44f72002-05-02 17:06:02 +00002712 // Allow free casting and conversion of sizes as long as the sign doesn't
2713 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002714 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002715 CastType FirstCast = getCastType(SrcTy, MidTy);
2716 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00002717
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002718 // Capture the effect of these two casts. If the result is a legal cast,
2719 // the CastType is stored here, otherwise a special code is used.
2720 static const unsigned CastResult[] = {
2721 // First cast is noop
2722 0, 1, 2, 3,
2723 // First cast is a truncate
2724 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2725 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00002726 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002727 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00002728 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002729 };
2730
2731 unsigned Result = CastResult[FirstCast*4+SecondCast];
2732 switch (Result) {
2733 default: assert(0 && "Illegal table value!");
2734 case 0:
2735 case 1:
2736 case 2:
2737 case 3:
2738 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2739 // truncates, we could eliminate more casts.
2740 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2741 case 4:
2742 return false; // Not possible to eliminate this here.
2743 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00002744 // Sign or zero extend followed by truncate is always ok if the result
2745 // is a truncate or noop.
2746 CastType ResultCast = getCastType(SrcTy, DstTy);
2747 if (ResultCast == Noop || ResultCast == Truncate)
2748 return true;
2749 // Otherwise we are still growing the value, we are only safe if the
2750 // result will match the sign/zeroextendness of the result.
2751 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00002752 }
Chris Lattner650b6da2002-08-02 20:00:25 +00002753 }
Chris Lattner48a44f72002-05-02 17:06:02 +00002754 return false;
2755}
2756
Chris Lattner11ffd592004-07-20 05:21:00 +00002757static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002758 if (V->getType() == Ty || isa<Constant>(V)) return false;
2759 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00002760 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2761 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002762 return false;
2763 return true;
2764}
2765
2766/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2767/// InsertBefore instruction. This is specialized a bit to avoid inserting
2768/// casts that are known to not do anything...
2769///
2770Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2771 Instruction *InsertBefore) {
2772 if (V->getType() == DestTy) return V;
2773 if (Constant *C = dyn_cast<Constant>(V))
2774 return ConstantExpr::getCast(C, DestTy);
2775
2776 CastInst *CI = new CastInst(V, DestTy, V->getName());
2777 InsertNewInstBefore(CI, *InsertBefore);
2778 return CI;
2779}
Chris Lattner48a44f72002-05-02 17:06:02 +00002780
2781// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002782//
Chris Lattner113f4f42002-06-25 16:13:24 +00002783Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002784 Value *Src = CI.getOperand(0);
2785
Chris Lattner48a44f72002-05-02 17:06:02 +00002786 // If the user is casting a value to the same type, eliminate this cast
2787 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002788 if (CI.getType() == Src->getType())
2789 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002790
Chris Lattner81a7a232004-10-16 18:11:37 +00002791 if (isa<UndefValue>(Src)) // cast undef -> undef
2792 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
2793
Chris Lattner48a44f72002-05-02 17:06:02 +00002794 // If casting the result of another cast instruction, try to eliminate this
2795 // one!
2796 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002797 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002798 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner11ffd592004-07-20 05:21:00 +00002799 CSrc->getType(), CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002800 // This instruction now refers directly to the cast's src operand. This
2801 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002802 CI.setOperand(0, CSrc->getOperand(0));
2803 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002804 }
2805
Chris Lattner650b6da2002-08-02 20:00:25 +00002806 // If this is an A->B->A cast, and we are dealing with integral types, try
2807 // to convert this into a logical 'and' instruction.
2808 //
2809 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002810 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002811 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2812 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2813 assert(CSrc->getType() != Type::ULongTy &&
2814 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002815 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002816 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002817 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002818 }
2819 }
2820
Chris Lattner03841652004-05-25 04:29:21 +00002821 // If this is a cast to bool, turn it into the appropriate setne instruction.
2822 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002823 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002824 Constant::getNullValue(CI.getOperand(0)->getType()));
2825
Chris Lattnerd0d51602003-06-21 23:12:02 +00002826 // If casting the result of a getelementptr instruction with no offset, turn
2827 // this into a cast of the original pointer!
2828 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002829 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002830 bool AllZeroOperands = true;
2831 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2832 if (!isa<Constant>(GEP->getOperand(i)) ||
2833 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2834 AllZeroOperands = false;
2835 break;
2836 }
2837 if (AllZeroOperands) {
2838 CI.setOperand(0, GEP->getOperand(0));
2839 return &CI;
2840 }
2841 }
2842
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002843 // If we are casting a malloc or alloca to a pointer to a type of the same
2844 // size, rewrite the allocation instruction to allocate the "right" type.
2845 //
2846 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002847 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002848 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2849 // Get the type really allocated and the type casted to...
2850 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002851 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002852 if (AllocElTy->isSized() && CastElTy->isSized()) {
2853 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2854 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002855
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002856 // If the allocation is for an even multiple of the cast type size
2857 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2858 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002859 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002860 std::string Name = AI->getName(); AI->setName("");
2861 AllocationInst *New;
2862 if (isa<MallocInst>(AI))
2863 New = new MallocInst(CastElTy, Amt, Name);
2864 else
2865 New = new AllocaInst(CastElTy, Amt, Name);
2866 InsertNewInstBefore(New, *AI);
2867 return ReplaceInstUsesWith(CI, New);
2868 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002869 }
2870 }
2871
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002872 if (isa<PHINode>(Src))
2873 if (Instruction *NV = FoldOpIntoPhi(CI))
2874 return NV;
2875
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002876 // If the source value is an instruction with only this use, we can attempt to
2877 // propagate the cast into the instruction. Also, only handle integral types
2878 // for now.
2879 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002880 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002881 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2882 const Type *DestTy = CI.getType();
2883 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2884 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2885
2886 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2887 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2888
2889 switch (SrcI->getOpcode()) {
2890 case Instruction::Add:
2891 case Instruction::Mul:
2892 case Instruction::And:
2893 case Instruction::Or:
2894 case Instruction::Xor:
2895 // If we are discarding information, or just changing the sign, rewrite.
2896 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2897 // Don't insert two casts if they cannot be eliminated. We allow two
2898 // casts to be inserted if the sizes are the same. This could only be
2899 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00002900 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2901 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002902 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2903 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2904 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2905 ->getOpcode(), Op0c, Op1c);
2906 }
2907 }
2908 break;
2909 case Instruction::Shl:
2910 // Allow changing the sign of the source operand. Do not allow changing
2911 // the size of the shift, UNLESS the shift amount is a constant. We
2912 // mush not change variable sized shifts to a smaller size, because it
2913 // is undefined to shift more bits out than exist in the value.
2914 if (DestBitSize == SrcBitSize ||
2915 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2916 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2917 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2918 }
2919 break;
2920 }
2921 }
2922
Chris Lattner260ab202002-04-18 17:39:14 +00002923 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00002924}
2925
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002926/// GetSelectFoldableOperands - We want to turn code that looks like this:
2927/// %C = or %A, %B
2928/// %D = select %cond, %C, %A
2929/// into:
2930/// %C = select %cond, %B, 0
2931/// %D = or %A, %C
2932///
2933/// Assuming that the specified instruction is an operand to the select, return
2934/// a bitmask indicating which operands of this instruction are foldable if they
2935/// equal the other incoming value of the select.
2936///
2937static unsigned GetSelectFoldableOperands(Instruction *I) {
2938 switch (I->getOpcode()) {
2939 case Instruction::Add:
2940 case Instruction::Mul:
2941 case Instruction::And:
2942 case Instruction::Or:
2943 case Instruction::Xor:
2944 return 3; // Can fold through either operand.
2945 case Instruction::Sub: // Can only fold on the amount subtracted.
2946 case Instruction::Shl: // Can only fold on the shift amount.
2947 case Instruction::Shr:
2948 return 1;
2949 default:
2950 return 0; // Cannot fold
2951 }
2952}
2953
2954/// GetSelectFoldableConstant - For the same transformation as the previous
2955/// function, return the identity constant that goes into the select.
2956static Constant *GetSelectFoldableConstant(Instruction *I) {
2957 switch (I->getOpcode()) {
2958 default: assert(0 && "This cannot happen!"); abort();
2959 case Instruction::Add:
2960 case Instruction::Sub:
2961 case Instruction::Or:
2962 case Instruction::Xor:
2963 return Constant::getNullValue(I->getType());
2964 case Instruction::Shl:
2965 case Instruction::Shr:
2966 return Constant::getNullValue(Type::UByteTy);
2967 case Instruction::And:
2968 return ConstantInt::getAllOnesValue(I->getType());
2969 case Instruction::Mul:
2970 return ConstantInt::get(I->getType(), 1);
2971 }
2972}
2973
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002974Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00002975 Value *CondVal = SI.getCondition();
2976 Value *TrueVal = SI.getTrueValue();
2977 Value *FalseVal = SI.getFalseValue();
2978
2979 // select true, X, Y -> X
2980 // select false, X, Y -> Y
2981 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002982 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00002983 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002984 else {
2985 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00002986 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002987 }
Chris Lattner533bc492004-03-30 19:37:13 +00002988
2989 // select C, X, X -> X
2990 if (TrueVal == FalseVal)
2991 return ReplaceInstUsesWith(SI, TrueVal);
2992
Chris Lattner81a7a232004-10-16 18:11:37 +00002993 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2994 return ReplaceInstUsesWith(SI, FalseVal);
2995 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2996 return ReplaceInstUsesWith(SI, TrueVal);
2997 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2998 if (isa<Constant>(TrueVal))
2999 return ReplaceInstUsesWith(SI, TrueVal);
3000 else
3001 return ReplaceInstUsesWith(SI, FalseVal);
3002 }
3003
Chris Lattner1c631e82004-04-08 04:43:23 +00003004 if (SI.getType() == Type::BoolTy)
3005 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3006 if (C == ConstantBool::True) {
3007 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003008 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003009 } else {
3010 // Change: A = select B, false, C --> A = and !B, C
3011 Value *NotCond =
3012 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3013 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003014 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003015 }
3016 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3017 if (C == ConstantBool::False) {
3018 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003019 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003020 } else {
3021 // Change: A = select B, C, true --> A = or !B, C
3022 Value *NotCond =
3023 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3024 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003025 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003026 }
3027 }
3028
Chris Lattner183b3362004-04-09 19:05:30 +00003029 // Selecting between two integer constants?
3030 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3031 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3032 // select C, 1, 0 -> cast C to int
3033 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3034 return new CastInst(CondVal, SI.getType());
3035 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3036 // select C, 0, 1 -> cast !C to int
3037 Value *NotCond =
3038 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00003039 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00003040 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00003041 }
Chris Lattner35167c32004-06-09 07:59:58 +00003042
3043 // If one of the constants is zero (we know they can't both be) and we
3044 // have a setcc instruction with zero, and we have an 'and' with the
3045 // non-constant value, eliminate this whole mess. This corresponds to
3046 // cases like this: ((X & 27) ? 27 : 0)
3047 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3048 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3049 if ((IC->getOpcode() == Instruction::SetEQ ||
3050 IC->getOpcode() == Instruction::SetNE) &&
3051 isa<ConstantInt>(IC->getOperand(1)) &&
3052 cast<Constant>(IC->getOperand(1))->isNullValue())
3053 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3054 if (ICA->getOpcode() == Instruction::And &&
3055 isa<ConstantInt>(ICA->getOperand(1)) &&
3056 (ICA->getOperand(1) == TrueValC ||
3057 ICA->getOperand(1) == FalseValC) &&
3058 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3059 // Okay, now we know that everything is set up, we just don't
3060 // know whether we have a setne or seteq and whether the true or
3061 // false val is the zero.
3062 bool ShouldNotVal = !TrueValC->isNullValue();
3063 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3064 Value *V = ICA;
3065 if (ShouldNotVal)
3066 V = InsertNewInstBefore(BinaryOperator::create(
3067 Instruction::Xor, V, ICA->getOperand(1)), SI);
3068 return ReplaceInstUsesWith(SI, V);
3069 }
Chris Lattner533bc492004-03-30 19:37:13 +00003070 }
Chris Lattner623fba12004-04-10 22:21:27 +00003071
3072 // See if we are selecting two values based on a comparison of the two values.
3073 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3074 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3075 // Transform (X == Y) ? X : Y -> Y
3076 if (SCI->getOpcode() == Instruction::SetEQ)
3077 return ReplaceInstUsesWith(SI, FalseVal);
3078 // Transform (X != Y) ? X : Y -> X
3079 if (SCI->getOpcode() == Instruction::SetNE)
3080 return ReplaceInstUsesWith(SI, TrueVal);
3081 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3082
3083 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3084 // Transform (X == Y) ? Y : X -> X
3085 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003086 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003087 // Transform (X != Y) ? Y : X -> Y
3088 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003089 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003090 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3091 }
3092 }
Chris Lattner1c631e82004-04-08 04:43:23 +00003093
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003094 // See if we can fold the select into one of our operands.
3095 if (SI.getType()->isInteger()) {
3096 // See the comment above GetSelectFoldableOperands for a description of the
3097 // transformation we are doing here.
3098 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3099 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3100 !isa<Constant>(FalseVal))
3101 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3102 unsigned OpToFold = 0;
3103 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3104 OpToFold = 1;
3105 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3106 OpToFold = 2;
3107 }
3108
3109 if (OpToFold) {
3110 Constant *C = GetSelectFoldableConstant(TVI);
3111 std::string Name = TVI->getName(); TVI->setName("");
3112 Instruction *NewSel =
3113 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3114 Name);
3115 InsertNewInstBefore(NewSel, SI);
3116 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3117 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3118 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3119 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3120 else {
3121 assert(0 && "Unknown instruction!!");
3122 }
3123 }
3124 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003125
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003126 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3127 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3128 !isa<Constant>(TrueVal))
3129 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3130 unsigned OpToFold = 0;
3131 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3132 OpToFold = 1;
3133 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3134 OpToFold = 2;
3135 }
3136
3137 if (OpToFold) {
3138 Constant *C = GetSelectFoldableConstant(FVI);
3139 std::string Name = FVI->getName(); FVI->setName("");
3140 Instruction *NewSel =
3141 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3142 Name);
3143 InsertNewInstBefore(NewSel, SI);
3144 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3145 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3146 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3147 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3148 else {
3149 assert(0 && "Unknown instruction!!");
3150 }
3151 }
3152 }
3153 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003154 return 0;
3155}
3156
3157
Chris Lattner970c33a2003-06-19 17:00:31 +00003158// CallInst simplification
3159//
3160Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003161 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3162 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00003163 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3164 bool Changed = false;
3165
3166 // memmove/cpy/set of zero bytes is a noop.
3167 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3168 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3169
3170 // FIXME: Increase alignment here.
3171
3172 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3173 if (CI->getRawValue() == 1) {
3174 // Replace the instruction with just byte operations. We would
3175 // transform other cases to loads/stores, but we don't know if
3176 // alignment is sufficient.
3177 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003178 }
3179
Chris Lattner00648e12004-10-12 04:52:52 +00003180 // If we have a memmove and the source operation is a constant global,
3181 // then the source and dest pointers can't alias, so we can change this
3182 // into a call to memcpy.
3183 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3184 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3185 if (GVSrc->isConstant()) {
3186 Module *M = CI.getParent()->getParent()->getParent();
3187 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3188 CI.getCalledFunction()->getFunctionType());
3189 CI.setOperand(0, MemCpy);
3190 Changed = true;
3191 }
3192
3193 if (Changed) return &CI;
3194 }
3195
Chris Lattneraec3d942003-10-07 22:32:43 +00003196 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003197}
3198
3199// InvokeInst simplification
3200//
3201Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003202 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003203}
3204
Chris Lattneraec3d942003-10-07 22:32:43 +00003205// visitCallSite - Improvements for call and invoke instructions.
3206//
3207Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003208 bool Changed = false;
3209
3210 // If the callee is a constexpr cast of a function, attempt to move the cast
3211 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003212 if (transformConstExprCastCall(CS)) return 0;
3213
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003214 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00003215
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003216 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3217 // This instruction is not reachable, just remove it. We insert a store to
3218 // undef so that we know that this code is not reachable, despite the fact
3219 // that we can't modify the CFG here.
3220 new StoreInst(ConstantBool::True,
3221 UndefValue::get(PointerType::get(Type::BoolTy)),
3222 CS.getInstruction());
3223
3224 if (!CS.getInstruction()->use_empty())
3225 CS.getInstruction()->
3226 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3227
3228 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3229 // Don't break the CFG, insert a dummy cond branch.
3230 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3231 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00003232 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003233 return EraseInstFromFunction(*CS.getInstruction());
3234 }
Chris Lattner81a7a232004-10-16 18:11:37 +00003235
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003236 const PointerType *PTy = cast<PointerType>(Callee->getType());
3237 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3238 if (FTy->isVarArg()) {
3239 // See if we can optimize any arguments passed through the varargs area of
3240 // the call.
3241 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3242 E = CS.arg_end(); I != E; ++I)
3243 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3244 // If this cast does not effect the value passed through the varargs
3245 // area, we can eliminate the use of the cast.
3246 Value *Op = CI->getOperand(0);
3247 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3248 *I = Op;
3249 Changed = true;
3250 }
3251 }
3252 }
Chris Lattneraec3d942003-10-07 22:32:43 +00003253
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003254 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00003255}
3256
Chris Lattner970c33a2003-06-19 17:00:31 +00003257// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3258// attempt to move the cast to the arguments of the call/invoke.
3259//
3260bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3261 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3262 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00003263 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00003264 return false;
Reid Spencer87436872004-07-18 00:38:32 +00003265 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00003266 Instruction *Caller = CS.getInstruction();
3267
3268 // Okay, this is a cast from a function to a different type. Unless doing so
3269 // would cause a type conversion of one of our arguments, change this call to
3270 // be a direct call with arguments casted to the appropriate types.
3271 //
3272 const FunctionType *FT = Callee->getFunctionType();
3273 const Type *OldRetTy = Caller->getType();
3274
Chris Lattner1f7942f2004-01-14 06:06:08 +00003275 // Check to see if we are changing the return type...
3276 if (OldRetTy != FT->getReturnType()) {
3277 if (Callee->isExternal() &&
3278 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3279 !Caller->use_empty())
3280 return false; // Cannot transform this return value...
3281
3282 // If the callsite is an invoke instruction, and the return value is used by
3283 // a PHI node in a successor, we cannot change the return type of the call
3284 // because there is no place to put the cast instruction (without breaking
3285 // the critical edge). Bail out in this case.
3286 if (!Caller->use_empty())
3287 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3288 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3289 UI != E; ++UI)
3290 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3291 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003292 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00003293 return false;
3294 }
Chris Lattner970c33a2003-06-19 17:00:31 +00003295
3296 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3297 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3298
3299 CallSite::arg_iterator AI = CS.arg_begin();
3300 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3301 const Type *ParamTy = FT->getParamType(i);
3302 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3303 if (Callee->isExternal() && !isConvertible) return false;
3304 }
3305
3306 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3307 Callee->isExternal())
3308 return false; // Do not delete arguments unless we have a function body...
3309
3310 // Okay, we decided that this is a safe thing to do: go ahead and start
3311 // inserting cast instructions as necessary...
3312 std::vector<Value*> Args;
3313 Args.reserve(NumActualArgs);
3314
3315 AI = CS.arg_begin();
3316 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3317 const Type *ParamTy = FT->getParamType(i);
3318 if ((*AI)->getType() == ParamTy) {
3319 Args.push_back(*AI);
3320 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00003321 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3322 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00003323 }
3324 }
3325
3326 // If the function takes more arguments than the call was taking, add them
3327 // now...
3328 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3329 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3330
3331 // If we are removing arguments to the function, emit an obnoxious warning...
3332 if (FT->getNumParams() < NumActualArgs)
3333 if (!FT->isVarArg()) {
3334 std::cerr << "WARNING: While resolving call to function '"
3335 << Callee->getName() << "' arguments were dropped!\n";
3336 } else {
3337 // Add all of the arguments in their promoted form to the arg list...
3338 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3339 const Type *PTy = getPromotedType((*AI)->getType());
3340 if (PTy != (*AI)->getType()) {
3341 // Must promote to pass through va_arg area!
3342 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3343 InsertNewInstBefore(Cast, *Caller);
3344 Args.push_back(Cast);
3345 } else {
3346 Args.push_back(*AI);
3347 }
3348 }
3349 }
3350
3351 if (FT->getReturnType() == Type::VoidTy)
3352 Caller->setName(""); // Void type should not have a name...
3353
3354 Instruction *NC;
3355 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003356 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00003357 Args, Caller->getName(), Caller);
3358 } else {
3359 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3360 }
3361
3362 // Insert a cast of the return type as necessary...
3363 Value *NV = NC;
3364 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3365 if (NV->getType() != Type::VoidTy) {
3366 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00003367
3368 // If this is an invoke instruction, we should insert it after the first
3369 // non-phi, instruction in the normal successor block.
3370 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3371 BasicBlock::iterator I = II->getNormalDest()->begin();
3372 while (isa<PHINode>(I)) ++I;
3373 InsertNewInstBefore(NC, *I);
3374 } else {
3375 // Otherwise, it's a call, just insert cast right after the call instr
3376 InsertNewInstBefore(NC, *Caller);
3377 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003378 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00003379 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00003380 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00003381 }
3382 }
3383
3384 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3385 Caller->replaceAllUsesWith(NV);
3386 Caller->getParent()->getInstList().erase(Caller);
3387 removeFromWorkList(Caller);
3388 return true;
3389}
3390
3391
Chris Lattner48a44f72002-05-02 17:06:02 +00003392
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003393// PHINode simplification
3394//
Chris Lattner113f4f42002-06-25 16:13:24 +00003395Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnere29d6342004-10-17 21:22:38 +00003396 if (Value *V = hasConstantValue(&PN)) {
3397 // If V is an instruction, we have to be certain that it dominates PN.
3398 // However, because we don't have dom info, we can't do a perfect job.
3399 if (Instruction *I = dyn_cast<Instruction>(V)) {
3400 // We know that the instruction dominates the PHI if there are no undef
3401 // values coming in.
Chris Lattner3b92f172004-10-18 01:48:31 +00003402 if (I->getParent() != &I->getParent()->getParent()->front() ||
3403 isa<InvokeInst>(I))
Chris Lattner107c15c2004-10-17 21:31:34 +00003404 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3405 if (isa<UndefValue>(PN.getIncomingValue(i))) {
3406 V = 0;
3407 break;
3408 }
Chris Lattnere29d6342004-10-17 21:22:38 +00003409 }
3410
3411 if (V)
3412 return ReplaceInstUsesWith(PN, V);
3413 }
Chris Lattner4db2d222004-02-16 05:07:08 +00003414
3415 // If the only user of this instruction is a cast instruction, and all of the
3416 // incoming values are constants, change this PHI to merge together the casted
3417 // constants.
3418 if (PN.hasOneUse())
3419 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3420 if (CI->getType() != PN.getType()) { // noop casts will be folded
3421 bool AllConstant = true;
3422 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3423 if (!isa<Constant>(PN.getIncomingValue(i))) {
3424 AllConstant = false;
3425 break;
3426 }
3427 if (AllConstant) {
3428 // Make a new PHI with all casted values.
3429 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3430 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3431 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3432 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3433 PN.getIncomingBlock(i));
3434 }
3435
3436 // Update the cast instruction.
3437 CI->setOperand(0, New);
3438 WorkList.push_back(CI); // revisit the cast instruction to fold.
3439 WorkList.push_back(New); // Make sure to revisit the new Phi
3440 return &PN; // PN is now dead!
3441 }
3442 }
Chris Lattner91daeb52003-12-19 05:58:40 +00003443 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003444}
3445
Chris Lattner69193f92004-04-05 01:30:19 +00003446static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3447 Instruction *InsertPoint,
3448 InstCombiner *IC) {
3449 unsigned PS = IC->getTargetData().getPointerSize();
3450 const Type *VTy = V->getType();
3451 Instruction *Cast;
3452 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3453 // We must insert a cast to ensure we sign-extend.
3454 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3455 V->getName()), *InsertPoint);
3456 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3457 *InsertPoint);
3458}
3459
Chris Lattner48a44f72002-05-02 17:06:02 +00003460
Chris Lattner113f4f42002-06-25 16:13:24 +00003461Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003462 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00003463 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00003464 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003465 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00003466 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003467
Chris Lattner81a7a232004-10-16 18:11:37 +00003468 if (isa<UndefValue>(GEP.getOperand(0)))
3469 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
3470
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003471 bool HasZeroPointerIndex = false;
3472 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3473 HasZeroPointerIndex = C->isNullValue();
3474
3475 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00003476 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00003477
Chris Lattner69193f92004-04-05 01:30:19 +00003478 // Eliminate unneeded casts for indices.
3479 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00003480 gep_type_iterator GTI = gep_type_begin(GEP);
3481 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3482 if (isa<SequentialType>(*GTI)) {
3483 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3484 Value *Src = CI->getOperand(0);
3485 const Type *SrcTy = Src->getType();
3486 const Type *DestTy = CI->getType();
3487 if (Src->getType()->isInteger()) {
3488 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3489 // We can always eliminate a cast from ulong or long to the other.
3490 // We can always eliminate a cast from uint to int or the other on
3491 // 32-bit pointer platforms.
3492 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3493 MadeChange = true;
3494 GEP.setOperand(i, Src);
3495 }
3496 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3497 SrcTy->getPrimitiveSize() == 4) {
3498 // We can always eliminate a cast from int to [u]long. We can
3499 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3500 // pointer target.
3501 if (SrcTy->isSigned() ||
3502 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3503 MadeChange = true;
3504 GEP.setOperand(i, Src);
3505 }
Chris Lattner69193f92004-04-05 01:30:19 +00003506 }
3507 }
3508 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00003509 // If we are using a wider index than needed for this platform, shrink it
3510 // to what we need. If the incoming value needs a cast instruction,
3511 // insert it. This explicit cast can make subsequent optimizations more
3512 // obvious.
3513 Value *Op = GEP.getOperand(i);
3514 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003515 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00003516 GEP.setOperand(i, ConstantExpr::getCast(C,
3517 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003518 MadeChange = true;
3519 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00003520 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3521 Op->getName()), GEP);
3522 GEP.setOperand(i, Op);
3523 MadeChange = true;
3524 }
Chris Lattner44d0b952004-07-20 01:48:15 +00003525
3526 // If this is a constant idx, make sure to canonicalize it to be a signed
3527 // operand, otherwise CSE and other optimizations are pessimized.
3528 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3529 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3530 CUI->getType()->getSignedVersion()));
3531 MadeChange = true;
3532 }
Chris Lattner69193f92004-04-05 01:30:19 +00003533 }
3534 if (MadeChange) return &GEP;
3535
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003536 // Combine Indices - If the source pointer to this getelementptr instruction
3537 // is a getelementptr instruction, combine the indices of the two
3538 // getelementptr instructions into a single instruction.
3539 //
Chris Lattner57c67b02004-03-25 22:59:29 +00003540 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00003541 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003542 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00003543 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003544 if (CE->getOpcode() == Instruction::GetElementPtr)
3545 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3546 }
3547
3548 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003549 // Note that if our source is a gep chain itself that we wait for that
3550 // chain to be resolved before we perform this transformation. This
3551 // avoids us creating a TON of code in some cases.
3552 //
3553 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3554 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3555 return 0; // Wait until our source is folded to completion.
3556
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003557 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00003558
3559 // Find out whether the last index in the source GEP is a sequential idx.
3560 bool EndsWithSequential = false;
3561 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3562 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00003563 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00003564
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003565 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00003566 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00003567 // Replace: gep (gep %P, long B), long A, ...
3568 // With: T = long A+B; gep %P, T, ...
3569 //
Chris Lattner5f667a62004-05-07 22:09:22 +00003570 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00003571 if (SO1 == Constant::getNullValue(SO1->getType())) {
3572 Sum = GO1;
3573 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3574 Sum = SO1;
3575 } else {
3576 // If they aren't the same type, convert both to an integer of the
3577 // target's pointer size.
3578 if (SO1->getType() != GO1->getType()) {
3579 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3580 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3581 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3582 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3583 } else {
3584 unsigned PS = TD->getPointerSize();
3585 Instruction *Cast;
3586 if (SO1->getType()->getPrimitiveSize() == PS) {
3587 // Convert GO1 to SO1's type.
3588 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3589
3590 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3591 // Convert SO1 to GO1's type.
3592 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3593 } else {
3594 const Type *PT = TD->getIntPtrType();
3595 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3596 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3597 }
3598 }
3599 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003600 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3601 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3602 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003603 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3604 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00003605 }
Chris Lattner69193f92004-04-05 01:30:19 +00003606 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003607
3608 // Recycle the GEP we already have if possible.
3609 if (SrcGEPOperands.size() == 2) {
3610 GEP.setOperand(0, SrcGEPOperands[0]);
3611 GEP.setOperand(1, Sum);
3612 return &GEP;
3613 } else {
3614 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3615 SrcGEPOperands.end()-1);
3616 Indices.push_back(Sum);
3617 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3618 }
Chris Lattner69193f92004-04-05 01:30:19 +00003619 } else if (isa<Constant>(*GEP.idx_begin()) &&
3620 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00003621 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003622 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00003623 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3624 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003625 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3626 }
3627
3628 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00003629 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003630
Chris Lattner5f667a62004-05-07 22:09:22 +00003631 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003632 // GEP of global variable. If all of the indices for this GEP are
3633 // constants, we can promote this to a constexpr instead of an instruction.
3634
3635 // Scan for nonconstants...
3636 std::vector<Constant*> Indices;
3637 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3638 for (; I != E && isa<Constant>(*I); ++I)
3639 Indices.push_back(cast<Constant>(*I));
3640
3641 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00003642 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003643
3644 // Replace all uses of the GEP with the new constexpr...
3645 return ReplaceInstUsesWith(GEP, CE);
3646 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003647 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003648 if (CE->getOpcode() == Instruction::Cast) {
3649 if (HasZeroPointerIndex) {
3650 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3651 // into : GEP [10 x ubyte]* X, long 0, ...
3652 //
3653 // This occurs when the program declares an array extern like "int X[];"
3654 //
3655 Constant *X = CE->getOperand(0);
3656 const PointerType *CPTy = cast<PointerType>(CE->getType());
3657 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3658 if (const ArrayType *XATy =
3659 dyn_cast<ArrayType>(XTy->getElementType()))
3660 if (const ArrayType *CATy =
3661 dyn_cast<ArrayType>(CPTy->getElementType()))
3662 if (CATy->getElementType() == XATy->getElementType()) {
3663 // At this point, we know that the cast source type is a pointer
3664 // to an array of the same type as the destination pointer
3665 // array. Because the array type is never stepped over (there
3666 // is a leading zero) we can fold the cast into this GEP.
3667 GEP.setOperand(0, X);
3668 return &GEP;
3669 }
3670 }
3671 }
Chris Lattnerca081252001-12-14 16:52:21 +00003672 }
3673
Chris Lattnerca081252001-12-14 16:52:21 +00003674 return 0;
3675}
3676
Chris Lattner1085bdf2002-11-04 16:18:53 +00003677Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3678 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3679 if (AI.isArrayAllocation()) // Check C != 1
3680 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3681 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003682 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00003683
3684 // Create and insert the replacement instruction...
3685 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00003686 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003687 else {
3688 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00003689 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003690 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003691
3692 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003693
3694 // Scan to the end of the allocation instructions, to skip over a block of
3695 // allocas if possible...
3696 //
3697 BasicBlock::iterator It = New;
3698 while (isa<AllocationInst>(*It)) ++It;
3699
3700 // Now that I is pointing to the first non-allocation-inst in the block,
3701 // insert our getelementptr instruction...
3702 //
Chris Lattner69193f92004-04-05 01:30:19 +00003703 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003704 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3705
3706 // Now make everything use the getelementptr instead of the original
3707 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00003708 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00003709 } else if (isa<UndefValue>(AI.getArraySize())) {
3710 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003711 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003712
3713 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3714 // Note that we only do this for alloca's, because malloc should allocate and
3715 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00003716 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3717 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00003718 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3719
Chris Lattner1085bdf2002-11-04 16:18:53 +00003720 return 0;
3721}
3722
Chris Lattner8427bff2003-12-07 01:24:23 +00003723Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3724 Value *Op = FI.getOperand(0);
3725
3726 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3727 if (CastInst *CI = dyn_cast<CastInst>(Op))
3728 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3729 FI.setOperand(0, CI->getOperand(0));
3730 return &FI;
3731 }
3732
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003733 // free undef -> unreachable.
3734 if (isa<UndefValue>(Op)) {
3735 // Insert a new store to null because we cannot modify the CFG here.
3736 new StoreInst(ConstantBool::True,
3737 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
3738 return EraseInstFromFunction(FI);
3739 }
3740
Chris Lattnerf3a36602004-02-28 04:57:37 +00003741 // If we have 'free null' delete the instruction. This can happen in stl code
3742 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003743 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00003744 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00003745
Chris Lattner8427bff2003-12-07 01:24:23 +00003746 return 0;
3747}
3748
3749
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003750/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3751/// constantexpr, return the constant value being addressed by the constant
3752/// expression, or null if something is funny.
3753///
3754static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00003755 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003756 return 0; // Do not allow stepping over the value!
3757
3758 // Loop over all of the operands, tracking down which value we are
3759 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00003760 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3761 for (++I; I != E; ++I)
3762 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3763 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3764 assert(CU->getValue() < STy->getNumElements() &&
3765 "Struct index out of range!");
3766 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003767 C = CS->getOperand(CU->getValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003768 } else if (isa<ConstantAggregateZero>(C)) {
3769 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003770 } else if (isa<UndefValue>(C)) {
3771 C = UndefValue::get(STy->getElementType(CU->getValue()));
Chris Lattnered79d8a2004-05-27 17:30:27 +00003772 } else {
3773 return 0;
3774 }
3775 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3776 const ArrayType *ATy = cast<ArrayType>(*I);
3777 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3778 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003779 C = CA->getOperand(CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003780 else if (isa<ConstantAggregateZero>(C))
3781 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00003782 else if (isa<UndefValue>(C))
3783 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003784 else
3785 return 0;
3786 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003787 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00003788 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003789 return C;
3790}
3791
Chris Lattner35e24772004-07-13 01:49:43 +00003792static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3793 User *CI = cast<User>(LI.getOperand(0));
3794
3795 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3796 if (const PointerType *SrcTy =
3797 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3798 const Type *SrcPTy = SrcTy->getElementType();
3799 if (SrcPTy->isSized() && DestPTy->isSized() &&
3800 IC.getTargetData().getTypeSize(SrcPTy) ==
3801 IC.getTargetData().getTypeSize(DestPTy) &&
3802 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3803 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3804 // Okay, we are casting from one integer or pointer type to another of
3805 // the same size. Instead of casting the pointer before the load, cast
3806 // the result of the loaded value.
3807 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003808 CI->getName(),
3809 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00003810 // Now cast the result of the load.
3811 return new CastInst(NewLoad, LI.getType());
3812 }
3813 }
3814 return 0;
3815}
3816
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003817/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00003818/// from this value cannot trap. If it is not obviously safe to load from the
3819/// specified pointer, we do a quick local scan of the basic block containing
3820/// ScanFrom, to determine if the address is already accessed.
3821static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3822 // If it is an alloca or global variable, it is always safe to load from.
3823 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3824
3825 // Otherwise, be a little bit agressive by scanning the local block where we
3826 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003827 // from/to. If so, the previous load or store would have already trapped,
3828 // so there is no harm doing an extra load (also, CSE will later eliminate
3829 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00003830 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3831
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003832 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00003833 --BBI;
3834
3835 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3836 if (LI->getOperand(0) == V) return true;
3837 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3838 if (SI->getOperand(1) == V) return true;
3839
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003840 }
Chris Lattnere6f13092004-09-19 19:18:10 +00003841 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003842}
3843
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003844Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3845 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00003846
Chris Lattner81a7a232004-10-16 18:11:37 +00003847 if (Constant *C = dyn_cast<Constant>(Op)) {
3848 if ((C->isNullValue() || isa<UndefValue>(C)) &&
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003849 !LI.isVolatile()) { // load null/undef -> undef
3850 // Insert a new store to null instruction before the load to indicate that
3851 // this code is not reachable. We do this instead of inserting an
3852 // unreachable instruction directly because we cannot modify the CFG.
3853 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00003854 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003855 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003856
Chris Lattner81a7a232004-10-16 18:11:37 +00003857 // Instcombine load (constant global) into the value loaded.
3858 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
3859 if (GV->isConstant() && !GV->isExternal())
3860 return ReplaceInstUsesWith(LI, GV->getInitializer());
3861
3862 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
3863 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
3864 if (CE->getOpcode() == Instruction::GetElementPtr) {
3865 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3866 if (GV->isConstant() && !GV->isExternal())
3867 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3868 return ReplaceInstUsesWith(LI, V);
3869 } else if (CE->getOpcode() == Instruction::Cast) {
3870 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3871 return Res;
3872 }
3873 }
Chris Lattnere228ee52004-04-08 20:39:49 +00003874
3875 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00003876 if (CastInst *CI = dyn_cast<CastInst>(Op))
3877 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3878 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00003879
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003880 if (!LI.isVolatile() && Op->hasOneUse()) {
3881 // Change select and PHI nodes to select values instead of addresses: this
3882 // helps alias analysis out a lot, allows many others simplifications, and
3883 // exposes redundancy in the code.
3884 //
3885 // Note that we cannot do the transformation unless we know that the
3886 // introduced loads cannot trap! Something like this is valid as long as
3887 // the condition is always false: load (select bool %C, int* null, int* %G),
3888 // but it would not be valid if we transformed it to load from null
3889 // unconditionally.
3890 //
3891 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3892 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00003893 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3894 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003895 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00003896 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003897 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00003898 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003899 return new SelectInst(SI->getCondition(), V1, V2);
3900 }
3901
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00003902 // load (select (cond, null, P)) -> load P
3903 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3904 if (C->isNullValue()) {
3905 LI.setOperand(0, SI->getOperand(2));
3906 return &LI;
3907 }
3908
3909 // load (select (cond, P, null)) -> load P
3910 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3911 if (C->isNullValue()) {
3912 LI.setOperand(0, SI->getOperand(1));
3913 return &LI;
3914 }
3915
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003916 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3917 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00003918 bool Safe = PN->getParent() == LI.getParent();
3919
3920 // Scan all of the instructions between the PHI and the load to make
3921 // sure there are no instructions that might possibly alter the value
3922 // loaded from the PHI.
3923 if (Safe) {
3924 BasicBlock::iterator I = &LI;
3925 for (--I; !isa<PHINode>(I); --I)
3926 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3927 Safe = false;
3928 break;
3929 }
3930 }
3931
3932 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00003933 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00003934 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003935 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00003936
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003937 if (Safe) {
3938 // Create the PHI.
3939 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3940 InsertNewInstBefore(NewPN, *PN);
3941 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3942
3943 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3944 BasicBlock *BB = PN->getIncomingBlock(i);
3945 Value *&TheLoad = LoadMap[BB];
3946 if (TheLoad == 0) {
3947 Value *InVal = PN->getIncomingValue(i);
3948 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3949 InVal->getName()+".val"),
3950 *BB->getTerminator());
3951 }
3952 NewPN->addIncoming(TheLoad, BB);
3953 }
3954 return ReplaceInstUsesWith(LI, NewPN);
3955 }
3956 }
3957 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003958 return 0;
3959}
3960
Chris Lattner9eef8a72003-06-04 04:46:00 +00003961Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3962 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00003963 Value *X;
3964 BasicBlock *TrueDest;
3965 BasicBlock *FalseDest;
3966 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3967 !isa<Constant>(X)) {
3968 // Swap Destinations and condition...
3969 BI.setCondition(X);
3970 BI.setSuccessor(0, FalseDest);
3971 BI.setSuccessor(1, TrueDest);
3972 return &BI;
3973 }
3974
3975 // Cannonicalize setne -> seteq
3976 Instruction::BinaryOps Op; Value *Y;
3977 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3978 TrueDest, FalseDest)))
3979 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3980 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3981 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3982 std::string Name = I->getName(); I->setName("");
3983 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3984 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00003985 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00003986 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00003987 BI.setSuccessor(0, FalseDest);
3988 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003989 removeFromWorkList(I);
3990 I->getParent()->getInstList().erase(I);
3991 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00003992 return &BI;
3993 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00003994
Chris Lattner9eef8a72003-06-04 04:46:00 +00003995 return 0;
3996}
Chris Lattner1085bdf2002-11-04 16:18:53 +00003997
Chris Lattner4c9c20a2004-07-03 00:26:11 +00003998Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3999 Value *Cond = SI.getCondition();
4000 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4001 if (I->getOpcode() == Instruction::Add)
4002 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4003 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4004 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00004005 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004006 AddRHS));
4007 SI.setOperand(0, I->getOperand(0));
4008 WorkList.push_back(I);
4009 return &SI;
4010 }
4011 }
4012 return 0;
4013}
4014
Chris Lattnerca081252001-12-14 16:52:21 +00004015
Chris Lattner99f48c62002-09-02 04:59:56 +00004016void InstCombiner::removeFromWorkList(Instruction *I) {
4017 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4018 WorkList.end());
4019}
4020
Chris Lattner113f4f42002-06-25 16:13:24 +00004021bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00004022 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004023 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00004024
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004025 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
4026 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00004027
Chris Lattnerca081252001-12-14 16:52:21 +00004028
4029 while (!WorkList.empty()) {
4030 Instruction *I = WorkList.back(); // Get an instruction from the worklist
4031 WorkList.pop_back();
4032
Misha Brukman632df282002-10-29 23:06:16 +00004033 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00004034 // Check to see if we can DIE the instruction...
4035 if (isInstructionTriviallyDead(I)) {
4036 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004037 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00004038 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00004039 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004040
4041 I->getParent()->getInstList().erase(I);
4042 removeFromWorkList(I);
4043 continue;
4044 }
Chris Lattner99f48c62002-09-02 04:59:56 +00004045
Misha Brukman632df282002-10-29 23:06:16 +00004046 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00004047 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner6580e092004-10-16 19:44:59 +00004048 if (isa<GetElementPtrInst>(I) &&
4049 cast<Constant>(I->getOperand(0))->isNullValue() &&
4050 !isa<ConstantPointerNull>(C)) {
4051 // If this is a constant expr gep that is effectively computing an
4052 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
4053 bool isFoldableGEP = true;
4054 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
4055 if (!isa<ConstantInt>(I->getOperand(i)))
4056 isFoldableGEP = false;
4057 if (isFoldableGEP) {
4058 uint64_t Offset = TD->getIndexedOffset(I->getOperand(0)->getType(),
4059 std::vector<Value*>(I->op_begin()+1, I->op_end()));
4060 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00004061 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00004062 C = ConstantExpr::getCast(C, I->getType());
4063 }
4064 }
4065
Chris Lattner99f48c62002-09-02 04:59:56 +00004066 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00004067 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00004068 ReplaceInstUsesWith(*I, C);
4069
Chris Lattner99f48c62002-09-02 04:59:56 +00004070 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004071 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00004072 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004073 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00004074 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004075
Chris Lattnerca081252001-12-14 16:52:21 +00004076 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004077 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00004078 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00004079 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00004080 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004081 DEBUG(std::cerr << "IC: Old = " << *I
4082 << " New = " << *Result);
4083
Chris Lattner396dbfe2004-06-09 05:08:07 +00004084 // Everything uses the new instruction now.
4085 I->replaceAllUsesWith(Result);
4086
4087 // Push the new instruction and any users onto the worklist.
4088 WorkList.push_back(Result);
4089 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004090
4091 // Move the name to the new instruction first...
4092 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00004093 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004094
4095 // Insert the new instruction into the basic block...
4096 BasicBlock *InstParent = I->getParent();
4097 InstParent->getInstList().insert(I, Result);
4098
Chris Lattner63d75af2004-05-01 23:27:23 +00004099 // Make sure that we reprocess all operands now that we reduced their
4100 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004101 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4102 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4103 WorkList.push_back(OpI);
4104
Chris Lattner396dbfe2004-06-09 05:08:07 +00004105 // Instructions can end up on the worklist more than once. Make sure
4106 // we do not process an instruction that has been deleted.
4107 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004108
4109 // Erase the old instruction.
4110 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004111 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004112 DEBUG(std::cerr << "IC: MOD = " << *I);
4113
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004114 // If the instruction was modified, it's possible that it is now dead.
4115 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00004116 if (isInstructionTriviallyDead(I)) {
4117 // Make sure we process all operands now that we are reducing their
4118 // use counts.
4119 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4120 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4121 WorkList.push_back(OpI);
4122
4123 // Instructions may end up in the worklist more than once. Erase all
4124 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00004125 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00004126 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00004127 } else {
4128 WorkList.push_back(Result);
4129 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004130 }
Chris Lattner053c0932002-05-14 15:24:07 +00004131 }
Chris Lattner260ab202002-04-18 17:39:14 +00004132 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00004133 }
4134 }
4135
Chris Lattner260ab202002-04-18 17:39:14 +00004136 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00004137}
4138
Brian Gaeke38b79e82004-07-27 17:43:21 +00004139FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00004140 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00004141}
Brian Gaeke960707c2003-11-11 22:41:34 +00004142