blob: 6689039fbe3d7032b2d90234649cda29f54994ac [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
John Criswellb576c942003-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 Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner62b14df2002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner32ed46b2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner32ed46b2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-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 Lattnerdf17af12003-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 Lattner2cd91962003-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 Lattnere92d2f42003-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 Lattner2cd91962003-07-23 21:41:57 +000032// N. This list is incomplete
33//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerbc61e662003-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 Lattner28977af2004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
46#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner221d6882002-02-12 21:07:25 +000047#include "llvm/Support/InstIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000049#include "llvm/Support/PatternMatch.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000050#include "llvm/Support/Debug.h"
51#include "llvm/ADT/Statistic.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000052#include <algorithm>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000053using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000054using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000055
Chris Lattnerdd841ae2002-04-18 17:39:14 +000056namespace {
Chris Lattnera92f6962002-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 Lattnerf57b8452002-04-27 06:56:12 +000061 class InstCombiner : public FunctionPass,
Chris Lattnerdd841ae2002-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 Lattnerbc61e662003-11-02 05:57:39 +000065 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000066
Chris Lattner7bcc0e72004-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 Lattner7e708292002-06-25 16:13:24 +000072 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000073 UI != UE; ++UI)
74 WorkList.push_back(cast<Instruction>(*UI));
75 }
76
Chris Lattner7bcc0e72004-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 Lattner62b14df2002-09-02 04:59:56 +000086 // removeFromWorkList - remove all instances of I from the worklist.
87 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000088 public:
Chris Lattner7e708292002-06-25 16:13:24 +000089 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000090
Chris Lattner97e52e42002-04-28 21:27:06 +000091 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +000092 AU.addRequired<TargetData>();
Chris Lattnercb2610e2002-10-21 20:00:28 +000093 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +000094 }
95
Chris Lattner28977af2004-04-05 01:30:19 +000096 TargetData &getTargetData() const { return *TD; }
97
Chris Lattnerdd841ae2002-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 Lattner233f7dc2002-08-12 21:17:25 +0000102 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000103 // otherwise - Change was made, replace I with returned instruction
104 //
Chris Lattner7e708292002-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 Lattnerea340052003-03-10 19:16:08 +0000114 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000115 Instruction *visitCastInst(CastInst &CI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000116 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000117 Instruction *visitCallInst(CallInst &CI);
118 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000119 Instruction *visitPHINode(PHINode &PN);
120 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000121 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000122 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000123 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000124 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000125 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000126
127 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000128 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000129
Chris Lattner9fe38862003-06-19 17:00:31 +0000130 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000131 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000132 bool transformConstExprCastCall(CallSite CS);
133
Chris Lattner28977af2004-04-05 01:30:19 +0000134 public:
Chris Lattner8b170942002-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 Lattner955f3312004-09-28 21:48:02 +0000138 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000139 assert(New && New->getParent() == 0 &&
140 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-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 Lattner4cb170c2004-02-23 06:38:22 +0000144 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000145 }
146
Chris Lattner0c967662004-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 Lattner8b170942002-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 Lattner7bcc0e72004-02-28 05:22:00 +0000165 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-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 Lattner17be6352004-10-18 02:59:09 +0000172 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000173 return &I;
174 }
Chris Lattner8b170942002-08-09 23:47:40 +0000175 }
Chris Lattner7bcc0e72004-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 Lattneraa9c1f12003-08-13 20:16:26 +0000190 private:
Chris Lattner24c8e382003-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 Lattnerc8802d22003-03-11 00:12:48 +0000198 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner4e998b22004-09-29 05:07:12 +0000199 // operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000200 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000201
Chris Lattner4e998b22004-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 Lattnerbd7b5ff2003-09-19 17:17:26 +0000208 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
209 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnera96879a2004-09-29 17:40:11 +0000210
211 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
212 bool Inside, Instruction &IB);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000213 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000214
Chris Lattnera6275cc2002-07-26 21:12:46 +0000215 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000216}
217
Chris Lattner4f98c562003-03-10 21:43:22 +0000218// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000219// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000220static unsigned getComplexity(Value *V) {
221 if (isa<Instruction>(V)) {
222 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000223 return 3;
224 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000225 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000226 if (isa<Argument>(V)) return 3;
227 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000228}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000229
Chris Lattnerc8802d22003-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 Lattnerfd059242003-10-15 16:48:29 +0000233 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000234}
235
Chris Lattner4cb170c2004-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 Lattner5dd04022004-06-17 18:16:02 +0000239 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-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 Lattner4f98c562003-03-10 21:43:22 +0000249// SimplifyCommutative - This performs a few simplifications for commutative
250// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000251//
Chris Lattner4f98c562003-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 Lattnerc8802d22003-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 Lattner4f98c562003-03-10 21:43:22 +0000258//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000259bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-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 Lattnerc8802d22003-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 Lattner2a9c8472003-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 Lattnerc8802d22003-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 Lattner2a9c8472003-05-27 16:40:51 +0000282 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-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 Lattner4f98c562003-03-10 21:43:22 +0000291 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000292 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000293}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000294
Chris Lattner8d969642003-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 Lattnerb35dde12002-05-06 16:49:18 +0000297//
Chris Lattner8d969642003-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 Lattnerfe32e0c2003-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 Lattner448c3232004-06-10 02:12:35 +0000304 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000305 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000306}
307
Chris Lattner8d969642003-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 Lattner3f2ec392003-04-30 22:34:06 +0000313 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000314 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000315 return 0;
316}
317
Chris Lattnerc8802d22003-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 Lattnerfd059242003-10-15 16:48:29 +0000323 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattnerc8802d22003-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 Lattnera2881962003-02-18 19:28:33 +0000329}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000330
Chris Lattnera2881962003-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 Lattneraf2930e2002-08-14 17:51:49 +0000342}
343
Chris Lattner955f3312004-09-28 21:48:02 +0000344// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000345static ConstantInt *AddOne(ConstantInt *C) {
346 return cast<ConstantInt>(ConstantExpr::getAdd(C,
347 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000348}
Chris Lattnera96879a2004-09-29 17:40:11 +0000349static ConstantInt *SubOne(ConstantInt *C) {
350 return cast<ConstantInt>(ConstantExpr::getSub(C,
351 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-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 Lattner564a7272003-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 Lattnerfd059242003-10-15 16:48:29 +0000382 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-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 Lattner564a7272003-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 Lattner65725312004-04-16 18:08:07 +0000406 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +0000407 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
408 return 0;
409 }
Chris Lattner65725312004-04-16 18:08:07 +0000410 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +0000411 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-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 Lattner564a7272003-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 Lattner65725312004-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 Lattner564a7272003-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 Lattneracd1f0f2004-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 Lattner564a7272003-08-13 19:01:45 +0000464 }
465 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +0000466 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +0000467 }
468};
469
Chris Lattner2eefe512004-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 Lattner564a7272003-08-13 19:01:45 +0000475
Chris Lattner2eefe512004-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 Lattner326c0f32004-04-10 19:15:56 +0000490 else {
Chris Lattner2eefe512004-04-09 19:05:30 +0000491 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +0000492 abort();
493 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000494 return IC->InsertNewInstBefore(New, BI);
495}
496
Chris Lattner4e998b22004-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 Lattner2eefe512004-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 Lattner564a7272003-08-13 19:01:45 +0000556
Chris Lattner7e708292002-06-25 16:13:24 +0000557Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000558 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000559 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000560
Chris Lattner66331a42004-04-10 22:01:55 +0000561 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +0000562 // X + undef -> undef
563 if (isa<UndefValue>(RHS))
564 return ReplaceInstUsesWith(I, RHS);
565
Chris Lattner66331a42004-04-10 22:01:55 +0000566 // X + 0 --> X
567 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
568 RHSC->isNullValue())
569 return ReplaceInstUsesWith(I, LHS);
570
571 // X + (signbit) --> X ^ signbit
572 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
573 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
574 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattnerf1580922004-11-05 04:45:43 +0000575 if (Val == (1ULL << (NumBits-1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000576 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner66331a42004-04-10 22:01:55 +0000577 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000578
579 if (isa<PHINode>(LHS))
580 if (Instruction *NV = FoldOpIntoPhi(I))
581 return NV;
Chris Lattner66331a42004-04-10 22:01:55 +0000582 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000583
Chris Lattner564a7272003-08-13 19:01:45 +0000584 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +0000585 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000586 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino71698282004-07-27 21:02:21 +0000587 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000588
Chris Lattner5c4afb92002-05-08 22:46:53 +0000589 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +0000590 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000591 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000592
593 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000594 if (!isa<Constant>(RHS))
595 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000596 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000597
Chris Lattnerad3448c2003-02-18 19:57:07 +0000598 // X*C + X --> X * (C+1)
599 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000600 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000601 ConstantExpr::getAdd(
Chris Lattner2a9c8472003-05-27 16:40:51 +0000602 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
603 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +0000604 return BinaryOperator::createMul(RHS, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000605 }
606
607 // X + X*C --> X * (C+1)
608 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000609 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000610 ConstantExpr::getAdd(
Chris Lattner2a9c8472003-05-27 16:40:51 +0000611 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
612 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +0000613 return BinaryOperator::createMul(LHS, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000614 }
615
Chris Lattner564a7272003-08-13 19:01:45 +0000616 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000617 ConstantInt *C2;
618 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +0000619 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000620
Chris Lattner6b032052003-10-02 15:11:26 +0000621 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattneracd1f0f2004-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 Lattner6b032052003-10-02 15:11:26 +0000626 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000627
Chris Lattnerb99d6b12004-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 Lattneracd1f0f2004-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 Lattner6b032052003-10-02 15:11:26 +0000657 }
658
Chris Lattner7e708292002-06-25 16:13:24 +0000659 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000660}
661
Chris Lattner1ba5bcd2003-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 Lattner24c8e382003-07-24 17:35:25 +0000669static unsigned getTypeSizeInBits(const Type *Ty) {
670 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
671}
672
Chris Lattnerbfe492b2004-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 Lattner7e708292002-06-25 16:13:24 +0000688Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000689 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000690
Chris Lattner233f7dc2002-08-12 21:17:25 +0000691 if (Op0 == Op1) // sub X, X -> 0
692 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000693
Chris Lattner233f7dc2002-08-12 21:17:25 +0000694 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +0000695 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +0000696 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000697
Chris Lattnere87597f2004-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 Lattnerd65460f2003-11-05 01:06:05 +0000703 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
704 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +0000705 if (C->isAllOnesValue())
706 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +0000707
Chris Lattnerd65460f2003-11-05 01:06:05 +0000708 // C - ~X == X + (1+C)
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000709 Value *X;
710 if (match(Op1, m_Not(m_Value(X))))
711 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +0000712 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +0000713 // -((uint)X >> 31) -> ((int)X >> 31)
714 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000715 if (C->isNullValue()) {
716 Value *NoopCastedRHS = RemoveNoopCast(Op1);
717 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-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 Lattnerbfe492b2004-03-13 00:11:49 +0000721 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +0000722 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000723 else
Chris Lattner5dd04022004-06-17 18:16:02 +0000724 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000725 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000726 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner9c290672004-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 Lattnerbfe492b2004-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 Lattner9c290672004-03-12 23:53:13 +0000740 }
741 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000742 }
Chris Lattner2eefe512004-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 Lattner4e998b22004-09-29 05:07:12 +0000748
749 if (isa<PHINode>(Op0))
750 if (Instruction *NV = FoldOpIntoPhi(I))
751 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +0000752 }
753
Chris Lattnera2881962003-02-18 19:28:33 +0000754 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerfd059242003-10-15 16:48:29 +0000755 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-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 Lattner0517e722004-02-02 20:09:56 +0000759 if (Op1I->getOpcode() == Instruction::Sub &&
760 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-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 Lattner48595f12004-06-10 02:07:29 +0000767 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-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 Lattnerf523d062004-06-09 05:08:07 +0000776 Value *NewNot =
777 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +0000778 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +0000779 }
Chris Lattnerad3448c2003-02-18 19:57:07 +0000780
Chris Lattner91ccc152004-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 Lattnerad3448c2003-02-18 19:57:07 +0000789 // X - X*C --> X * (1-C)
790 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000791 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000792 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000793 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000794 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattner48595f12004-06-10 02:07:29 +0000795 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000796 }
Chris Lattner40371712002-05-09 01:29:19 +0000797 }
Chris Lattnera2881962003-02-18 19:28:33 +0000798
Chris Lattnerad3448c2003-02-18 19:57:07 +0000799 // X*C - X --> X * (C-1)
800 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000801 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000802 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000803 ConstantInt::get(I.getType(), 1));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000804 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattner48595f12004-06-10 02:07:29 +0000805 return BinaryOperator::createMul(Op1, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000806 }
807
Chris Lattner3f5b8772002-05-06 16:14:14 +0000808 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000809}
810
Chris Lattner4cb170c2004-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 Lattner7e708292002-06-25 16:13:24 +0000831Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000832 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +0000833 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000834
Chris Lattnere87597f2004-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 Lattner233f7dc2002-08-12 21:17:25 +0000838 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +0000839 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
840 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-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 Lattner48595f12004-06-10 02:07:29 +0000846 return BinaryOperator::createMul(SI->getOperand(0),
847 ConstantExpr::getShl(CI, ShOp));
Chris Lattner7c4049c2004-01-12 19:35:11 +0000848
Chris Lattner515c97c2003-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 Lattner0af1fab2003-06-25 17:09:20 +0000854 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +0000855
Chris Lattner515c97c2003-09-11 22:24:54 +0000856 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattnera2881962003-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 Bocchino71698282004-07-27 21:02:21 +0000860 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +0000861 if (Op1F->isNullValue())
862 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +0000863
Chris Lattnera2881962003-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 Lattner2eefe512004-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 Lattner4e998b22004-09-29 05:07:12 +0000874
875 if (isa<PHINode>(Op0))
876 if (Instruction *NV = FoldOpIntoPhi(I))
877 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000878 }
879
Chris Lattnera4f445b2003-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 Lattner48595f12004-06-10 02:07:29 +0000882 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +0000883
Chris Lattnerfb54b2b2004-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 Lattner4cb170c2004-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 Lattnerfb54b2b2004-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 Lattner4cb170c2004-02-23 06:38:22 +0000908 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000909 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattner4cb170c2004-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 Lattnerfb54b2b2004-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 Lattner4cb170c2004-02-23 06:38:22 +0000922 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000923
924 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +0000925 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000926 }
927 }
928 }
929
Chris Lattner7e708292002-06-25 16:13:24 +0000930 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000931}
932
Chris Lattner7e708292002-06-25 16:13:24 +0000933Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnere87597f2004-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 Lattnera2881962003-02-18 19:28:33 +0000939 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattner83a2e6e2004-04-26 14:01:59 +0000940 // div X, 1 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +0000941 if (RHS->equalsInt(1))
942 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattnera2881962003-02-18 19:28:33 +0000943
Chris Lattner83a2e6e2004-04-26 14:01:59 +0000944 // div X, -1 == -X
945 if (RHS->isAllOnesValue())
946 return BinaryOperator::createNeg(I.getOperand(0));
947
Chris Lattner18d19ca2004-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 Lattner18d19ca2004-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 Lattnera2881962003-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 Lattner4e998b22004-09-29 05:07:12 +0000963
Chris Lattnera052f822004-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 Lattner4e998b22004-09-29 05:07:12 +0000969 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
970 if (Instruction *NV = FoldOpIntoPhi(I))
971 return NV;
Chris Lattnera2881962003-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 Lattner3f5b8772002-05-06 16:14:14 +0000979 return 0;
980}
981
982
Chris Lattner7e708292002-06-25 16:13:24 +0000983Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner5b73c082004-07-06 07:01:22 +0000984 if (I.getType()->isSigned())
985 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner1e3564e2004-07-06 07:11:42 +0000986 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattnerb49f3062004-08-09 21:05:48 +0000987 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner5b73c082004-07-06 07:01:22 +0000988 // X % -Y -> X % Y
989 AddUsesToWorkList(I);
990 I.setOperand(1, RHSNeg);
991 return &I;
992 }
993
Chris Lattnere87597f2004-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 Lattnera2881962003-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 Lattner546516c2004-05-07 15:35:56 +00001007 if (!(Val & (Val-1))) // Power of 2
Chris Lattner48595f12004-06-10 02:07:29 +00001008 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattnera2881962003-02-18 19:28:33 +00001009 ConstantUInt::get(I.getType(), Val-1));
Chris Lattner4e998b22004-09-29 05:07:12 +00001010 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
1011 if (Instruction *NV = FoldOpIntoPhi(I))
1012 return NV;
Chris Lattnera2881962003-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 Lattner233f7dc2002-08-12 21:17:25 +00001018 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1019
Chris Lattner3f5b8772002-05-06 16:14:14 +00001020 return 0;
1021}
1022
Chris Lattner8b170942002-08-09 23:47:40 +00001023// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001024static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner8b170942002-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 Lattner233f7dc2002-08-12 21:17:25 +00001043static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-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 Lattner457dd822004-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 Lattnerb20ba0a2004-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 Lattneraa9c1f12003-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 Lattner021c1902003-09-22 20:33:34 +00001157 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-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 Lattnerbd7b5ff2003-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 Lattner76f7fe22004-01-12 19:47:05 +00001177 Constant *Together = 0;
1178 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00001179 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001180
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001181 switch (Op->getOpcode()) {
1182 case Instruction::Xor:
Chris Lattner7c4049c2004-01-12 19:35:11 +00001183 if (Together->isNullValue()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001184 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattner48595f12004-06-10 02:07:29 +00001185 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001186 } else if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001187 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1188 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001189 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001190 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001191 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001192 }
1193 break;
1194 case Instruction::Or:
1195 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattner7c4049c2004-01-12 19:35:11 +00001196 if (Together->isNullValue())
Chris Lattner48595f12004-06-10 02:07:29 +00001197 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001198 else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001199 if (Together == AndRHS) // (X | C) & C --> C
1200 return ReplaceInstUsesWith(TheAnd, AndRHS);
1201
Chris Lattnerfd059242003-10-15 16:48:29 +00001202 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001203 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1204 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001205 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001206 InsertNewInstBefore(Or, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001207 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001208 }
1209 }
1210 break;
1211 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00001212 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-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 Lattner457dd822004-06-09 07:59:58 +00001216 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-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 Lattner457dd822004-06-09 07:59:58 +00001222 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-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 Lattner457dd822004-06-09 07:59:58 +00001226 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-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 Lattner48595f12004-06-10 02:07:29 +00001240 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001241 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001242 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001243 }
1244 }
1245 }
1246 }
1247 break;
Chris Lattner62a355c2003-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 Lattner0c967662004-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 Lattner62a355c2003-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 Lattner0c967662004-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 Lattner62a355c2003-09-19 19:05:02 +00001279 return &TheAnd;
1280 }
Chris Lattner0c967662004-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 Lattner9b991822004-10-22 04:53:16 +00001288 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner0c967662004-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 Lattnerdc781222004-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 Lattner0c967662004-09-24 15:21:34 +00001301 return new CastInst(ShVal, Op->getType());
1302 }
1303 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001304 }
1305 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001306 }
1307 return 0;
1308}
1309
Chris Lattner8b170942002-08-09 23:47:40 +00001310
Chris Lattnera96879a2004-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 Lattner7e708292002-06-25 16:13:24 +00001356Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001357 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001358 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001359
Chris Lattnere87597f2004-10-16 18:11:37 +00001360 if (isa<UndefValue>(Op1)) // X & undef -> 0
1361 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1362
Chris Lattner3f5b8772002-05-06 16:14:14 +00001363 // and X, X = X and X, 0 == 0
Chris Lattner233f7dc2002-08-12 21:17:25 +00001364 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1365 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001366
1367 // and X, -1 == X
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001368 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner233f7dc2002-08-12 21:17:25 +00001369 if (RHS->isAllOnesValue())
1370 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001371
Chris Lattnerbd7b5ff2003-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 Lattner06782f82003-07-23 19:36:21 +00001375 Value *X = Op0I->getOperand(0);
Chris Lattner58403262003-07-23 19:25:52 +00001376 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001377 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1378 return Res;
Chris Lattner06782f82003-07-23 19:36:21 +00001379 }
Chris Lattner2eefe512004-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 Lattner4e998b22004-09-29 05:07:12 +00001385 if (isa<PHINode>(Op0))
1386 if (Instruction *NV = FoldOpIntoPhi(I))
1387 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001388 }
1389
Chris Lattner8d969642003-03-10 23:06:50 +00001390 Value *Op0NotVal = dyn_castNotVal(Op0);
1391 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001392
Chris Lattner5b62aa72004-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 Brukmancb6267b2004-07-30 12:50:08 +00001396 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00001397 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00001398 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1399 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001400 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00001401 return BinaryOperator::createNot(Or);
1402 }
1403
Chris Lattner955f3312004-09-28 21:48:02 +00001404 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1405 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001406 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1407 return R;
1408
Chris Lattner955f3312004-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 Lattnera96879a2004-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 Lattner955f3312004-09-28 21:48:02 +00001495 }
1496 }
1497 }
1498 }
1499
Chris Lattner7e708292002-06-25 16:13:24 +00001500 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001501}
1502
Chris Lattner7e708292002-06-25 16:13:24 +00001503Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001504 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001505 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001506
Chris Lattnere87597f2004-10-16 18:11:37 +00001507 if (isa<UndefValue>(Op1))
1508 return ReplaceInstUsesWith(I, // X | undef -> -1
1509 ConstantIntegral::getAllOnesValue(I.getType()));
1510
Chris Lattner3f5b8772002-05-06 16:14:14 +00001511 // or X, X = X or X, 0 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00001512 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1513 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001514
1515 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001516 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner233f7dc2002-08-12 21:17:25 +00001517 if (RHS->isAllOnesValue())
1518 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001519
Chris Lattneracd1f0f2004-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 Lattnerad44ebf2003-07-23 18:29:44 +00001528
Chris Lattneracd1f0f2004-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 Lattnerad44ebf2003-07-23 18:29:44 +00001536 }
Chris Lattner2eefe512004-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 Lattner4e998b22004-09-29 05:07:12 +00001542 if (isa<PHINode>(Op0))
1543 if (Instruction *NV = FoldOpIntoPhi(I))
1544 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001545 }
1546
Chris Lattner67ca7682003-08-12 19:11:07 +00001547 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattneracd1f0f2004-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 Lattner67ca7682003-08-12 19:11:07 +00001552
Chris Lattneracd1f0f2004-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 Lattnera2881962003-02-18 19:28:33 +00001560
Chris Lattneracd1f0f2004-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 Lattnera27231a2003-03-10 23:13:59 +00001565
Misha Brukmancb6267b2004-07-30 12:50:08 +00001566 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-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 Lattnera27231a2003-03-10 23:13:59 +00001572 }
Chris Lattnera2881962003-02-18 19:28:33 +00001573
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001574 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerb4f40d22004-09-28 22:33:08 +00001575 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001576 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1577 return R;
1578
Chris Lattnerb4f40d22004-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 Lattnera96879a2004-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 Lattnerb4f40d22004-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 Lattner7e708292002-06-25 16:13:24 +00001670 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001671}
1672
Chris Lattnerc317d392004-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 Lattner3f5b8772002-05-06 16:14:14 +00001682
1683
Chris Lattner7e708292002-06-25 16:13:24 +00001684Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001685 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001686 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001687
Chris Lattnere87597f2004-10-16 18:11:37 +00001688 if (isa<UndefValue>(Op1))
1689 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1690
Chris Lattnerc317d392004-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 Lattner233f7dc2002-08-12 21:17:25 +00001694 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00001695 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001696
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001697 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner8b170942002-08-09 23:47:40 +00001698 // xor X, 0 == X
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001699 if (RHS->isNullValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00001700 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8b170942002-08-09 23:47:40 +00001701
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001702 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00001703 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001704 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerfd059242003-10-15 16:48:29 +00001705 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00001706 return new SetCondInst(SCI->getInverseCondition(),
1707 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001708
Chris Lattnerd65460f2003-11-05 01:06:05 +00001709 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00001710 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1711 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00001712 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1713 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00001714 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00001715 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001716 }
Chris Lattner5b62aa72004-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 Lattnereca0c5c2003-07-23 21:37:07 +00001729
1730 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001731 switch (Op0I->getOpcode()) {
1732 case Instruction::Add:
Chris Lattner689d24b2003-11-04 23:37:10 +00001733 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00001734 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00001735 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1736 return BinaryOperator::createSub(
1737 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00001738 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00001739 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00001740 }
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001741 break;
1742 case Instruction::And:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001743 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattner48595f12004-06-10 02:07:29 +00001744 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1745 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001746 break;
1747 case Instruction::Or:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001748 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattner48595f12004-06-10 02:07:29 +00001749 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattner448c3232004-06-10 02:12:35 +00001750 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001751 break;
1752 default: break;
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001753 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00001754 }
Chris Lattner2eefe512004-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 Lattner4e998b22004-09-29 05:07:12 +00001760 if (isa<PHINode>(Op0))
1761 if (Instruction *NV = FoldOpIntoPhi(I))
1762 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001763 }
1764
Chris Lattner8d969642003-03-10 23:06:50 +00001765 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00001766 if (X == Op1)
1767 return ReplaceInstUsesWith(I,
1768 ConstantIntegral::getAllOnesValue(I.getType()));
1769
Chris Lattner8d969642003-03-10 23:06:50 +00001770 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00001771 if (X == Op0)
1772 return ReplaceInstUsesWith(I,
1773 ConstantIntegral::getAllOnesValue(I.getType()));
1774
Chris Lattnercb40a372003-03-10 18:24:17 +00001775 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00001776 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-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 Lattner26ca7e12004-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 Lattnercb40a372003-03-10 18:24:17 +00001791
1792 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00001793 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00001794 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1795 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00001796 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerf523d062004-06-09 05:08:07 +00001797 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1798 Op1->getName()+".not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00001799 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00001800 }
Chris Lattner26ca7e12004-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 Lattnercb40a372003-03-10 18:24:17 +00001806 }
1807
Chris Lattner14840892004-08-01 19:42:59 +00001808 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-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 Lattner14840892004-08-01 19:42:59 +00001812 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001813 return BinaryOperator::createOr(Op0, Op1);
Chris Lattnerc8802d22003-03-11 00:12:48 +00001814
Chris Lattneraa9c1f12003-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 Lattner7e708292002-06-25 16:13:24 +00001820 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001821}
1822
Chris Lattnera96879a2004-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 Lattner7e708292002-06-25 16:13:24 +00001853Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001854 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00001855 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1856 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00001857
1858 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00001859 if (Op0 == Op1)
1860 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00001861
Chris Lattnere87597f2004-10-16 18:11:37 +00001862 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
1863 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
1864
Chris Lattner3ccd17e2003-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 Lattner8b170942002-08-09 23:47:40 +00001868 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1869
Chris Lattner3ccd17e2003-08-13 05:38:46 +00001870
Chris Lattner8b170942002-08-09 23:47:40 +00001871 // setcc's with boolean values can always be turned into bitwise operations
1872 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-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 Lattner48595f12004-06-10 02:07:29 +00001876 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00001877 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00001878 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00001879 }
Chris Lattner5dbef222004-08-11 00:50:51 +00001880 case Instruction::SetNE:
1881 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00001882
Chris Lattner5dbef222004-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 Lattner8b170942002-08-09 23:47:40 +00001892 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-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 Lattner8b170942002-08-09 23:47:40 +00001900 }
1901
Chris Lattner2be51ae2004-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 Lattner8b170942002-08-09 23:47:40 +00001904 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera96879a2004-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 Lattner3c6a0d42004-05-25 06:32:08 +00001949 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00001950 switch (LHSI->getOpcode()) {
Chris Lattner4e998b22004-09-29 05:07:12 +00001951 case Instruction::PHI:
1952 if (Instruction *NV = FoldOpIntoPhi(I))
1953 return NV;
1954 break;
Chris Lattner648e3bc2004-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 Lattner0cba71b2004-09-28 17:54:07 +00001973 Shift->getType()->isUnsigned();
Chris Lattner648e3bc2004-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 Lattnerf0cacc02004-07-21 20:14:10 +00001978 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattner648e3bc2004-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 Lattner0cba71b2004-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 Lattner83c4ec02004-09-27 19:29:18 +00001991
Chris Lattner648e3bc2004-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 Lattner0cba71b2004-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 Lattner648e3bc2004-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 Lattner5eb91942004-07-21 19:50:44 +00002014 }
2015 }
Chris Lattner457dd822004-06-09 07:59:58 +00002016 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00002017 }
2018 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00002019
Chris Lattnerf6d1d7d2004-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 Lattnerdd763f42004-09-29 03:16:24 +00002023 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00002024 if (SrcTy == Type::BoolTy) SrcBits = 1;
Chris Lattnerdd763f42004-09-29 03:16:24 +00002025 unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00002026 if (LHSI->getType() == Type::BoolTy) DestBits = 1;
Chris Lattnerd308f8a2004-11-02 03:50:32 +00002027 if (SrcBits < DestBits &&
2028 // FIXME: Reenable the code below for < and >. However, we have
2029 // to handle the cases when the source of the cast and the dest of
2030 // the cast have different signs. e.g:
2031 // (cast sbyte %X to uint) >u 255U -> X <s (sbyte)0
2032 (I.getOpcode() == Instruction::SetEQ ||
2033 I.getOpcode() == Instruction::SetNE)) {
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00002034 // Check to see if the comparison is always true or false.
2035 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
2036 if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00002037 switch (I.getOpcode()) {
2038 default: assert(0 && "unknown integer comparison");
Chris Lattnerd308f8a2004-11-02 03:50:32 +00002039#if 0
2040 case Instruction::SetLT: {
2041 Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
2042 Max = ConstantExpr::getCast(Max, LHSI->getType());
2043 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
2044 }
2045 case Instruction::SetGT: {
2046 Constant *Min = ConstantIntegral::getMinValue(SrcTy);
2047 Min = ConstantExpr::getCast(Min, LHSI->getType());
2048 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
2049 }
2050#endif
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00002051 case Instruction::SetEQ:
2052 return ReplaceInstUsesWith(I, ConstantBool::False);
2053 case Instruction::SetNE:
2054 return ReplaceInstUsesWith(I, ConstantBool::True);
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00002055 }
2056 }
2057
Chris Lattnerd308f8a2004-11-02 03:50:32 +00002058 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0), NewCst);
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00002059 }
2060 }
2061 break;
2062 }
Chris Lattner18d19ca2004-09-28 18:22:15 +00002063 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2064 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2065 switch (I.getOpcode()) {
2066 default: break;
2067 case Instruction::SetEQ:
2068 case Instruction::SetNE: {
2069 // If we are comparing against bits always shifted out, the
2070 // comparison cannot succeed.
2071 Constant *Comp =
2072 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2073 if (Comp != CI) {// Comparing against a bit that we know is zero.
2074 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2075 Constant *Cst = ConstantBool::get(IsSetNE);
2076 return ReplaceInstUsesWith(I, Cst);
2077 }
2078
2079 if (LHSI->hasOneUse()) {
2080 // Otherwise strength reduce the shift into an and.
2081 unsigned ShAmtVal = ShAmt->getValue();
2082 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2083 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2084
2085 Constant *Mask;
2086 if (CI->getType()->isUnsigned()) {
2087 Mask = ConstantUInt::get(CI->getType(), Val);
2088 } else if (ShAmtVal != 0) {
2089 Mask = ConstantSInt::get(CI->getType(), Val);
2090 } else {
2091 Mask = ConstantInt::getAllOnesValue(CI->getType());
2092 }
2093
2094 Instruction *AndI =
2095 BinaryOperator::createAnd(LHSI->getOperand(0),
2096 Mask, LHSI->getName()+".mask");
2097 Value *And = InsertNewInstBefore(AndI, I);
2098 return new SetCondInst(I.getOpcode(), And,
2099 ConstantExpr::getUShr(CI, ShAmt));
2100 }
2101 }
2102 }
2103 }
2104 break;
2105
Chris Lattner83c4ec02004-09-27 19:29:18 +00002106 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattnerf63f6472004-09-27 16:18:50 +00002107 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerf63f6472004-09-27 16:18:50 +00002108 switch (I.getOpcode()) {
2109 default: break;
2110 case Instruction::SetEQ:
2111 case Instruction::SetNE: {
2112 // If we are comparing against bits always shifted out, the
2113 // comparison cannot succeed.
2114 Constant *Comp =
2115 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2116
2117 if (Comp != CI) {// Comparing against a bit that we know is zero.
2118 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2119 Constant *Cst = ConstantBool::get(IsSetNE);
2120 return ReplaceInstUsesWith(I, Cst);
2121 }
2122
2123 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner18d19ca2004-09-28 18:22:15 +00002124 unsigned ShAmtVal = ShAmt->getValue();
2125
Chris Lattnerf63f6472004-09-27 16:18:50 +00002126 // Otherwise strength reduce the shift into an and.
2127 uint64_t Val = ~0ULL; // All ones.
2128 Val <<= ShAmtVal; // Shift over to the right spot.
2129
2130 Constant *Mask;
2131 if (CI->getType()->isUnsigned()) {
2132 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2133 Val &= (1ULL << TypeBits)-1;
2134 Mask = ConstantUInt::get(CI->getType(), Val);
2135 } else {
2136 Mask = ConstantSInt::get(CI->getType(), Val);
2137 }
2138
2139 Instruction *AndI =
2140 BinaryOperator::createAnd(LHSI->getOperand(0),
2141 Mask, LHSI->getName()+".mask");
2142 Value *And = InsertNewInstBefore(AndI, I);
2143 return new SetCondInst(I.getOpcode(), And,
2144 ConstantExpr::getShl(CI, ShAmt));
2145 }
2146 break;
2147 }
2148 }
2149 }
2150 break;
Chris Lattner0c967662004-09-24 15:21:34 +00002151
Chris Lattnera96879a2004-09-29 17:40:11 +00002152 case Instruction::Div:
2153 // Fold: (div X, C1) op C2 -> range check
2154 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2155 // Fold this div into the comparison, producing a range check.
2156 // Determine, based on the divide type, what the range is being
2157 // checked. If there is an overflow on the low or high side, remember
2158 // it, otherwise compute the range [low, hi) bounding the new value.
2159 bool LoOverflow = false, HiOverflow = 0;
2160 ConstantInt *LoBound = 0, *HiBound = 0;
2161
2162 ConstantInt *Prod;
2163 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2164
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00002165 Instruction::BinaryOps Opcode = I.getOpcode();
2166
Chris Lattnera96879a2004-09-29 17:40:11 +00002167 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2168 } else if (LHSI->getType()->isUnsigned()) { // udiv
2169 LoBound = Prod;
2170 LoOverflow = ProdOV;
2171 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2172 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2173 if (CI->isNullValue()) { // (X / pos) op 0
2174 // Can't overflow.
2175 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2176 HiBound = DivRHS;
2177 } else if (isPositive(CI)) { // (X / pos) op pos
2178 LoBound = Prod;
2179 LoOverflow = ProdOV;
2180 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2181 } else { // (X / pos) op neg
2182 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2183 LoOverflow = AddWithOverflow(LoBound, Prod,
2184 cast<ConstantInt>(DivRHSH));
2185 HiBound = Prod;
2186 HiOverflow = ProdOV;
2187 }
2188 } else { // Divisor is < 0.
2189 if (CI->isNullValue()) { // (X / neg) op 0
2190 LoBound = AddOne(DivRHS);
2191 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2192 } else if (isPositive(CI)) { // (X / neg) op pos
2193 HiOverflow = LoOverflow = ProdOV;
2194 if (!LoOverflow)
2195 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2196 HiBound = AddOne(Prod);
2197 } else { // (X / neg) op neg
2198 LoBound = Prod;
2199 LoOverflow = HiOverflow = ProdOV;
2200 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2201 }
Chris Lattner340a05f2004-10-08 19:15:44 +00002202
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00002203 // Dividing by a negate swaps the condition.
2204 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattnera96879a2004-09-29 17:40:11 +00002205 }
2206
2207 if (LoBound) {
2208 Value *X = LHSI->getOperand(0);
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00002209 switch (Opcode) {
Chris Lattnera96879a2004-09-29 17:40:11 +00002210 default: assert(0 && "Unhandled setcc opcode!");
2211 case Instruction::SetEQ:
2212 if (LoOverflow && HiOverflow)
2213 return ReplaceInstUsesWith(I, ConstantBool::False);
2214 else if (HiOverflow)
2215 return new SetCondInst(Instruction::SetGE, X, LoBound);
2216 else if (LoOverflow)
2217 return new SetCondInst(Instruction::SetLT, X, HiBound);
2218 else
2219 return InsertRangeTest(X, LoBound, HiBound, true, I);
2220 case Instruction::SetNE:
2221 if (LoOverflow && HiOverflow)
2222 return ReplaceInstUsesWith(I, ConstantBool::True);
2223 else if (HiOverflow)
2224 return new SetCondInst(Instruction::SetLT, X, LoBound);
2225 else if (LoOverflow)
2226 return new SetCondInst(Instruction::SetGE, X, HiBound);
2227 else
2228 return InsertRangeTest(X, LoBound, HiBound, false, I);
2229 case Instruction::SetLT:
2230 if (LoOverflow)
2231 return ReplaceInstUsesWith(I, ConstantBool::False);
2232 return new SetCondInst(Instruction::SetLT, X, LoBound);
2233 case Instruction::SetGT:
2234 if (HiOverflow)
2235 return ReplaceInstUsesWith(I, ConstantBool::False);
2236 return new SetCondInst(Instruction::SetGE, X, HiBound);
2237 }
2238 }
2239 }
2240 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00002241 case Instruction::Select:
2242 // If either operand of the select is a constant, we can fold the
2243 // comparison into the select arms, which will cause one to be
2244 // constant folded and the select turned into a bitwise or.
2245 Value *Op1 = 0, *Op2 = 0;
2246 if (LHSI->hasOneUse()) {
Chris Lattner457dd822004-06-09 07:59:58 +00002247 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2be51ae2004-06-09 04:24:29 +00002248 // Fold the known value into the constant operand.
2249 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2250 // Insert a new SetCC of the other select operand.
2251 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner457dd822004-06-09 07:59:58 +00002252 LHSI->getOperand(2), CI,
Chris Lattner2be51ae2004-06-09 04:24:29 +00002253 I.getName()), I);
Chris Lattner457dd822004-06-09 07:59:58 +00002254 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2be51ae2004-06-09 04:24:29 +00002255 // Fold the known value into the constant operand.
2256 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2257 // Insert a new SetCC of the other select operand.
2258 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner457dd822004-06-09 07:59:58 +00002259 LHSI->getOperand(1), CI,
Chris Lattner2be51ae2004-06-09 04:24:29 +00002260 I.getName()), I);
2261 }
Chris Lattner2be51ae2004-06-09 04:24:29 +00002262 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00002263
2264 if (Op1)
2265 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2266 break;
2267 }
2268
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002269 // Simplify seteq and setne instructions...
2270 if (I.getOpcode() == Instruction::SetEQ ||
2271 I.getOpcode() == Instruction::SetNE) {
2272 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2273
Chris Lattner00b1a7e2003-07-23 17:26:36 +00002274 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002275 // operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00002276 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2277 switch (BO->getOpcode()) {
Chris Lattner3571b722004-07-06 07:38:18 +00002278 case Instruction::Rem:
2279 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2280 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2281 BO->hasOneUse() &&
2282 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2283 if (unsigned L2 =
2284 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2285 const Type *UTy = BO->getType()->getUnsignedVersion();
2286 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2287 UTy, "tmp"), I);
2288 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2289 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2290 RHSCst, BO->getName()), I);
2291 return BinaryOperator::create(I.getOpcode(), NewRem,
2292 Constant::getNullValue(UTy));
2293 }
2294 break;
2295
Chris Lattner934754b2003-08-13 05:33:12 +00002296 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00002297 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2298 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00002299 if (BO->hasOneUse())
2300 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2301 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00002302 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00002303 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2304 // efficiently invertible, or if the add has just this one use.
2305 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner15d58b62004-06-27 22:51:36 +00002306
Chris Lattner934754b2003-08-13 05:33:12 +00002307 if (Value *NegVal = dyn_castNegVal(BOp1))
2308 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2309 else if (Value *NegVal = dyn_castNegVal(BOp0))
2310 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00002311 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00002312 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2313 BO->setName("");
2314 InsertNewInstBefore(Neg, I);
2315 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2316 }
2317 }
2318 break;
2319 case Instruction::Xor:
2320 // For the xor case, we can xor two constants together, eliminating
2321 // the explicit xor.
2322 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2323 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002324 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00002325
2326 // FALLTHROUGH
2327 case Instruction::Sub:
2328 // Replace (([sub|xor] A, B) != 0) with (A != B)
2329 if (CI->isNullValue())
2330 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2331 BO->getOperand(1));
2332 break;
2333
2334 case Instruction::Or:
2335 // If bits are being or'd in that are not present in the constant we
2336 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00002337 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00002338 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00002339 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002340 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00002341 }
Chris Lattner934754b2003-08-13 05:33:12 +00002342 break;
2343
2344 case Instruction::And:
2345 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002346 // If bits are being compared against that are and'd out, then the
2347 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00002348 if (!ConstantExpr::getAnd(CI,
2349 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002350 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00002351
Chris Lattner457dd822004-06-09 07:59:58 +00002352 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00002353 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00002354 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2355 Instruction::SetNE, Op0,
2356 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00002357
Chris Lattner934754b2003-08-13 05:33:12 +00002358 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2359 // to be a signed value as appropriate.
2360 if (isSignBit(BOC)) {
2361 Value *X = BO->getOperand(0);
2362 // If 'X' is not signed, insert a cast now...
2363 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00002364 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner83c4ec02004-09-27 19:29:18 +00002365 X = InsertCastBefore(X, DestTy, I);
Chris Lattner934754b2003-08-13 05:33:12 +00002366 }
2367 return new SetCondInst(isSetNE ? Instruction::SetLT :
2368 Instruction::SetGE, X,
2369 Constant::getNullValue(X->getType()));
2370 }
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002371
Chris Lattner83c4ec02004-09-27 19:29:18 +00002372 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002373 if (CI->isNullValue() && isHighOnes(BOC)) {
2374 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00002375 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002376
2377 // If 'X' is signed, insert a cast now.
Chris Lattner83c4ec02004-09-27 19:29:18 +00002378 if (NegX->getType()->isSigned()) {
2379 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2380 X = InsertCastBefore(X, DestTy, I);
2381 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002382 }
2383
2384 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattner83c4ec02004-09-27 19:29:18 +00002385 Instruction::SetLT, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002386 }
2387
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002388 }
Chris Lattner934754b2003-08-13 05:33:12 +00002389 default: break;
2390 }
2391 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002392 } else { // Not a SetEQ/SetNE
2393 // If the LHS is a cast from an integral value of the same size,
2394 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2395 Value *CastOp = Cast->getOperand(0);
2396 const Type *SrcTy = CastOp->getType();
2397 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2398 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2399 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2400 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2401 "Source and destination signednesses should differ!");
2402 if (Cast->getType()->isSigned()) {
2403 // If this is a signed comparison, check for comparisons in the
2404 // vicinity of zero.
2405 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2406 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00002407 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002408 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2409 else if (I.getOpcode() == Instruction::SetGT &&
2410 cast<ConstantSInt>(CI)->getValue() == -1)
2411 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00002412 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002413 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2414 } else {
2415 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2416 if (I.getOpcode() == Instruction::SetLT &&
2417 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2418 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00002419 return BinaryOperator::createSetGT(CastOp,
2420 ConstantSInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002421 else if (I.getOpcode() == Instruction::SetGT &&
2422 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2423 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00002424 return BinaryOperator::createSetLT(CastOp,
2425 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002426 }
2427 }
2428 }
Chris Lattner40f5d702003-06-04 05:10:11 +00002429 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002430 }
2431
Chris Lattnerde90b762003-11-03 04:25:02 +00002432 // Test to see if the operands of the setcc are casted versions of other
2433 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00002434 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2435 Value *CastOp0 = CI->getOperand(0);
2436 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner0cea42a2004-03-13 23:54:27 +00002437 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattnerde90b762003-11-03 04:25:02 +00002438 (I.getOpcode() == Instruction::SetEQ ||
2439 I.getOpcode() == Instruction::SetNE)) {
2440 // We keep moving the cast from the left operand over to the right
2441 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00002442 Op0 = CastOp0;
Chris Lattnerde90b762003-11-03 04:25:02 +00002443
2444 // If operand #1 is a cast instruction, see if we can eliminate it as
2445 // well.
Chris Lattner68708052003-11-03 05:17:03 +00002446 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2447 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00002448 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00002449 Op1 = CI2->getOperand(0);
Chris Lattnerde90b762003-11-03 04:25:02 +00002450
2451 // If Op1 is a constant, we can fold the cast into the constant.
2452 if (Op1->getType() != Op0->getType())
2453 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2454 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2455 } else {
2456 // Otherwise, cast the RHS right before the setcc
2457 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2458 InsertNewInstBefore(cast<Instruction>(Op1), I);
2459 }
2460 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2461 }
2462
Chris Lattner68708052003-11-03 05:17:03 +00002463 // Handle the special case of: setcc (cast bool to X), <cst>
2464 // This comes up when you have code like
2465 // int X = A < B;
2466 // if (X) ...
2467 // For generality, we handle any zero-extension of any operand comparison
2468 // with a constant.
2469 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2470 const Type *SrcTy = CastOp0->getType();
2471 const Type *DestTy = Op0->getType();
2472 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2473 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2474 // Ok, we have an expansion of operand 0 into a new type. Get the
2475 // constant value, masink off bits which are not set in the RHS. These
2476 // could be set if the destination value is signed.
2477 uint64_t ConstVal = ConstantRHS->getRawValue();
2478 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2479
2480 // If the constant we are comparing it with has high bits set, which
2481 // don't exist in the original value, the values could never be equal,
2482 // because the source would be zero extended.
2483 unsigned SrcBits =
2484 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner1bcc70d2003-11-05 17:31:36 +00002485 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2486 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner68708052003-11-03 05:17:03 +00002487 switch (I.getOpcode()) {
2488 default: assert(0 && "Unknown comparison type!");
2489 case Instruction::SetEQ:
2490 return ReplaceInstUsesWith(I, ConstantBool::False);
2491 case Instruction::SetNE:
2492 return ReplaceInstUsesWith(I, ConstantBool::True);
2493 case Instruction::SetLT:
2494 case Instruction::SetLE:
2495 if (DestTy->isSigned() && HasSignBit)
2496 return ReplaceInstUsesWith(I, ConstantBool::False);
2497 return ReplaceInstUsesWith(I, ConstantBool::True);
2498 case Instruction::SetGT:
2499 case Instruction::SetGE:
2500 if (DestTy->isSigned() && HasSignBit)
2501 return ReplaceInstUsesWith(I, ConstantBool::True);
2502 return ReplaceInstUsesWith(I, ConstantBool::False);
2503 }
2504 }
2505
2506 // Otherwise, we can replace the setcc with a setcc of the smaller
2507 // operand value.
2508 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2509 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2510 }
2511 }
2512 }
Chris Lattner7e708292002-06-25 16:13:24 +00002513 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002514}
2515
2516
2517
Chris Lattnerea340052003-03-10 19:16:08 +00002518Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002519 assert(I.getOperand(1)->getType() == Type::UByteTy);
2520 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00002521 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002522
2523 // shl X, 0 == X and shr X, 0 == X
2524 // shl 0, X == 0 and shr 0, X == 0
2525 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00002526 Op0 == Constant::getNullValue(Op0->getType()))
2527 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002528
Chris Lattnere87597f2004-10-16 18:11:37 +00002529 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
2530 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner79a564c2004-10-16 23:28:04 +00002531 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere87597f2004-10-16 18:11:37 +00002532 else // undef << X -> 0 AND undef >>u X -> 0
2533 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2534 }
2535 if (isa<UndefValue>(Op1)) {
2536 if (isLeftShift || I.getType()->isUnsigned())
2537 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2538 else
2539 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
2540 }
2541
Chris Lattnerdf17af12003-08-12 21:53:41 +00002542 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2543 if (!isLeftShift)
2544 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2545 if (CSI->isAllOnesValue())
2546 return ReplaceInstUsesWith(I, CSI);
2547
Chris Lattner2eefe512004-04-09 19:05:30 +00002548 // Try to fold constant and into select arguments.
2549 if (isa<Constant>(Op0))
2550 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2551 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2552 return R;
2553
Chris Lattner3f5b8772002-05-06 16:14:14 +00002554 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002555 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2556 // of a signed value.
2557 //
Chris Lattnerea340052003-03-10 19:16:08 +00002558 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner8adac752004-02-23 20:30:06 +00002559 if (CUI->getValue() >= TypeBits) {
2560 if (!Op0->getType()->isSigned() || isLeftShift)
2561 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2562 else {
2563 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2564 return &I;
2565 }
2566 }
Chris Lattnerf2836082002-09-10 23:04:09 +00002567
Chris Lattnere92d2f42003-08-13 04:18:28 +00002568 // ((X*C1) << C2) == (X * (C1 << C2))
2569 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2570 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2571 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002572 return BinaryOperator::createMul(BO->getOperand(0),
2573 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnere92d2f42003-08-13 04:18:28 +00002574
Chris Lattner2eefe512004-04-09 19:05:30 +00002575 // Try to fold constant and into select arguments.
2576 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2577 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2578 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002579 if (isa<PHINode>(Op0))
2580 if (Instruction *NV = FoldOpIntoPhi(I))
2581 return NV;
Chris Lattnere92d2f42003-08-13 04:18:28 +00002582
Chris Lattnerdf17af12003-08-12 21:53:41 +00002583 // If the operand is an bitwise operator with a constant RHS, and the
2584 // shift is the only use, we can pull it out of the shift.
Chris Lattnerfd059242003-10-15 16:48:29 +00002585 if (Op0->hasOneUse())
Chris Lattnerdf17af12003-08-12 21:53:41 +00002586 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2587 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2588 bool isValid = true; // Valid only for And, Or, Xor
2589 bool highBitSet = false; // Transform if high bit of constant set?
2590
2591 switch (Op0BO->getOpcode()) {
2592 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00002593 case Instruction::Add:
2594 isValid = isLeftShift;
2595 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00002596 case Instruction::Or:
2597 case Instruction::Xor:
2598 highBitSet = false;
2599 break;
2600 case Instruction::And:
2601 highBitSet = true;
2602 break;
2603 }
2604
2605 // If this is a signed shift right, and the high bit is modified
2606 // by the logical operation, do not perform the transformation.
2607 // The highBitSet boolean indicates the value of the high bit of
2608 // the constant which would cause it to be modified for this
2609 // operation.
2610 //
2611 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2612 uint64_t Val = Op0C->getRawValue();
2613 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2614 }
2615
2616 if (isValid) {
Chris Lattner7c4049c2004-01-12 19:35:11 +00002617 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdf17af12003-08-12 21:53:41 +00002618
2619 Instruction *NewShift =
2620 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2621 Op0BO->getName());
2622 Op0BO->setName("");
2623 InsertNewInstBefore(NewShift, I);
2624
2625 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2626 NewRHS);
2627 }
2628 }
2629
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002630 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdf17af12003-08-12 21:53:41 +00002631 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattner943c7132003-07-24 18:38:56 +00002632 if (ConstantUInt *ShiftAmt1C =
2633 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002634 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2635 unsigned ShiftAmt2 = CUI->getValue();
2636
2637 // Check for (A << c1) << c2 and (A >> c1) >> c2
2638 if (I.getOpcode() == Op0SI->getOpcode()) {
2639 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattner8adac752004-02-23 20:30:06 +00002640 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2641 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002642 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2643 ConstantUInt::get(Type::UByteTy, Amt));
2644 }
2645
Chris Lattner943c7132003-07-24 18:38:56 +00002646 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2647 // signed types, we can only support the (A >> c1) << c2 configuration,
2648 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdf17af12003-08-12 21:53:41 +00002649 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002650 // Calculate bitmask for what gets shifted off the edge...
2651 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00002652 if (isLeftShift)
Chris Lattner48595f12004-06-10 02:07:29 +00002653 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdf17af12003-08-12 21:53:41 +00002654 else
Chris Lattner48595f12004-06-10 02:07:29 +00002655 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002656
2657 Instruction *Mask =
Chris Lattner48595f12004-06-10 02:07:29 +00002658 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2659 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002660 InsertNewInstBefore(Mask, I);
2661
2662 // Figure out what flavor of shift we should use...
2663 if (ShiftAmt1 == ShiftAmt2)
2664 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2665 else if (ShiftAmt1 < ShiftAmt2) {
2666 return new ShiftInst(I.getOpcode(), Mask,
2667 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2668 } else {
2669 return new ShiftInst(Op0SI->getOpcode(), Mask,
2670 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2671 }
2672 }
2673 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002674 }
Chris Lattner6eaeb572002-10-08 16:16:40 +00002675
Chris Lattner3f5b8772002-05-06 16:14:14 +00002676 return 0;
2677}
2678
Chris Lattnerbee7e762004-07-20 00:59:32 +00002679enum CastType {
2680 Noop = 0,
2681 Truncate = 1,
2682 Signext = 2,
2683 Zeroext = 3
2684};
2685
2686/// getCastType - In the future, we will split the cast instruction into these
2687/// various types. Until then, we have to do the analysis here.
2688static CastType getCastType(const Type *Src, const Type *Dest) {
2689 assert(Src->isIntegral() && Dest->isIntegral() &&
2690 "Only works on integral types!");
2691 unsigned SrcSize = Src->getPrimitiveSize()*8;
2692 if (Src == Type::BoolTy) SrcSize = 1;
2693 unsigned DestSize = Dest->getPrimitiveSize()*8;
2694 if (Dest == Type::BoolTy) DestSize = 1;
2695
2696 if (SrcSize == DestSize) return Noop;
2697 if (SrcSize > DestSize) return Truncate;
2698 if (Src->isSigned()) return Signext;
2699 return Zeroext;
2700}
2701
Chris Lattner3f5b8772002-05-06 16:14:14 +00002702
Chris Lattnera1be5662002-05-02 17:06:02 +00002703// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2704// instruction.
2705//
Chris Lattner24c8e382003-07-24 17:35:25 +00002706static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner59a20772004-07-20 05:21:00 +00002707 const Type *DstTy, TargetData *TD) {
Chris Lattnera1be5662002-05-02 17:06:02 +00002708
Chris Lattner8fd217c2002-08-02 20:00:25 +00002709 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2710 // are identical and the bits don't get reinterpreted (for example
Chris Lattner5eb91942004-07-21 19:50:44 +00002711 // int->float->int would not be allowed).
Misha Brukmanf117cc92003-05-20 18:45:36 +00002712 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner8fd217c2002-08-02 20:00:25 +00002713 return true;
Chris Lattnera1be5662002-05-02 17:06:02 +00002714
Chris Lattnere8a7e592004-07-21 04:27:24 +00002715 // If we are casting between pointer and integer types, treat pointers as
2716 // integers of the appropriate size for the code below.
2717 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2718 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2719 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner59a20772004-07-20 05:21:00 +00002720
Chris Lattnera1be5662002-05-02 17:06:02 +00002721 // Allow free casting and conversion of sizes as long as the sign doesn't
2722 // change...
Chris Lattner0c4e8862002-09-03 01:08:28 +00002723 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattnerbee7e762004-07-20 00:59:32 +00002724 CastType FirstCast = getCastType(SrcTy, MidTy);
2725 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner8fd217c2002-08-02 20:00:25 +00002726
Chris Lattnerbee7e762004-07-20 00:59:32 +00002727 // Capture the effect of these two casts. If the result is a legal cast,
2728 // the CastType is stored here, otherwise a special code is used.
2729 static const unsigned CastResult[] = {
2730 // First cast is noop
2731 0, 1, 2, 3,
2732 // First cast is a truncate
2733 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2734 // First cast is a sign ext
Chris Lattner5eb91942004-07-21 19:50:44 +00002735 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattnerbee7e762004-07-20 00:59:32 +00002736 // First cast is a zero ext
Chris Lattner5eb91942004-07-21 19:50:44 +00002737 3, 5, 3, 3,
Chris Lattnerbee7e762004-07-20 00:59:32 +00002738 };
2739
2740 unsigned Result = CastResult[FirstCast*4+SecondCast];
2741 switch (Result) {
2742 default: assert(0 && "Illegal table value!");
2743 case 0:
2744 case 1:
2745 case 2:
2746 case 3:
2747 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2748 // truncates, we could eliminate more casts.
2749 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2750 case 4:
2751 return false; // Not possible to eliminate this here.
2752 case 5:
Chris Lattner5eb91942004-07-21 19:50:44 +00002753 // Sign or zero extend followed by truncate is always ok if the result
2754 // is a truncate or noop.
2755 CastType ResultCast = getCastType(SrcTy, DstTy);
2756 if (ResultCast == Noop || ResultCast == Truncate)
2757 return true;
2758 // Otherwise we are still growing the value, we are only safe if the
2759 // result will match the sign/zeroextendness of the result.
2760 return ResultCast == FirstCast;
Chris Lattner3ecce662002-08-15 16:15:25 +00002761 }
Chris Lattner8fd217c2002-08-02 20:00:25 +00002762 }
Chris Lattnera1be5662002-05-02 17:06:02 +00002763 return false;
2764}
2765
Chris Lattner59a20772004-07-20 05:21:00 +00002766static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattner24c8e382003-07-24 17:35:25 +00002767 if (V->getType() == Ty || isa<Constant>(V)) return false;
2768 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner59a20772004-07-20 05:21:00 +00002769 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2770 TD))
Chris Lattner24c8e382003-07-24 17:35:25 +00002771 return false;
2772 return true;
2773}
2774
2775/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2776/// InsertBefore instruction. This is specialized a bit to avoid inserting
2777/// casts that are known to not do anything...
2778///
2779Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2780 Instruction *InsertBefore) {
2781 if (V->getType() == DestTy) return V;
2782 if (Constant *C = dyn_cast<Constant>(V))
2783 return ConstantExpr::getCast(C, DestTy);
2784
2785 CastInst *CI = new CastInst(V, DestTy, V->getName());
2786 InsertNewInstBefore(CI, *InsertBefore);
2787 return CI;
2788}
Chris Lattnera1be5662002-05-02 17:06:02 +00002789
2790// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002791//
Chris Lattner7e708292002-06-25 16:13:24 +00002792Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00002793 Value *Src = CI.getOperand(0);
2794
Chris Lattnera1be5662002-05-02 17:06:02 +00002795 // If the user is casting a value to the same type, eliminate this cast
2796 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00002797 if (CI.getType() == Src->getType())
2798 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00002799
Chris Lattnere87597f2004-10-16 18:11:37 +00002800 if (isa<UndefValue>(Src)) // cast undef -> undef
2801 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
2802
Chris Lattnera1be5662002-05-02 17:06:02 +00002803 // If casting the result of another cast instruction, try to eliminate this
2804 // one!
2805 //
Chris Lattner79d35b32003-06-23 21:59:52 +00002806 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00002807 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner59a20772004-07-20 05:21:00 +00002808 CSrc->getType(), CI.getType(), TD)) {
Chris Lattnera1be5662002-05-02 17:06:02 +00002809 // This instruction now refers directly to the cast's src operand. This
2810 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00002811 CI.setOperand(0, CSrc->getOperand(0));
2812 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00002813 }
2814
Chris Lattner8fd217c2002-08-02 20:00:25 +00002815 // If this is an A->B->A cast, and we are dealing with integral types, try
2816 // to convert this into a logical 'and' instruction.
2817 //
2818 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00002819 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner8fd217c2002-08-02 20:00:25 +00002820 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2821 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2822 assert(CSrc->getType() != Type::ULongTy &&
2823 "Cannot have type bigger than ulong!");
Chris Lattnerbd4ecf72003-05-26 23:41:32 +00002824 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner8fd217c2002-08-02 20:00:25 +00002825 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattner48595f12004-06-10 02:07:29 +00002826 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner8fd217c2002-08-02 20:00:25 +00002827 }
2828 }
2829
Chris Lattnera710ddc2004-05-25 04:29:21 +00002830 // If this is a cast to bool, turn it into the appropriate setne instruction.
2831 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00002832 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00002833 Constant::getNullValue(CI.getOperand(0)->getType()));
2834
Chris Lattner797249b2003-06-21 23:12:02 +00002835 // If casting the result of a getelementptr instruction with no offset, turn
2836 // this into a cast of the original pointer!
2837 //
Chris Lattner79d35b32003-06-23 21:59:52 +00002838 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00002839 bool AllZeroOperands = true;
2840 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2841 if (!isa<Constant>(GEP->getOperand(i)) ||
2842 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2843 AllZeroOperands = false;
2844 break;
2845 }
2846 if (AllZeroOperands) {
2847 CI.setOperand(0, GEP->getOperand(0));
2848 return &CI;
2849 }
2850 }
2851
Chris Lattnerbc61e662003-11-02 05:57:39 +00002852 // If we are casting a malloc or alloca to a pointer to a type of the same
2853 // size, rewrite the allocation instruction to allocate the "right" type.
2854 //
2855 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerfc07a342003-11-02 06:54:48 +00002856 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerbc61e662003-11-02 05:57:39 +00002857 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2858 // Get the type really allocated and the type casted to...
2859 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerbc61e662003-11-02 05:57:39 +00002860 const Type *CastElTy = PTy->getElementType();
Chris Lattnerfae10102004-07-06 19:28:42 +00002861 if (AllocElTy->isSized() && CastElTy->isSized()) {
2862 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2863 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner1bcc70d2003-11-05 17:31:36 +00002864
Chris Lattnerfae10102004-07-06 19:28:42 +00002865 // If the allocation is for an even multiple of the cast type size
2866 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2867 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerbc61e662003-11-02 05:57:39 +00002868 AllocElTySize/CastElTySize);
Chris Lattnerfae10102004-07-06 19:28:42 +00002869 std::string Name = AI->getName(); AI->setName("");
2870 AllocationInst *New;
2871 if (isa<MallocInst>(AI))
2872 New = new MallocInst(CastElTy, Amt, Name);
2873 else
2874 New = new AllocaInst(CastElTy, Amt, Name);
2875 InsertNewInstBefore(New, *AI);
2876 return ReplaceInstUsesWith(CI, New);
2877 }
Chris Lattnerbc61e662003-11-02 05:57:39 +00002878 }
2879 }
2880
Chris Lattner4e998b22004-09-29 05:07:12 +00002881 if (isa<PHINode>(Src))
2882 if (Instruction *NV = FoldOpIntoPhi(CI))
2883 return NV;
2884
Chris Lattner24c8e382003-07-24 17:35:25 +00002885 // If the source value is an instruction with only this use, we can attempt to
2886 // propagate the cast into the instruction. Also, only handle integral types
2887 // for now.
2888 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerfd059242003-10-15 16:48:29 +00002889 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00002890 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2891 const Type *DestTy = CI.getType();
2892 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2893 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2894
2895 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2896 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2897
2898 switch (SrcI->getOpcode()) {
2899 case Instruction::Add:
2900 case Instruction::Mul:
2901 case Instruction::And:
2902 case Instruction::Or:
2903 case Instruction::Xor:
2904 // If we are discarding information, or just changing the sign, rewrite.
2905 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2906 // Don't insert two casts if they cannot be eliminated. We allow two
2907 // casts to be inserted if the sizes are the same. This could only be
2908 // converting signedness, which is a noop.
Chris Lattner59a20772004-07-20 05:21:00 +00002909 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2910 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00002911 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2912 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2913 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2914 ->getOpcode(), Op0c, Op1c);
2915 }
2916 }
2917 break;
2918 case Instruction::Shl:
2919 // Allow changing the sign of the source operand. Do not allow changing
2920 // the size of the shift, UNLESS the shift amount is a constant. We
2921 // mush not change variable sized shifts to a smaller size, because it
2922 // is undefined to shift more bits out than exist in the value.
2923 if (DestBitSize == SrcBitSize ||
2924 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2925 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2926 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2927 }
2928 break;
2929 }
2930 }
2931
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002932 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00002933}
2934
Chris Lattnere576b912004-04-09 23:46:01 +00002935/// GetSelectFoldableOperands - We want to turn code that looks like this:
2936/// %C = or %A, %B
2937/// %D = select %cond, %C, %A
2938/// into:
2939/// %C = select %cond, %B, 0
2940/// %D = or %A, %C
2941///
2942/// Assuming that the specified instruction is an operand to the select, return
2943/// a bitmask indicating which operands of this instruction are foldable if they
2944/// equal the other incoming value of the select.
2945///
2946static unsigned GetSelectFoldableOperands(Instruction *I) {
2947 switch (I->getOpcode()) {
2948 case Instruction::Add:
2949 case Instruction::Mul:
2950 case Instruction::And:
2951 case Instruction::Or:
2952 case Instruction::Xor:
2953 return 3; // Can fold through either operand.
2954 case Instruction::Sub: // Can only fold on the amount subtracted.
2955 case Instruction::Shl: // Can only fold on the shift amount.
2956 case Instruction::Shr:
2957 return 1;
2958 default:
2959 return 0; // Cannot fold
2960 }
2961}
2962
2963/// GetSelectFoldableConstant - For the same transformation as the previous
2964/// function, return the identity constant that goes into the select.
2965static Constant *GetSelectFoldableConstant(Instruction *I) {
2966 switch (I->getOpcode()) {
2967 default: assert(0 && "This cannot happen!"); abort();
2968 case Instruction::Add:
2969 case Instruction::Sub:
2970 case Instruction::Or:
2971 case Instruction::Xor:
2972 return Constant::getNullValue(I->getType());
2973 case Instruction::Shl:
2974 case Instruction::Shr:
2975 return Constant::getNullValue(Type::UByteTy);
2976 case Instruction::And:
2977 return ConstantInt::getAllOnesValue(I->getType());
2978 case Instruction::Mul:
2979 return ConstantInt::get(I->getType(), 1);
2980 }
2981}
2982
Chris Lattner3d69f462004-03-12 05:52:32 +00002983Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002984 Value *CondVal = SI.getCondition();
2985 Value *TrueVal = SI.getTrueValue();
2986 Value *FalseVal = SI.getFalseValue();
2987
2988 // select true, X, Y -> X
2989 // select false, X, Y -> Y
2990 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner3d69f462004-03-12 05:52:32 +00002991 if (C == ConstantBool::True)
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002992 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00002993 else {
2994 assert(C == ConstantBool::False);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002995 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00002996 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002997
2998 // select C, X, X -> X
2999 if (TrueVal == FalseVal)
3000 return ReplaceInstUsesWith(SI, TrueVal);
3001
Chris Lattnere87597f2004-10-16 18:11:37 +00003002 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3003 return ReplaceInstUsesWith(SI, FalseVal);
3004 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3005 return ReplaceInstUsesWith(SI, TrueVal);
3006 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3007 if (isa<Constant>(TrueVal))
3008 return ReplaceInstUsesWith(SI, TrueVal);
3009 else
3010 return ReplaceInstUsesWith(SI, FalseVal);
3011 }
3012
Chris Lattner0c199a72004-04-08 04:43:23 +00003013 if (SI.getType() == Type::BoolTy)
3014 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3015 if (C == ConstantBool::True) {
3016 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00003017 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00003018 } else {
3019 // Change: A = select B, false, C --> A = and !B, C
3020 Value *NotCond =
3021 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3022 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00003023 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00003024 }
3025 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3026 if (C == ConstantBool::False) {
3027 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00003028 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00003029 } else {
3030 // Change: A = select B, C, true --> A = or !B, C
3031 Value *NotCond =
3032 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3033 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00003034 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00003035 }
3036 }
3037
Chris Lattner2eefe512004-04-09 19:05:30 +00003038 // Selecting between two integer constants?
3039 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3040 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3041 // select C, 1, 0 -> cast C to int
3042 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3043 return new CastInst(CondVal, SI.getType());
3044 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3045 // select C, 0, 1 -> cast !C to int
3046 Value *NotCond =
3047 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00003048 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00003049 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00003050 }
Chris Lattner457dd822004-06-09 07:59:58 +00003051
3052 // If one of the constants is zero (we know they can't both be) and we
3053 // have a setcc instruction with zero, and we have an 'and' with the
3054 // non-constant value, eliminate this whole mess. This corresponds to
3055 // cases like this: ((X & 27) ? 27 : 0)
3056 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3057 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3058 if ((IC->getOpcode() == Instruction::SetEQ ||
3059 IC->getOpcode() == Instruction::SetNE) &&
3060 isa<ConstantInt>(IC->getOperand(1)) &&
3061 cast<Constant>(IC->getOperand(1))->isNullValue())
3062 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3063 if (ICA->getOpcode() == Instruction::And &&
3064 isa<ConstantInt>(ICA->getOperand(1)) &&
3065 (ICA->getOperand(1) == TrueValC ||
3066 ICA->getOperand(1) == FalseValC) &&
3067 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3068 // Okay, now we know that everything is set up, we just don't
3069 // know whether we have a setne or seteq and whether the true or
3070 // false val is the zero.
3071 bool ShouldNotVal = !TrueValC->isNullValue();
3072 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3073 Value *V = ICA;
3074 if (ShouldNotVal)
3075 V = InsertNewInstBefore(BinaryOperator::create(
3076 Instruction::Xor, V, ICA->getOperand(1)), SI);
3077 return ReplaceInstUsesWith(SI, V);
3078 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00003079 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00003080
3081 // See if we are selecting two values based on a comparison of the two values.
3082 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3083 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3084 // Transform (X == Y) ? X : Y -> Y
3085 if (SCI->getOpcode() == Instruction::SetEQ)
3086 return ReplaceInstUsesWith(SI, FalseVal);
3087 // Transform (X != Y) ? X : Y -> X
3088 if (SCI->getOpcode() == Instruction::SetNE)
3089 return ReplaceInstUsesWith(SI, TrueVal);
3090 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3091
3092 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3093 // Transform (X == Y) ? Y : X -> X
3094 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00003095 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00003096 // Transform (X != Y) ? Y : X -> Y
3097 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00003098 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00003099 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3100 }
3101 }
Chris Lattner0c199a72004-04-08 04:43:23 +00003102
Chris Lattnere576b912004-04-09 23:46:01 +00003103 // See if we can fold the select into one of our operands.
3104 if (SI.getType()->isInteger()) {
3105 // See the comment above GetSelectFoldableOperands for a description of the
3106 // transformation we are doing here.
3107 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3108 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3109 !isa<Constant>(FalseVal))
3110 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3111 unsigned OpToFold = 0;
3112 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3113 OpToFold = 1;
3114 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3115 OpToFold = 2;
3116 }
3117
3118 if (OpToFold) {
3119 Constant *C = GetSelectFoldableConstant(TVI);
3120 std::string Name = TVI->getName(); TVI->setName("");
3121 Instruction *NewSel =
3122 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3123 Name);
3124 InsertNewInstBefore(NewSel, SI);
3125 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3126 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3127 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3128 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3129 else {
3130 assert(0 && "Unknown instruction!!");
3131 }
3132 }
3133 }
Chris Lattnera96879a2004-09-29 17:40:11 +00003134
Chris Lattnere576b912004-04-09 23:46:01 +00003135 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3136 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3137 !isa<Constant>(TrueVal))
3138 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3139 unsigned OpToFold = 0;
3140 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3141 OpToFold = 1;
3142 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3143 OpToFold = 2;
3144 }
3145
3146 if (OpToFold) {
3147 Constant *C = GetSelectFoldableConstant(FVI);
3148 std::string Name = FVI->getName(); FVI->setName("");
3149 Instruction *NewSel =
3150 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3151 Name);
3152 InsertNewInstBefore(NewSel, SI);
3153 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3154 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3155 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3156 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3157 else {
3158 assert(0 && "Unknown instruction!!");
3159 }
3160 }
3161 }
3162 }
Chris Lattner3d69f462004-03-12 05:52:32 +00003163 return 0;
3164}
3165
3166
Chris Lattner9fe38862003-06-19 17:00:31 +00003167// CallInst simplification
3168//
3169Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003170 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3171 // visitCallSite.
Chris Lattner35b9e482004-10-12 04:52:52 +00003172 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3173 bool Changed = false;
3174
3175 // memmove/cpy/set of zero bytes is a noop.
3176 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3177 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3178
3179 // FIXME: Increase alignment here.
3180
3181 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3182 if (CI->getRawValue() == 1) {
3183 // Replace the instruction with just byte operations. We would
3184 // transform other cases to loads/stores, but we don't know if
3185 // alignment is sufficient.
3186 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003187 }
3188
Chris Lattner35b9e482004-10-12 04:52:52 +00003189 // If we have a memmove and the source operation is a constant global,
3190 // then the source and dest pointers can't alias, so we can change this
3191 // into a call to memcpy.
3192 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3193 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3194 if (GVSrc->isConstant()) {
3195 Module *M = CI.getParent()->getParent()->getParent();
3196 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3197 CI.getCalledFunction()->getFunctionType());
3198 CI.setOperand(0, MemCpy);
3199 Changed = true;
3200 }
3201
3202 if (Changed) return &CI;
3203 }
3204
Chris Lattnera44d8a22003-10-07 22:32:43 +00003205 return visitCallSite(&CI);
Chris Lattner9fe38862003-06-19 17:00:31 +00003206}
3207
3208// InvokeInst simplification
3209//
3210Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00003211 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00003212}
3213
Chris Lattnera44d8a22003-10-07 22:32:43 +00003214// visitCallSite - Improvements for call and invoke instructions.
3215//
3216Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00003217 bool Changed = false;
3218
3219 // If the callee is a constexpr cast of a function, attempt to move the cast
3220 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00003221 if (transformConstExprCastCall(CS)) return 0;
3222
Chris Lattner6c266db2003-10-07 22:54:13 +00003223 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00003224
Chris Lattner17be6352004-10-18 02:59:09 +00003225 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3226 // This instruction is not reachable, just remove it. We insert a store to
3227 // undef so that we know that this code is not reachable, despite the fact
3228 // that we can't modify the CFG here.
3229 new StoreInst(ConstantBool::True,
3230 UndefValue::get(PointerType::get(Type::BoolTy)),
3231 CS.getInstruction());
3232
3233 if (!CS.getInstruction()->use_empty())
3234 CS.getInstruction()->
3235 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3236
3237 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3238 // Don't break the CFG, insert a dummy cond branch.
3239 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3240 ConstantBool::True, II);
Chris Lattnere87597f2004-10-16 18:11:37 +00003241 }
Chris Lattner17be6352004-10-18 02:59:09 +00003242 return EraseInstFromFunction(*CS.getInstruction());
3243 }
Chris Lattnere87597f2004-10-16 18:11:37 +00003244
Chris Lattner6c266db2003-10-07 22:54:13 +00003245 const PointerType *PTy = cast<PointerType>(Callee->getType());
3246 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3247 if (FTy->isVarArg()) {
3248 // See if we can optimize any arguments passed through the varargs area of
3249 // the call.
3250 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3251 E = CS.arg_end(); I != E; ++I)
3252 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3253 // If this cast does not effect the value passed through the varargs
3254 // area, we can eliminate the use of the cast.
3255 Value *Op = CI->getOperand(0);
3256 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3257 *I = Op;
3258 Changed = true;
3259 }
3260 }
3261 }
Chris Lattnera44d8a22003-10-07 22:32:43 +00003262
Chris Lattner6c266db2003-10-07 22:54:13 +00003263 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00003264}
3265
Chris Lattner9fe38862003-06-19 17:00:31 +00003266// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3267// attempt to move the cast to the arguments of the call/invoke.
3268//
3269bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3270 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3271 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattner9db07b92004-07-18 18:59:44 +00003272 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00003273 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00003274 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00003275 Instruction *Caller = CS.getInstruction();
3276
3277 // Okay, this is a cast from a function to a different type. Unless doing so
3278 // would cause a type conversion of one of our arguments, change this call to
3279 // be a direct call with arguments casted to the appropriate types.
3280 //
3281 const FunctionType *FT = Callee->getFunctionType();
3282 const Type *OldRetTy = Caller->getType();
3283
Chris Lattnerf78616b2004-01-14 06:06:08 +00003284 // Check to see if we are changing the return type...
3285 if (OldRetTy != FT->getReturnType()) {
3286 if (Callee->isExternal() &&
3287 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3288 !Caller->use_empty())
3289 return false; // Cannot transform this return value...
3290
3291 // If the callsite is an invoke instruction, and the return value is used by
3292 // a PHI node in a successor, we cannot change the return type of the call
3293 // because there is no place to put the cast instruction (without breaking
3294 // the critical edge). Bail out in this case.
3295 if (!Caller->use_empty())
3296 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3297 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3298 UI != E; ++UI)
3299 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3300 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00003301 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00003302 return false;
3303 }
Chris Lattner9fe38862003-06-19 17:00:31 +00003304
3305 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3306 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3307
3308 CallSite::arg_iterator AI = CS.arg_begin();
3309 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3310 const Type *ParamTy = FT->getParamType(i);
3311 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3312 if (Callee->isExternal() && !isConvertible) return false;
3313 }
3314
3315 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3316 Callee->isExternal())
3317 return false; // Do not delete arguments unless we have a function body...
3318
3319 // Okay, we decided that this is a safe thing to do: go ahead and start
3320 // inserting cast instructions as necessary...
3321 std::vector<Value*> Args;
3322 Args.reserve(NumActualArgs);
3323
3324 AI = CS.arg_begin();
3325 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3326 const Type *ParamTy = FT->getParamType(i);
3327 if ((*AI)->getType() == ParamTy) {
3328 Args.push_back(*AI);
3329 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00003330 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3331 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00003332 }
3333 }
3334
3335 // If the function takes more arguments than the call was taking, add them
3336 // now...
3337 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3338 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3339
3340 // If we are removing arguments to the function, emit an obnoxious warning...
3341 if (FT->getNumParams() < NumActualArgs)
3342 if (!FT->isVarArg()) {
3343 std::cerr << "WARNING: While resolving call to function '"
3344 << Callee->getName() << "' arguments were dropped!\n";
3345 } else {
3346 // Add all of the arguments in their promoted form to the arg list...
3347 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3348 const Type *PTy = getPromotedType((*AI)->getType());
3349 if (PTy != (*AI)->getType()) {
3350 // Must promote to pass through va_arg area!
3351 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3352 InsertNewInstBefore(Cast, *Caller);
3353 Args.push_back(Cast);
3354 } else {
3355 Args.push_back(*AI);
3356 }
3357 }
3358 }
3359
3360 if (FT->getReturnType() == Type::VoidTy)
3361 Caller->setName(""); // Void type should not have a name...
3362
3363 Instruction *NC;
3364 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00003365 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00003366 Args, Caller->getName(), Caller);
3367 } else {
3368 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3369 }
3370
3371 // Insert a cast of the return type as necessary...
3372 Value *NV = NC;
3373 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3374 if (NV->getType() != Type::VoidTy) {
3375 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00003376
3377 // If this is an invoke instruction, we should insert it after the first
3378 // non-phi, instruction in the normal successor block.
3379 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3380 BasicBlock::iterator I = II->getNormalDest()->begin();
3381 while (isa<PHINode>(I)) ++I;
3382 InsertNewInstBefore(NC, *I);
3383 } else {
3384 // Otherwise, it's a call, just insert cast right after the call instr
3385 InsertNewInstBefore(NC, *Caller);
3386 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003387 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00003388 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00003389 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00003390 }
3391 }
3392
3393 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3394 Caller->replaceAllUsesWith(NV);
3395 Caller->getParent()->getInstList().erase(Caller);
3396 removeFromWorkList(Caller);
3397 return true;
3398}
3399
3400
Chris Lattnera1be5662002-05-02 17:06:02 +00003401
Chris Lattner473945d2002-05-06 18:06:38 +00003402// PHINode simplification
3403//
Chris Lattner7e708292002-06-25 16:13:24 +00003404Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnerc30bda72004-10-17 21:22:38 +00003405 if (Value *V = hasConstantValue(&PN)) {
3406 // If V is an instruction, we have to be certain that it dominates PN.
3407 // However, because we don't have dom info, we can't do a perfect job.
3408 if (Instruction *I = dyn_cast<Instruction>(V)) {
3409 // We know that the instruction dominates the PHI if there are no undef
3410 // values coming in.
Chris Lattner77bcee72004-10-18 01:48:31 +00003411 if (I->getParent() != &I->getParent()->getParent()->front() ||
3412 isa<InvokeInst>(I))
Chris Lattnerca459302004-10-17 21:31:34 +00003413 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3414 if (isa<UndefValue>(PN.getIncomingValue(i))) {
3415 V = 0;
3416 break;
3417 }
Chris Lattnerc30bda72004-10-17 21:22:38 +00003418 }
3419
3420 if (V)
3421 return ReplaceInstUsesWith(PN, V);
3422 }
Chris Lattner7059f2e2004-02-16 05:07:08 +00003423
3424 // If the only user of this instruction is a cast instruction, and all of the
3425 // incoming values are constants, change this PHI to merge together the casted
3426 // constants.
3427 if (PN.hasOneUse())
3428 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3429 if (CI->getType() != PN.getType()) { // noop casts will be folded
3430 bool AllConstant = true;
3431 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3432 if (!isa<Constant>(PN.getIncomingValue(i))) {
3433 AllConstant = false;
3434 break;
3435 }
3436 if (AllConstant) {
3437 // Make a new PHI with all casted values.
3438 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3439 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3440 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3441 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3442 PN.getIncomingBlock(i));
3443 }
3444
3445 // Update the cast instruction.
3446 CI->setOperand(0, New);
3447 WorkList.push_back(CI); // revisit the cast instruction to fold.
3448 WorkList.push_back(New); // Make sure to revisit the new Phi
3449 return &PN; // PN is now dead!
3450 }
3451 }
Chris Lattner60921c92003-12-19 05:58:40 +00003452 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00003453}
3454
Chris Lattner28977af2004-04-05 01:30:19 +00003455static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3456 Instruction *InsertPoint,
3457 InstCombiner *IC) {
3458 unsigned PS = IC->getTargetData().getPointerSize();
3459 const Type *VTy = V->getType();
Chris Lattner28977af2004-04-05 01:30:19 +00003460 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3461 // We must insert a cast to ensure we sign-extend.
3462 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3463 V->getName()), *InsertPoint);
3464 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3465 *InsertPoint);
3466}
3467
Chris Lattnera1be5662002-05-02 17:06:02 +00003468
Chris Lattner7e708292002-06-25 16:13:24 +00003469Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00003470 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00003471 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00003472 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00003473 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00003474 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00003475
Chris Lattnere87597f2004-10-16 18:11:37 +00003476 if (isa<UndefValue>(GEP.getOperand(0)))
3477 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
3478
Chris Lattnerc6bd1952004-02-22 05:25:17 +00003479 bool HasZeroPointerIndex = false;
3480 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3481 HasZeroPointerIndex = C->isNullValue();
3482
3483 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00003484 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00003485
Chris Lattner28977af2004-04-05 01:30:19 +00003486 // Eliminate unneeded casts for indices.
3487 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00003488 gep_type_iterator GTI = gep_type_begin(GEP);
3489 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3490 if (isa<SequentialType>(*GTI)) {
3491 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3492 Value *Src = CI->getOperand(0);
3493 const Type *SrcTy = Src->getType();
3494 const Type *DestTy = CI->getType();
3495 if (Src->getType()->isInteger()) {
3496 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3497 // We can always eliminate a cast from ulong or long to the other.
3498 // We can always eliminate a cast from uint to int or the other on
3499 // 32-bit pointer platforms.
3500 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3501 MadeChange = true;
3502 GEP.setOperand(i, Src);
3503 }
3504 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3505 SrcTy->getPrimitiveSize() == 4) {
3506 // We can always eliminate a cast from int to [u]long. We can
3507 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3508 // pointer target.
3509 if (SrcTy->isSigned() ||
3510 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3511 MadeChange = true;
3512 GEP.setOperand(i, Src);
3513 }
Chris Lattner28977af2004-04-05 01:30:19 +00003514 }
3515 }
3516 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00003517 // If we are using a wider index than needed for this platform, shrink it
3518 // to what we need. If the incoming value needs a cast instruction,
3519 // insert it. This explicit cast can make subsequent optimizations more
3520 // obvious.
3521 Value *Op = GEP.getOperand(i);
3522 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00003523 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00003524 GEP.setOperand(i, ConstantExpr::getCast(C,
3525 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00003526 MadeChange = true;
3527 } else {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00003528 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3529 Op->getName()), GEP);
3530 GEP.setOperand(i, Op);
3531 MadeChange = true;
3532 }
Chris Lattner67769e52004-07-20 01:48:15 +00003533
3534 // If this is a constant idx, make sure to canonicalize it to be a signed
3535 // operand, otherwise CSE and other optimizations are pessimized.
3536 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3537 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3538 CUI->getType()->getSignedVersion()));
3539 MadeChange = true;
3540 }
Chris Lattner28977af2004-04-05 01:30:19 +00003541 }
3542 if (MadeChange) return &GEP;
3543
Chris Lattner90ac28c2002-08-02 19:29:35 +00003544 // Combine Indices - If the source pointer to this getelementptr instruction
3545 // is a getelementptr instruction, combine the indices of the two
3546 // getelementptr instructions into a single instruction.
3547 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00003548 std::vector<Value*> SrcGEPOperands;
Chris Lattner620ce142004-05-07 22:09:22 +00003549 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattnerebd985c2004-03-25 22:59:29 +00003550 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner620ce142004-05-07 22:09:22 +00003551 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattnerebd985c2004-03-25 22:59:29 +00003552 if (CE->getOpcode() == Instruction::GetElementPtr)
3553 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3554 }
3555
3556 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00003557 // Note that if our source is a gep chain itself that we wait for that
3558 // chain to be resolved before we perform this transformation. This
3559 // avoids us creating a TON of code in some cases.
3560 //
3561 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3562 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3563 return 0; // Wait until our source is folded to completion.
3564
Chris Lattner90ac28c2002-08-02 19:29:35 +00003565 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00003566
3567 // Find out whether the last index in the source GEP is a sequential idx.
3568 bool EndsWithSequential = false;
3569 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3570 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00003571 EndsWithSequential = !isa<StructType>(*I);
Chris Lattner8a2a3112001-12-14 16:52:21 +00003572
Chris Lattner90ac28c2002-08-02 19:29:35 +00003573 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00003574 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00003575 // Replace: gep (gep %P, long B), long A, ...
3576 // With: T = long A+B; gep %P, T, ...
3577 //
Chris Lattner620ce142004-05-07 22:09:22 +00003578 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00003579 if (SO1 == Constant::getNullValue(SO1->getType())) {
3580 Sum = GO1;
3581 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3582 Sum = SO1;
3583 } else {
3584 // If they aren't the same type, convert both to an integer of the
3585 // target's pointer size.
3586 if (SO1->getType() != GO1->getType()) {
3587 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3588 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3589 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3590 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3591 } else {
3592 unsigned PS = TD->getPointerSize();
Chris Lattner28977af2004-04-05 01:30:19 +00003593 if (SO1->getType()->getPrimitiveSize() == PS) {
3594 // Convert GO1 to SO1's type.
3595 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3596
3597 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3598 // Convert SO1 to GO1's type.
3599 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3600 } else {
3601 const Type *PT = TD->getIntPtrType();
3602 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3603 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3604 }
3605 }
3606 }
Chris Lattner620ce142004-05-07 22:09:22 +00003607 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3608 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3609 else {
Chris Lattner48595f12004-06-10 02:07:29 +00003610 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3611 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00003612 }
Chris Lattner28977af2004-04-05 01:30:19 +00003613 }
Chris Lattner620ce142004-05-07 22:09:22 +00003614
3615 // Recycle the GEP we already have if possible.
3616 if (SrcGEPOperands.size() == 2) {
3617 GEP.setOperand(0, SrcGEPOperands[0]);
3618 GEP.setOperand(1, Sum);
3619 return &GEP;
3620 } else {
3621 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3622 SrcGEPOperands.end()-1);
3623 Indices.push_back(Sum);
3624 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3625 }
Chris Lattner28977af2004-04-05 01:30:19 +00003626 } else if (isa<Constant>(*GEP.idx_begin()) &&
3627 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerebd985c2004-03-25 22:59:29 +00003628 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00003629 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00003630 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3631 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00003632 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3633 }
3634
3635 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00003636 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00003637
Chris Lattner620ce142004-05-07 22:09:22 +00003638 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00003639 // GEP of global variable. If all of the indices for this GEP are
3640 // constants, we can promote this to a constexpr instead of an instruction.
3641
3642 // Scan for nonconstants...
3643 std::vector<Constant*> Indices;
3644 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3645 for (; I != E && isa<Constant>(*I); ++I)
3646 Indices.push_back(cast<Constant>(*I));
3647
3648 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00003649 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00003650
3651 // Replace all uses of the GEP with the new constexpr...
3652 return ReplaceInstUsesWith(GEP, CE);
3653 }
Chris Lattner620ce142004-05-07 22:09:22 +00003654 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattnerc6bd1952004-02-22 05:25:17 +00003655 if (CE->getOpcode() == Instruction::Cast) {
3656 if (HasZeroPointerIndex) {
3657 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3658 // into : GEP [10 x ubyte]* X, long 0, ...
3659 //
3660 // This occurs when the program declares an array extern like "int X[];"
3661 //
3662 Constant *X = CE->getOperand(0);
3663 const PointerType *CPTy = cast<PointerType>(CE->getType());
3664 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3665 if (const ArrayType *XATy =
3666 dyn_cast<ArrayType>(XTy->getElementType()))
3667 if (const ArrayType *CATy =
3668 dyn_cast<ArrayType>(CPTy->getElementType()))
3669 if (CATy->getElementType() == XATy->getElementType()) {
3670 // At this point, we know that the cast source type is a pointer
3671 // to an array of the same type as the destination pointer
3672 // array. Because the array type is never stepped over (there
3673 // is a leading zero) we can fold the cast into this GEP.
3674 GEP.setOperand(0, X);
3675 return &GEP;
3676 }
3677 }
3678 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00003679 }
3680
Chris Lattner8a2a3112001-12-14 16:52:21 +00003681 return 0;
3682}
3683
Chris Lattner0864acf2002-11-04 16:18:53 +00003684Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3685 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3686 if (AI.isArrayAllocation()) // Check C != 1
3687 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3688 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00003689 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00003690
3691 // Create and insert the replacement instruction...
3692 if (isa<MallocInst>(AI))
Chris Lattner7c881df2004-03-19 06:08:10 +00003693 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00003694 else {
3695 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner7c881df2004-03-19 06:08:10 +00003696 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00003697 }
Chris Lattner7c881df2004-03-19 06:08:10 +00003698
3699 InsertNewInstBefore(New, AI);
Chris Lattner0864acf2002-11-04 16:18:53 +00003700
3701 // Scan to the end of the allocation instructions, to skip over a block of
3702 // allocas if possible...
3703 //
3704 BasicBlock::iterator It = New;
3705 while (isa<AllocationInst>(*It)) ++It;
3706
3707 // Now that I is pointing to the first non-allocation-inst in the block,
3708 // insert our getelementptr instruction...
3709 //
Chris Lattner28977af2004-04-05 01:30:19 +00003710 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner0864acf2002-11-04 16:18:53 +00003711 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3712
3713 // Now make everything use the getelementptr instead of the original
3714 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00003715 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00003716 } else if (isa<UndefValue>(AI.getArraySize())) {
3717 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00003718 }
Chris Lattner7c881df2004-03-19 06:08:10 +00003719
3720 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3721 // Note that we only do this for alloca's, because malloc should allocate and
3722 // return a unique pointer, even for a zero byte allocation.
Chris Lattnercf27afb2004-07-02 22:55:47 +00003723 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3724 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00003725 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3726
Chris Lattner0864acf2002-11-04 16:18:53 +00003727 return 0;
3728}
3729
Chris Lattner67b1e1b2003-12-07 01:24:23 +00003730Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3731 Value *Op = FI.getOperand(0);
3732
3733 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3734 if (CastInst *CI = dyn_cast<CastInst>(Op))
3735 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3736 FI.setOperand(0, CI->getOperand(0));
3737 return &FI;
3738 }
3739
Chris Lattner17be6352004-10-18 02:59:09 +00003740 // free undef -> unreachable.
3741 if (isa<UndefValue>(Op)) {
3742 // Insert a new store to null because we cannot modify the CFG here.
3743 new StoreInst(ConstantBool::True,
3744 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
3745 return EraseInstFromFunction(FI);
3746 }
3747
Chris Lattner6160e852004-02-28 04:57:37 +00003748 // If we have 'free null' delete the instruction. This can happen in stl code
3749 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00003750 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003751 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00003752
Chris Lattner67b1e1b2003-12-07 01:24:23 +00003753 return 0;
3754}
3755
3756
Chris Lattner833b8a42003-06-26 05:06:25 +00003757/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3758/// constantexpr, return the constant value being addressed by the constant
3759/// expression, or null if something is funny.
3760///
3761static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner28977af2004-04-05 01:30:19 +00003762 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner833b8a42003-06-26 05:06:25 +00003763 return 0; // Do not allow stepping over the value!
3764
3765 // Loop over all of the operands, tracking down which value we are
3766 // addressing...
Chris Lattnere1368ae2004-05-27 17:30:27 +00003767 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3768 for (++I; I != E; ++I)
3769 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3770 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3771 assert(CU->getValue() < STy->getNumElements() &&
3772 "Struct index out of range!");
3773 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +00003774 C = CS->getOperand(CU->getValue());
Chris Lattnere1368ae2004-05-27 17:30:27 +00003775 } else if (isa<ConstantAggregateZero>(C)) {
3776 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003777 } else if (isa<UndefValue>(C)) {
3778 C = UndefValue::get(STy->getElementType(CU->getValue()));
Chris Lattnere1368ae2004-05-27 17:30:27 +00003779 } else {
3780 return 0;
3781 }
3782 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3783 const ArrayType *ATy = cast<ArrayType>(*I);
3784 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3785 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +00003786 C = CA->getOperand(CI->getRawValue());
Chris Lattnere1368ae2004-05-27 17:30:27 +00003787 else if (isa<ConstantAggregateZero>(C))
3788 C = Constant::getNullValue(ATy->getElementType());
Chris Lattnere87597f2004-10-16 18:11:37 +00003789 else if (isa<UndefValue>(C))
3790 C = UndefValue::get(ATy->getElementType());
Chris Lattnere1368ae2004-05-27 17:30:27 +00003791 else
3792 return 0;
3793 } else {
Chris Lattner833b8a42003-06-26 05:06:25 +00003794 return 0;
Chris Lattnere1368ae2004-05-27 17:30:27 +00003795 }
Chris Lattner833b8a42003-06-26 05:06:25 +00003796 return C;
3797}
3798
Chris Lattnerb89e0712004-07-13 01:49:43 +00003799static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3800 User *CI = cast<User>(LI.getOperand(0));
3801
3802 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3803 if (const PointerType *SrcTy =
3804 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3805 const Type *SrcPTy = SrcTy->getElementType();
3806 if (SrcPTy->isSized() && DestPTy->isSized() &&
3807 IC.getTargetData().getTypeSize(SrcPTy) ==
3808 IC.getTargetData().getTypeSize(DestPTy) &&
3809 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3810 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3811 // Okay, we are casting from one integer or pointer type to another of
3812 // the same size. Instead of casting the pointer before the load, cast
3813 // the result of the loaded value.
3814 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerc10aced2004-09-19 18:43:46 +00003815 CI->getName(),
3816 LI.isVolatile()),LI);
Chris Lattnerb89e0712004-07-13 01:49:43 +00003817 // Now cast the result of the load.
3818 return new CastInst(NewLoad, LI.getType());
3819 }
3820 }
3821 return 0;
3822}
3823
Chris Lattnerc10aced2004-09-19 18:43:46 +00003824/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00003825/// from this value cannot trap. If it is not obviously safe to load from the
3826/// specified pointer, we do a quick local scan of the basic block containing
3827/// ScanFrom, to determine if the address is already accessed.
3828static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3829 // If it is an alloca or global variable, it is always safe to load from.
3830 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3831
3832 // Otherwise, be a little bit agressive by scanning the local block where we
3833 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00003834 // from/to. If so, the previous load or store would have already trapped,
3835 // so there is no harm doing an extra load (also, CSE will later eliminate
3836 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00003837 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3838
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00003839 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00003840 --BBI;
3841
3842 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3843 if (LI->getOperand(0) == V) return true;
3844 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3845 if (SI->getOperand(1) == V) return true;
3846
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00003847 }
Chris Lattner8a375202004-09-19 19:18:10 +00003848 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00003849}
3850
Chris Lattner833b8a42003-06-26 05:06:25 +00003851Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3852 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00003853
Chris Lattnere87597f2004-10-16 18:11:37 +00003854 if (Constant *C = dyn_cast<Constant>(Op)) {
3855 if ((C->isNullValue() || isa<UndefValue>(C)) &&
Chris Lattner17be6352004-10-18 02:59:09 +00003856 !LI.isVolatile()) { // load null/undef -> undef
3857 // Insert a new store to null instruction before the load to indicate that
3858 // this code is not reachable. We do this instead of inserting an
3859 // unreachable instruction directly because we cannot modify the CFG.
3860 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00003861 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00003862 }
Chris Lattner833b8a42003-06-26 05:06:25 +00003863
Chris Lattnere87597f2004-10-16 18:11:37 +00003864 // Instcombine load (constant global) into the value loaded.
3865 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
3866 if (GV->isConstant() && !GV->isExternal())
3867 return ReplaceInstUsesWith(LI, GV->getInitializer());
3868
3869 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
3870 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
3871 if (CE->getOpcode() == Instruction::GetElementPtr) {
3872 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3873 if (GV->isConstant() && !GV->isExternal())
3874 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3875 return ReplaceInstUsesWith(LI, V);
3876 } else if (CE->getOpcode() == Instruction::Cast) {
3877 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3878 return Res;
3879 }
3880 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00003881
3882 // load (cast X) --> cast (load X) iff safe
Chris Lattnerb89e0712004-07-13 01:49:43 +00003883 if (CastInst *CI = dyn_cast<CastInst>(Op))
3884 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3885 return Res;
Chris Lattnerf499eac2004-04-08 20:39:49 +00003886
Chris Lattnerc10aced2004-09-19 18:43:46 +00003887 if (!LI.isVolatile() && Op->hasOneUse()) {
3888 // Change select and PHI nodes to select values instead of addresses: this
3889 // helps alias analysis out a lot, allows many others simplifications, and
3890 // exposes redundancy in the code.
3891 //
3892 // Note that we cannot do the transformation unless we know that the
3893 // introduced loads cannot trap! Something like this is valid as long as
3894 // the condition is always false: load (select bool %C, int* null, int* %G),
3895 // but it would not be valid if we transformed it to load from null
3896 // unconditionally.
3897 //
3898 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3899 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00003900 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3901 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00003902 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003903 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00003904 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003905 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00003906 return new SelectInst(SI->getCondition(), V1, V2);
3907 }
3908
Chris Lattner684fe212004-09-23 15:46:00 +00003909 // load (select (cond, null, P)) -> load P
3910 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3911 if (C->isNullValue()) {
3912 LI.setOperand(0, SI->getOperand(2));
3913 return &LI;
3914 }
3915
3916 // load (select (cond, P, null)) -> load P
3917 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3918 if (C->isNullValue()) {
3919 LI.setOperand(0, SI->getOperand(1));
3920 return &LI;
3921 }
3922
Chris Lattnerc10aced2004-09-19 18:43:46 +00003923 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3924 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003925 bool Safe = PN->getParent() == LI.getParent();
3926
3927 // Scan all of the instructions between the PHI and the load to make
3928 // sure there are no instructions that might possibly alter the value
3929 // loaded from the PHI.
3930 if (Safe) {
3931 BasicBlock::iterator I = &LI;
3932 for (--I; !isa<PHINode>(I); --I)
3933 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3934 Safe = false;
3935 break;
3936 }
3937 }
3938
3939 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattner8a375202004-09-19 19:18:10 +00003940 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003941 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerc10aced2004-09-19 18:43:46 +00003942 Safe = false;
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003943
Chris Lattnerc10aced2004-09-19 18:43:46 +00003944 if (Safe) {
3945 // Create the PHI.
3946 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3947 InsertNewInstBefore(NewPN, *PN);
3948 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3949
3950 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3951 BasicBlock *BB = PN->getIncomingBlock(i);
3952 Value *&TheLoad = LoadMap[BB];
3953 if (TheLoad == 0) {
3954 Value *InVal = PN->getIncomingValue(i);
3955 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3956 InVal->getName()+".val"),
3957 *BB->getTerminator());
3958 }
3959 NewPN->addIncoming(TheLoad, BB);
3960 }
3961 return ReplaceInstUsesWith(LI, NewPN);
3962 }
3963 }
3964 }
Chris Lattner833b8a42003-06-26 05:06:25 +00003965 return 0;
3966}
3967
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00003968Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3969 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003970 Value *X;
3971 BasicBlock *TrueDest;
3972 BasicBlock *FalseDest;
3973 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3974 !isa<Constant>(X)) {
3975 // Swap Destinations and condition...
3976 BI.setCondition(X);
3977 BI.setSuccessor(0, FalseDest);
3978 BI.setSuccessor(1, TrueDest);
3979 return &BI;
3980 }
3981
3982 // Cannonicalize setne -> seteq
3983 Instruction::BinaryOps Op; Value *Y;
3984 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3985 TrueDest, FalseDest)))
3986 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3987 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3988 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3989 std::string Name = I->getName(); I->setName("");
3990 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3991 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00003992 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003993 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00003994 BI.setSuccessor(0, FalseDest);
3995 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003996 removeFromWorkList(I);
3997 I->getParent()->getInstList().erase(I);
3998 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00003999 return &BI;
4000 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004001
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00004002 return 0;
4003}
Chris Lattner0864acf2002-11-04 16:18:53 +00004004
Chris Lattner46238a62004-07-03 00:26:11 +00004005Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4006 Value *Cond = SI.getCondition();
4007 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4008 if (I->getOpcode() == Instruction::Add)
4009 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4010 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4011 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00004012 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00004013 AddRHS));
4014 SI.setOperand(0, I->getOperand(0));
4015 WorkList.push_back(I);
4016 return &SI;
4017 }
4018 }
4019 return 0;
4020}
4021
Chris Lattner8a2a3112001-12-14 16:52:21 +00004022
Chris Lattner62b14df2002-09-02 04:59:56 +00004023void InstCombiner::removeFromWorkList(Instruction *I) {
4024 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4025 WorkList.end());
4026}
4027
Chris Lattner7e708292002-06-25 16:13:24 +00004028bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004029 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00004030 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00004031
Chris Lattner216d4d82004-05-01 23:19:52 +00004032 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
4033 WorkList.push_back(&*i);
Chris Lattner6ffe5512004-04-27 15:13:33 +00004034
Chris Lattner8a2a3112001-12-14 16:52:21 +00004035
4036 while (!WorkList.empty()) {
4037 Instruction *I = WorkList.back(); // Get an instruction from the worklist
4038 WorkList.pop_back();
4039
Misha Brukmana3bbcb52002-10-29 23:06:16 +00004040 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner62b14df2002-09-02 04:59:56 +00004041 // Check to see if we can DIE the instruction...
4042 if (isInstructionTriviallyDead(I)) {
4043 // Add operands to the worklist...
Chris Lattner4bb7c022003-10-06 17:11:01 +00004044 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004045 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00004046 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00004047
4048 I->getParent()->getInstList().erase(I);
4049 removeFromWorkList(I);
4050 continue;
4051 }
Chris Lattner62b14df2002-09-02 04:59:56 +00004052
Misha Brukmana3bbcb52002-10-29 23:06:16 +00004053 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner62b14df2002-09-02 04:59:56 +00004054 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner061718c2004-10-16 19:44:59 +00004055 if (isa<GetElementPtrInst>(I) &&
4056 cast<Constant>(I->getOperand(0))->isNullValue() &&
4057 !isa<ConstantPointerNull>(C)) {
4058 // If this is a constant expr gep that is effectively computing an
4059 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
4060 bool isFoldableGEP = true;
4061 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
4062 if (!isa<ConstantInt>(I->getOperand(i)))
4063 isFoldableGEP = false;
4064 if (isFoldableGEP) {
4065 uint64_t Offset = TD->getIndexedOffset(I->getOperand(0)->getType(),
4066 std::vector<Value*>(I->op_begin()+1, I->op_end()));
4067 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner6e758ae2004-10-16 19:46:33 +00004068 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner061718c2004-10-16 19:44:59 +00004069 C = ConstantExpr::getCast(C, I->getType());
4070 }
4071 }
4072
Chris Lattner62b14df2002-09-02 04:59:56 +00004073 // Add operands to the worklist...
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004074 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00004075 ReplaceInstUsesWith(*I, C);
4076
Chris Lattner62b14df2002-09-02 04:59:56 +00004077 ++NumConstProp;
Chris Lattner4bb7c022003-10-06 17:11:01 +00004078 I->getParent()->getInstList().erase(I);
Chris Lattner60610002003-10-07 15:17:02 +00004079 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00004080 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00004081 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00004082
Chris Lattner8a2a3112001-12-14 16:52:21 +00004083 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00004084 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00004085 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004086 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00004087 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00004088 DEBUG(std::cerr << "IC: Old = " << *I
4089 << " New = " << *Result);
4090
Chris Lattnerf523d062004-06-09 05:08:07 +00004091 // Everything uses the new instruction now.
4092 I->replaceAllUsesWith(Result);
4093
4094 // Push the new instruction and any users onto the worklist.
4095 WorkList.push_back(Result);
4096 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00004097
4098 // Move the name to the new instruction first...
4099 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00004100 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00004101
4102 // Insert the new instruction into the basic block...
4103 BasicBlock *InstParent = I->getParent();
4104 InstParent->getInstList().insert(I, Result);
4105
Chris Lattner00d51312004-05-01 23:27:23 +00004106 // Make sure that we reprocess all operands now that we reduced their
4107 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00004108 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4109 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4110 WorkList.push_back(OpI);
4111
Chris Lattnerf523d062004-06-09 05:08:07 +00004112 // Instructions can end up on the worklist more than once. Make sure
4113 // we do not process an instruction that has been deleted.
4114 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00004115
4116 // Erase the old instruction.
4117 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004118 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00004119 DEBUG(std::cerr << "IC: MOD = " << *I);
4120
Chris Lattner90ac28c2002-08-02 19:29:35 +00004121 // If the instruction was modified, it's possible that it is now dead.
4122 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00004123 if (isInstructionTriviallyDead(I)) {
4124 // Make sure we process all operands now that we are reducing their
4125 // use counts.
4126 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4127 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4128 WorkList.push_back(OpI);
4129
4130 // Instructions may end up in the worklist more than once. Erase all
4131 // occurrances of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00004132 removeFromWorkList(I);
Chris Lattner00d51312004-05-01 23:27:23 +00004133 I->getParent()->getInstList().erase(I);
Chris Lattnerf523d062004-06-09 05:08:07 +00004134 } else {
4135 WorkList.push_back(Result);
4136 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00004137 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00004138 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004139 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00004140 }
4141 }
4142
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004143 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00004144}
4145
Brian Gaeke96d4bf72004-07-27 17:43:21 +00004146FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004147 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00004148}
Brian Gaeked0fde302003-11-11 22:41:34 +00004149