blob: 767fc9582b0777068e39ab31af526d23b5715236 [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 Lattnerc54e2b82003-05-22 19:07:21 +000038#include "llvm/Instructions.h"
Chris Lattner7bcc0e72004-02-28 05:22:00 +000039#include "llvm/Intrinsics.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner2a9c8472003-05-27 16:40:51 +000041#include "llvm/Constants.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000042#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000043#include "llvm/GlobalVariable.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
48#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner221d6882002-02-12 21:07:25 +000049#include "llvm/Support/InstIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000052#include "llvm/Support/Debug.h"
53#include "llvm/ADT/Statistic.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000057
Chris Lattnerdd841ae2002-04-18 17:39:14 +000058namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000059 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
62
Chris Lattnerf57b8452002-04-27 06:56:12 +000063 class InstCombiner : public FunctionPass,
Chris Lattnerdd841ae2002-04-18 17:39:14 +000064 public InstVisitor<InstCombiner, Instruction*> {
65 // Worklist of all of the instructions that need to be simplified.
66 std::vector<Instruction*> WorkList;
Chris Lattnerbc61e662003-11-02 05:57:39 +000067 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000068
Chris Lattner7bcc0e72004-02-28 05:22:00 +000069 /// AddUsersToWorkList - When an instruction is simplified, add all users of
70 /// the instruction to the work lists because they might get more simplified
71 /// now.
72 ///
73 void AddUsersToWorkList(Instruction &I) {
Chris Lattner7e708292002-06-25 16:13:24 +000074 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000075 UI != UE; ++UI)
76 WorkList.push_back(cast<Instruction>(*UI));
77 }
78
Chris Lattner7bcc0e72004-02-28 05:22:00 +000079 /// AddUsesToWorkList - When an instruction is simplified, add operands to
80 /// the work lists because they might get more simplified now.
81 ///
82 void AddUsesToWorkList(Instruction &I) {
83 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
84 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
85 WorkList.push_back(Op);
86 }
87
Chris Lattner62b14df2002-09-02 04:59:56 +000088 // removeFromWorkList - remove all instances of I from the worklist.
89 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000090 public:
Chris Lattner7e708292002-06-25 16:13:24 +000091 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000092
Chris Lattner97e52e42002-04-28 21:27:06 +000093 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +000094 AU.addRequired<TargetData>();
Chris Lattnercb2610e2002-10-21 20:00:28 +000095 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +000096 }
97
Chris Lattner28977af2004-04-05 01:30:19 +000098 TargetData &getTargetData() const { return *TD; }
99
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000100 // Visitation implementation - Implement instruction combining for different
101 // instruction types. The semantics are as follows:
102 // Return Value:
103 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000104 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000105 // otherwise - Change was made, replace I with returned instruction
106 //
Chris Lattner7e708292002-06-25 16:13:24 +0000107 Instruction *visitAdd(BinaryOperator &I);
108 Instruction *visitSub(BinaryOperator &I);
109 Instruction *visitMul(BinaryOperator &I);
110 Instruction *visitDiv(BinaryOperator &I);
111 Instruction *visitRem(BinaryOperator &I);
112 Instruction *visitAnd(BinaryOperator &I);
113 Instruction *visitOr (BinaryOperator &I);
114 Instruction *visitXor(BinaryOperator &I);
115 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnerea340052003-03-10 19:16:08 +0000116 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000117 Instruction *visitCastInst(CastInst &CI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000118 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000119 Instruction *visitCallInst(CallInst &CI);
120 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000121 Instruction *visitPHINode(PHINode &PN);
122 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000123 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000124 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000125 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000126 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000127 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000128
129 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000130 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000131
Chris Lattner9fe38862003-06-19 17:00:31 +0000132 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000133 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000134 bool transformConstExprCastCall(CallSite CS);
135
Chris Lattner28977af2004-04-05 01:30:19 +0000136 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000137 // InsertNewInstBefore - insert an instruction New before instruction Old
138 // in the program. Add the new instruction to the worklist.
139 //
Chris Lattner955f3312004-09-28 21:48:02 +0000140 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000141 assert(New && New->getParent() == 0 &&
142 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000143 BasicBlock *BB = Old.getParent();
144 BB->getInstList().insert(&Old, New); // Insert inst
145 WorkList.push_back(New); // Add to worklist
Chris Lattner4cb170c2004-02-23 06:38:22 +0000146 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000147 }
148
Chris Lattner0c967662004-09-24 15:21:34 +0000149 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
150 /// This also adds the cast to the worklist. Finally, this returns the
151 /// cast.
152 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
153 if (V->getType() == Ty) return V;
154
155 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
156 WorkList.push_back(C);
157 return C;
158 }
159
Chris Lattner8b170942002-08-09 23:47:40 +0000160 // ReplaceInstUsesWith - This method is to be used when an instruction is
161 // found to be dead, replacable with another preexisting expression. Here
162 // we add all uses of I to the worklist, replace all uses of I with the new
163 // value, then return I, so that the inst combiner will know that I was
164 // modified.
165 //
166 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000167 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000168 if (&I != V) {
169 I.replaceAllUsesWith(V);
170 return &I;
171 } else {
172 // If we are replacing the instruction with itself, this must be in a
173 // segment of unreachable code, so just clobber the instruction.
174 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
175 return &I;
176 }
Chris Lattner8b170942002-08-09 23:47:40 +0000177 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000178
179 // EraseInstFromFunction - When dealing with an instruction that has side
180 // effects or produces a void value, we can't rely on DCE to delete the
181 // instruction. Instead, visit methods should return the value returned by
182 // this function.
183 Instruction *EraseInstFromFunction(Instruction &I) {
184 assert(I.use_empty() && "Cannot erase instruction that is used!");
185 AddUsesToWorkList(I);
186 removeFromWorkList(&I);
187 I.getParent()->getInstList().erase(&I);
188 return 0; // Don't do anything with FI
189 }
190
191
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000192 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000193 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
194 /// InsertBefore instruction. This is specialized a bit to avoid inserting
195 /// casts that are known to not do anything...
196 ///
197 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
198 Instruction *InsertBefore);
199
Chris Lattnerc8802d22003-03-11 00:12:48 +0000200 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner4e998b22004-09-29 05:07:12 +0000201 // operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000202 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000203
Chris Lattner4e998b22004-09-29 05:07:12 +0000204
205 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
206 // PHI node as operand #0, see if we can fold the instruction into the PHI
207 // (which is only possible if all operands to the PHI are constants).
208 Instruction *FoldOpIntoPhi(Instruction &I);
209
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000210 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
211 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnera96879a2004-09-29 17:40:11 +0000212
213 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
214 bool Inside, Instruction &IB);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000215 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000216
Chris Lattnera6275cc2002-07-26 21:12:46 +0000217 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000218}
219
Chris Lattner4f98c562003-03-10 21:43:22 +0000220// getComplexity: Assign a complexity or rank value to LLVM Values...
221// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
222static unsigned getComplexity(Value *V) {
223 if (isa<Instruction>(V)) {
224 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
225 return 2;
226 return 3;
227 }
228 if (isa<Argument>(V)) return 2;
229 return isa<Constant>(V) ? 0 : 1;
230}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000231
Chris Lattnerc8802d22003-03-11 00:12:48 +0000232// isOnlyUse - Return true if this instruction will be deleted if we stop using
233// it.
234static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000235 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000236}
237
Chris Lattner4cb170c2004-02-23 06:38:22 +0000238// getPromotedType - Return the specified type promoted as it would be to pass
239// though a va_arg area...
240static const Type *getPromotedType(const Type *Ty) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000241 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-02-23 06:38:22 +0000242 case Type::SByteTyID:
243 case Type::ShortTyID: return Type::IntTy;
244 case Type::UByteTyID:
245 case Type::UShortTyID: return Type::UIntTy;
246 case Type::FloatTyID: return Type::DoubleTy;
247 default: return Ty;
248 }
249}
250
Chris Lattner4f98c562003-03-10 21:43:22 +0000251// SimplifyCommutative - This performs a few simplifications for commutative
252// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000253//
Chris Lattner4f98c562003-03-10 21:43:22 +0000254// 1. Order operands such that they are listed from right (least complex) to
255// left (most complex). This puts constants before unary operators before
256// binary operators.
257//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000258// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
259// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000260//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000261bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000262 bool Changed = false;
263 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
264 Changed = !I.swapOperands();
265
266 if (!I.isAssociative()) return Changed;
267 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000268 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
269 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
270 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000271 Constant *Folded = ConstantExpr::get(I.getOpcode(),
272 cast<Constant>(I.getOperand(1)),
273 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000274 I.setOperand(0, Op->getOperand(0));
275 I.setOperand(1, Folded);
276 return true;
277 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
278 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
279 isOnlyUse(Op) && isOnlyUse(Op1)) {
280 Constant *C1 = cast<Constant>(Op->getOperand(1));
281 Constant *C2 = cast<Constant>(Op1->getOperand(1));
282
283 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000284 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000285 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
286 Op1->getOperand(0),
287 Op1->getName(), &I);
288 WorkList.push_back(New);
289 I.setOperand(0, New);
290 I.setOperand(1, Folded);
291 return true;
292 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000293 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000294 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000295}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000296
Chris Lattner8d969642003-03-10 23:06:50 +0000297// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
298// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000299//
Chris Lattner8d969642003-03-10 23:06:50 +0000300static inline Value *dyn_castNegVal(Value *V) {
301 if (BinaryOperator::isNeg(V))
302 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
303
Chris Lattnerfe32e0c2003-04-30 22:19:10 +0000304 // Constants can be considered to be negated values if they can be folded...
305 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000306 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000307 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000308}
309
Chris Lattner8d969642003-03-10 23:06:50 +0000310static inline Value *dyn_castNotVal(Value *V) {
311 if (BinaryOperator::isNot(V))
312 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
313
314 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000315 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000316 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000317 return 0;
318}
319
Chris Lattnerc8802d22003-03-11 00:12:48 +0000320// dyn_castFoldableMul - If this value is a multiply that can be folded into
321// other computations (because it has a constant operand), return the
322// non-constant operand of the multiply.
323//
324static inline Value *dyn_castFoldableMul(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000325 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattnerc8802d22003-03-11 00:12:48 +0000326 if (Instruction *I = dyn_cast<Instruction>(V))
327 if (I->getOpcode() == Instruction::Mul)
328 if (isa<Constant>(I->getOperand(1)))
329 return I->getOperand(0);
330 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000331}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000332
Chris Lattnera2881962003-02-18 19:28:33 +0000333// Log2 - Calculate the log base 2 for the specified value if it is exactly a
334// power of 2.
335static unsigned Log2(uint64_t Val) {
336 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
337 unsigned Count = 0;
338 while (Val != 1) {
339 if (Val & 1) return 0; // Multiple bits set?
340 Val >>= 1;
341 ++Count;
342 }
343 return Count;
Chris Lattneraf2930e2002-08-14 17:51:49 +0000344}
345
Chris Lattner955f3312004-09-28 21:48:02 +0000346// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000347static ConstantInt *AddOne(ConstantInt *C) {
348 return cast<ConstantInt>(ConstantExpr::getAdd(C,
349 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000350}
Chris Lattnera96879a2004-09-29 17:40:11 +0000351static ConstantInt *SubOne(ConstantInt *C) {
352 return cast<ConstantInt>(ConstantExpr::getSub(C,
353 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000354}
355
356// isTrueWhenEqual - Return true if the specified setcondinst instruction is
357// true when both operands are equal...
358//
359static bool isTrueWhenEqual(Instruction &I) {
360 return I.getOpcode() == Instruction::SetEQ ||
361 I.getOpcode() == Instruction::SetGE ||
362 I.getOpcode() == Instruction::SetLE;
363}
Chris Lattner564a7272003-08-13 19:01:45 +0000364
365/// AssociativeOpt - Perform an optimization on an associative operator. This
366/// function is designed to check a chain of associative operators for a
367/// potential to apply a certain optimization. Since the optimization may be
368/// applicable if the expression was reassociated, this checks the chain, then
369/// reassociates the expression as necessary to expose the optimization
370/// opportunity. This makes use of a special Functor, which must define
371/// 'shouldApply' and 'apply' methods.
372///
373template<typename Functor>
374Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
375 unsigned Opcode = Root.getOpcode();
376 Value *LHS = Root.getOperand(0);
377
378 // Quick check, see if the immediate LHS matches...
379 if (F.shouldApply(LHS))
380 return F.apply(Root);
381
382 // Otherwise, if the LHS is not of the same opcode as the root, return.
383 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +0000384 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000385 // Should we apply this transform to the RHS?
386 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
387
388 // If not to the RHS, check to see if we should apply to the LHS...
389 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
390 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
391 ShouldApply = true;
392 }
393
394 // If the functor wants to apply the optimization to the RHS of LHSI,
395 // reassociate the expression from ((? op A) op B) to (? op (A op B))
396 if (ShouldApply) {
397 BasicBlock *BB = Root.getParent();
Chris Lattner564a7272003-08-13 19:01:45 +0000398
399 // Now all of the instructions are in the current basic block, go ahead
400 // and perform the reassociation.
401 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
402
403 // First move the selected RHS to the LHS of the root...
404 Root.setOperand(0, LHSI->getOperand(1));
405
406 // Make what used to be the LHS of the root be the user of the root...
407 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +0000408 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +0000409 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
410 return 0;
411 }
Chris Lattner65725312004-04-16 18:08:07 +0000412 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +0000413 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +0000414 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
415 BasicBlock::iterator ARI = &Root; ++ARI;
416 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
417 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +0000418
419 // Now propagate the ExtraOperand down the chain of instructions until we
420 // get to LHSI.
421 while (TmpLHSI != LHSI) {
422 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +0000423 // Move the instruction to immediately before the chain we are
424 // constructing to avoid breaking dominance properties.
425 NextLHSI->getParent()->getInstList().remove(NextLHSI);
426 BB->getInstList().insert(ARI, NextLHSI);
427 ARI = NextLHSI;
428
Chris Lattner564a7272003-08-13 19:01:45 +0000429 Value *NextOp = NextLHSI->getOperand(1);
430 NextLHSI->setOperand(1, ExtraOperand);
431 TmpLHSI = NextLHSI;
432 ExtraOperand = NextOp;
433 }
434
435 // Now that the instructions are reassociated, have the functor perform
436 // the transformation...
437 return F.apply(Root);
438 }
439
440 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
441 }
442 return 0;
443}
444
445
446// AddRHS - Implements: X + X --> X << 1
447struct AddRHS {
448 Value *RHS;
449 AddRHS(Value *rhs) : RHS(rhs) {}
450 bool shouldApply(Value *LHS) const { return LHS == RHS; }
451 Instruction *apply(BinaryOperator &Add) const {
452 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
453 ConstantInt::get(Type::UByteTy, 1));
454 }
455};
456
457// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
458// iff C1&C2 == 0
459struct AddMaskingAnd {
460 Constant *C2;
461 AddMaskingAnd(Constant *c) : C2(c) {}
462 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000463 ConstantInt *C1;
464 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
465 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +0000466 }
467 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +0000468 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +0000469 }
470};
471
Chris Lattner2eefe512004-04-09 19:05:30 +0000472static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
473 InstCombiner *IC) {
474 // Figure out if the constant is the left or the right argument.
475 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
476 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000477
Chris Lattner2eefe512004-04-09 19:05:30 +0000478 if (Constant *SOC = dyn_cast<Constant>(SO)) {
479 if (ConstIsRHS)
480 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
481 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
482 }
483
484 Value *Op0 = SO, *Op1 = ConstOperand;
485 if (!ConstIsRHS)
486 std::swap(Op0, Op1);
487 Instruction *New;
488 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
489 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
490 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
491 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattner326c0f32004-04-10 19:15:56 +0000492 else {
Chris Lattner2eefe512004-04-09 19:05:30 +0000493 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +0000494 abort();
495 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000496 return IC->InsertNewInstBefore(New, BI);
497}
498
Chris Lattner4e998b22004-09-29 05:07:12 +0000499
500/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
501/// node as operand #0, see if we can fold the instruction into the PHI (which
502/// is only possible if all operands to the PHI are constants).
503Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
504 PHINode *PN = cast<PHINode>(I.getOperand(0));
505 if (!PN->hasOneUse()) return 0;
506
507 // Check to see if all of the operands of the PHI are constants. If not, we
508 // cannot do the transformation.
509 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
510 if (!isa<Constant>(PN->getIncomingValue(i)))
511 return 0;
512
513 // Okay, we can do the transformation: create the new PHI node.
514 PHINode *NewPN = new PHINode(I.getType(), I.getName());
515 I.setName("");
516 NewPN->op_reserve(PN->getNumOperands());
517 InsertNewInstBefore(NewPN, *PN);
518
519 // Next, add all of the operands to the PHI.
520 if (I.getNumOperands() == 2) {
521 Constant *C = cast<Constant>(I.getOperand(1));
522 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
523 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
524 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
525 PN->getIncomingBlock(i));
526 }
527 } else {
528 assert(isa<CastInst>(I) && "Unary op should be a cast!");
529 const Type *RetTy = I.getType();
530 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
531 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
532 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
533 PN->getIncomingBlock(i));
534 }
535 }
536 return ReplaceInstUsesWith(I, NewPN);
537}
538
Chris Lattner2eefe512004-04-09 19:05:30 +0000539// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
540// constant as the other operand, try to fold the binary operator into the
541// select arguments.
542static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
543 InstCombiner *IC) {
544 // Don't modify shared select instructions
545 if (!SI->hasOneUse()) return 0;
546 Value *TV = SI->getOperand(1);
547 Value *FV = SI->getOperand(2);
548
549 if (isa<Constant>(TV) || isa<Constant>(FV)) {
550 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
551 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
552
553 return new SelectInst(SI->getCondition(), SelectTrueVal,
554 SelectFalseVal);
555 }
556 return 0;
557}
Chris Lattner564a7272003-08-13 19:01:45 +0000558
Chris Lattner7e708292002-06-25 16:13:24 +0000559Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000560 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000561 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000562
Chris Lattner66331a42004-04-10 22:01:55 +0000563 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
564 // X + 0 --> X
565 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
566 RHSC->isNullValue())
567 return ReplaceInstUsesWith(I, LHS);
568
569 // X + (signbit) --> X ^ signbit
570 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
571 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
572 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
573 if (Val == (1ULL << NumBits-1))
Chris Lattner48595f12004-06-10 02:07:29 +0000574 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner66331a42004-04-10 22:01:55 +0000575 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000576
577 if (isa<PHINode>(LHS))
578 if (Instruction *NV = FoldOpIntoPhi(I))
579 return NV;
Chris Lattner66331a42004-04-10 22:01:55 +0000580 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000581
Chris Lattner564a7272003-08-13 19:01:45 +0000582 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +0000583 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000584 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino71698282004-07-27 21:02:21 +0000585 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000586
Chris Lattner5c4afb92002-05-08 22:46:53 +0000587 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +0000588 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000589 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000590
591 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000592 if (!isa<Constant>(RHS))
593 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000594 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000595
Chris Lattnerad3448c2003-02-18 19:57:07 +0000596 // X*C + X --> X * (C+1)
597 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000598 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000599 ConstantExpr::getAdd(
Chris Lattner2a9c8472003-05-27 16:40:51 +0000600 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
601 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +0000602 return BinaryOperator::createMul(RHS, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000603 }
604
605 // X + X*C --> X * (C+1)
606 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000607 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000608 ConstantExpr::getAdd(
Chris Lattner2a9c8472003-05-27 16:40:51 +0000609 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
610 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +0000611 return BinaryOperator::createMul(LHS, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000612 }
613
Chris Lattner564a7272003-08-13 19:01:45 +0000614 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000615 ConstantInt *C2;
616 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +0000617 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000618
Chris Lattner6b032052003-10-02 15:11:26 +0000619 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000620 Value *X;
621 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
622 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
623 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +0000624 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000625
626 // Try to fold constant add into select arguments.
627 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
628 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
629 return R;
Chris Lattner6b032052003-10-02 15:11:26 +0000630 }
631
Chris Lattner7e708292002-06-25 16:13:24 +0000632 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000633}
634
Chris Lattner1ba5bcd2003-07-22 21:46:59 +0000635// isSignBit - Return true if the value represented by the constant only has the
636// highest order bit set.
637static bool isSignBit(ConstantInt *CI) {
638 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
639 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
640}
641
Chris Lattner24c8e382003-07-24 17:35:25 +0000642static unsigned getTypeSizeInBits(const Type *Ty) {
643 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
644}
645
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000646/// RemoveNoopCast - Strip off nonconverting casts from the value.
647///
648static Value *RemoveNoopCast(Value *V) {
649 if (CastInst *CI = dyn_cast<CastInst>(V)) {
650 const Type *CTy = CI->getType();
651 const Type *OpTy = CI->getOperand(0)->getType();
652 if (CTy->isInteger() && OpTy->isInteger()) {
653 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
654 return RemoveNoopCast(CI->getOperand(0));
655 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
656 return RemoveNoopCast(CI->getOperand(0));
657 }
658 return V;
659}
660
Chris Lattner7e708292002-06-25 16:13:24 +0000661Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000662 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000663
Chris Lattner233f7dc2002-08-12 21:17:25 +0000664 if (Op0 == Op1) // sub X, X -> 0
665 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000666
Chris Lattner233f7dc2002-08-12 21:17:25 +0000667 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +0000668 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +0000669 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000670
Chris Lattnerd65460f2003-11-05 01:06:05 +0000671 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
672 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +0000673 if (C->isAllOnesValue())
674 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +0000675
Chris Lattnerd65460f2003-11-05 01:06:05 +0000676 // C - ~X == X + (1+C)
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000677 Value *X;
678 if (match(Op1, m_Not(m_Value(X))))
679 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +0000680 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +0000681 // -((uint)X >> 31) -> ((int)X >> 31)
682 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000683 if (C->isNullValue()) {
684 Value *NoopCastedRHS = RemoveNoopCast(Op1);
685 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-03-12 23:53:13 +0000686 if (SI->getOpcode() == Instruction::Shr)
687 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
688 const Type *NewTy;
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000689 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +0000690 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000691 else
Chris Lattner5dd04022004-06-17 18:16:02 +0000692 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000693 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000694 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner9c290672004-03-12 23:53:13 +0000695 // Ok, the transformation is safe. Insert a cast of the incoming
696 // value, then the new shift, then the new cast.
697 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
698 SI->getOperand(0)->getName());
699 Value *InV = InsertNewInstBefore(FirstCast, I);
700 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
701 CU, SI->getName());
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000702 if (NewShift->getType() == I.getType())
703 return NewShift;
704 else {
705 InV = InsertNewInstBefore(NewShift, I);
706 return new CastInst(NewShift, I.getType());
707 }
Chris Lattner9c290672004-03-12 23:53:13 +0000708 }
709 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000710 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000711
712 // Try to fold constant sub into select arguments.
713 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
714 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
715 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +0000716
717 if (isa<PHINode>(Op0))
718 if (Instruction *NV = FoldOpIntoPhi(I))
719 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +0000720 }
721
Chris Lattnera2881962003-02-18 19:28:33 +0000722 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerfd059242003-10-15 16:48:29 +0000723 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000724 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
725 // is not used by anyone else...
726 //
Chris Lattner0517e722004-02-02 20:09:56 +0000727 if (Op1I->getOpcode() == Instruction::Sub &&
728 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000729 // Swap the two operands of the subexpr...
730 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
731 Op1I->setOperand(0, IIOp1);
732 Op1I->setOperand(1, IIOp0);
733
734 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +0000735 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +0000736 }
737
738 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
739 //
740 if (Op1I->getOpcode() == Instruction::And &&
741 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
742 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
743
Chris Lattnerf523d062004-06-09 05:08:07 +0000744 Value *NewNot =
745 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +0000746 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +0000747 }
Chris Lattnerad3448c2003-02-18 19:57:07 +0000748
Chris Lattner91ccc152004-10-06 15:08:25 +0000749 // -(X sdiv C) -> (X sdiv -C)
750 if (Op1I->getOpcode() == Instruction::Div)
751 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
752 if (CSI->getValue() == 0)
753 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
754 return BinaryOperator::createDiv(Op1I->getOperand(0),
755 ConstantExpr::getNeg(DivRHS));
756
Chris Lattnerad3448c2003-02-18 19:57:07 +0000757 // X - X*C --> X * (1-C)
758 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000759 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000760 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000761 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000762 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattner48595f12004-06-10 02:07:29 +0000763 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000764 }
Chris Lattner40371712002-05-09 01:29:19 +0000765 }
Chris Lattnera2881962003-02-18 19:28:33 +0000766
Chris Lattnerad3448c2003-02-18 19:57:07 +0000767 // X*C - X --> X * (C-1)
768 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000769 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000770 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000771 ConstantInt::get(I.getType(), 1));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000772 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattner48595f12004-06-10 02:07:29 +0000773 return BinaryOperator::createMul(Op1, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000774 }
775
Chris Lattner3f5b8772002-05-06 16:14:14 +0000776 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000777}
778
Chris Lattner4cb170c2004-02-23 06:38:22 +0000779/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
780/// really just returns true if the most significant (sign) bit is set.
781static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
782 if (RHS->getType()->isSigned()) {
783 // True if source is LHS < 0 or LHS <= -1
784 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
785 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
786 } else {
787 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
788 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
789 // the size of the integer type.
790 if (Opcode == Instruction::SetGE)
791 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
792 if (Opcode == Instruction::SetGT)
793 return RHSC->getValue() ==
794 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
795 }
796 return false;
797}
798
Chris Lattner7e708292002-06-25 16:13:24 +0000799Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000800 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +0000801 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000802
Chris Lattner233f7dc2002-08-12 21:17:25 +0000803 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +0000804 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
805 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +0000806
807 // ((X << C1)*C2) == (X * (C2 << C1))
808 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
809 if (SI->getOpcode() == Instruction::Shl)
810 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000811 return BinaryOperator::createMul(SI->getOperand(0),
812 ConstantExpr::getShl(CI, ShOp));
Chris Lattner7c4049c2004-01-12 19:35:11 +0000813
Chris Lattner515c97c2003-09-11 22:24:54 +0000814 if (CI->isNullValue())
815 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
816 if (CI->equalsInt(1)) // X * 1 == X
817 return ReplaceInstUsesWith(I, Op0);
818 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +0000819 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +0000820
Chris Lattner515c97c2003-09-11 22:24:54 +0000821 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattnera2881962003-02-18 19:28:33 +0000822 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
823 return new ShiftInst(Instruction::Shl, Op0,
824 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino71698282004-07-27 21:02:21 +0000825 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +0000826 if (Op1F->isNullValue())
827 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +0000828
Chris Lattnera2881962003-02-18 19:28:33 +0000829 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
830 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
831 if (Op1F->getValue() == 1.0)
832 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
833 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000834
835 // Try to fold constant mul into select arguments.
836 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
837 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
838 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +0000839
840 if (isa<PHINode>(Op0))
841 if (Instruction *NV = FoldOpIntoPhi(I))
842 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000843 }
844
Chris Lattnera4f445b2003-03-10 23:23:04 +0000845 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
846 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000847 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +0000848
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000849 // If one of the operands of the multiply is a cast from a boolean value, then
850 // we know the bool is either zero or one, so this is a 'masking' multiply.
851 // See if we can simplify things based on how the boolean was originally
852 // formed.
853 CastInst *BoolCast = 0;
854 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
855 if (CI->getOperand(0)->getType() == Type::BoolTy)
856 BoolCast = CI;
857 if (!BoolCast)
858 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
859 if (CI->getOperand(0)->getType() == Type::BoolTy)
860 BoolCast = CI;
861 if (BoolCast) {
862 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
863 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
864 const Type *SCOpTy = SCIOp0->getType();
865
Chris Lattner4cb170c2004-02-23 06:38:22 +0000866 // If the setcc is true iff the sign bit of X is set, then convert this
867 // multiply into a shift/and combination.
868 if (isa<ConstantInt>(SCIOp1) &&
869 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000870 // Shift the X value right to turn it into "all signbits".
871 Constant *Amt = ConstantUInt::get(Type::UByteTy,
872 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000873 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000874 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattner4cb170c2004-02-23 06:38:22 +0000875 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
876 SCIOp0->getName()), I);
877 }
878
879 Value *V =
880 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
881 BoolCast->getOperand(0)->getName()+
882 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000883
884 // If the multiply type is not the same as the source type, sign extend
885 // or truncate to the multiply type.
886 if (I.getType() != V->getType())
Chris Lattner4cb170c2004-02-23 06:38:22 +0000887 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000888
889 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +0000890 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000891 }
892 }
893 }
894
Chris Lattner7e708292002-06-25 16:13:24 +0000895 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000896}
897
Chris Lattner7e708292002-06-25 16:13:24 +0000898Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnera2881962003-02-18 19:28:33 +0000899 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattner83a2e6e2004-04-26 14:01:59 +0000900 // div X, 1 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +0000901 if (RHS->equalsInt(1))
902 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattnera2881962003-02-18 19:28:33 +0000903
Chris Lattner83a2e6e2004-04-26 14:01:59 +0000904 // div X, -1 == -X
905 if (RHS->isAllOnesValue())
906 return BinaryOperator::createNeg(I.getOperand(0));
907
Chris Lattner18d19ca2004-09-28 18:22:15 +0000908 if (Instruction *LHS = dyn_cast<Instruction>(I.getOperand(0)))
909 if (LHS->getOpcode() == Instruction::Div)
910 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner18d19ca2004-09-28 18:22:15 +0000911 // (X / C1) / C2 -> X / (C1*C2)
912 return BinaryOperator::createDiv(LHS->getOperand(0),
913 ConstantExpr::getMul(RHS, LHSRHS));
914 }
915
Chris Lattnera2881962003-02-18 19:28:33 +0000916 // Check to see if this is an unsigned division with an exact power of 2,
917 // if so, convert to a right shift.
918 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
919 if (uint64_t Val = C->getValue()) // Don't break X / 0
920 if (uint64_t C = Log2(Val))
921 return new ShiftInst(Instruction::Shr, I.getOperand(0),
922 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner4e998b22004-09-29 05:07:12 +0000923
924 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
925 if (Instruction *NV = FoldOpIntoPhi(I))
926 return NV;
Chris Lattnera2881962003-02-18 19:28:33 +0000927 }
928
929 // 0 / X == 0, we don't need to preserve faults!
930 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
931 if (LHS->equalsInt(0))
932 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
933
Chris Lattner3f5b8772002-05-06 16:14:14 +0000934 return 0;
935}
936
937
Chris Lattner7e708292002-06-25 16:13:24 +0000938Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner5b73c082004-07-06 07:01:22 +0000939 if (I.getType()->isSigned())
940 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner1e3564e2004-07-06 07:11:42 +0000941 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattnerb49f3062004-08-09 21:05:48 +0000942 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner5b73c082004-07-06 07:01:22 +0000943 // X % -Y -> X % Y
944 AddUsesToWorkList(I);
945 I.setOperand(1, RHSNeg);
946 return &I;
947 }
948
Chris Lattnera2881962003-02-18 19:28:33 +0000949 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
950 if (RHS->equalsInt(1)) // X % 1 == 0
951 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
952
953 // Check to see if this is an unsigned remainder with an exact power of 2,
954 // if so, convert to a bitwise and.
955 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
956 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattner546516c2004-05-07 15:35:56 +0000957 if (!(Val & (Val-1))) // Power of 2
Chris Lattner48595f12004-06-10 02:07:29 +0000958 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattnera2881962003-02-18 19:28:33 +0000959 ConstantUInt::get(I.getType(), Val-1));
Chris Lattner4e998b22004-09-29 05:07:12 +0000960 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
961 if (Instruction *NV = FoldOpIntoPhi(I))
962 return NV;
Chris Lattnera2881962003-02-18 19:28:33 +0000963 }
964
965 // 0 % X == 0, we don't need to preserve faults!
966 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
967 if (LHS->equalsInt(0))
Chris Lattner233f7dc2002-08-12 21:17:25 +0000968 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
969
Chris Lattner3f5b8772002-05-06 16:14:14 +0000970 return 0;
971}
972
Chris Lattner8b170942002-08-09 23:47:40 +0000973// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +0000974static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +0000975 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
976 // Calculate -1 casted to the right type...
977 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
978 uint64_t Val = ~0ULL; // All ones
979 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
980 return CU->getValue() == Val-1;
981 }
982
983 const ConstantSInt *CS = cast<ConstantSInt>(C);
984
985 // Calculate 0111111111..11111
986 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
987 int64_t Val = INT64_MAX; // All ones
988 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
989 return CS->getValue() == Val-1;
990}
991
992// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +0000993static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +0000994 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
995 return CU->getValue() == 1;
996
997 const ConstantSInt *CS = cast<ConstantSInt>(C);
998
999 // Calculate 1111111111000000000000
1000 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1001 int64_t Val = -1; // All ones
1002 Val <<= TypeBits-1; // Shift over to the right spot
1003 return CS->getValue() == Val+1;
1004}
1005
Chris Lattner457dd822004-06-09 07:59:58 +00001006// isOneBitSet - Return true if there is exactly one bit set in the specified
1007// constant.
1008static bool isOneBitSet(const ConstantInt *CI) {
1009 uint64_t V = CI->getRawValue();
1010 return V && (V & (V-1)) == 0;
1011}
1012
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00001013#if 0 // Currently unused
1014// isLowOnes - Return true if the constant is of the form 0+1+.
1015static bool isLowOnes(const ConstantInt *CI) {
1016 uint64_t V = CI->getRawValue();
1017
1018 // There won't be bits set in parts that the type doesn't contain.
1019 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1020
1021 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1022 return U && V && (U & V) == 0;
1023}
1024#endif
1025
1026// isHighOnes - Return true if the constant is of the form 1+0+.
1027// This is the same as lowones(~X).
1028static bool isHighOnes(const ConstantInt *CI) {
1029 uint64_t V = ~CI->getRawValue();
1030
1031 // There won't be bits set in parts that the type doesn't contain.
1032 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1033
1034 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1035 return U && V && (U & V) == 0;
1036}
1037
1038
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001039/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1040/// are carefully arranged to allow folding of expressions such as:
1041///
1042/// (A < B) | (A > B) --> (A != B)
1043///
1044/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1045/// represents that the comparison is true if A == B, and bit value '1' is true
1046/// if A < B.
1047///
1048static unsigned getSetCondCode(const SetCondInst *SCI) {
1049 switch (SCI->getOpcode()) {
1050 // False -> 0
1051 case Instruction::SetGT: return 1;
1052 case Instruction::SetEQ: return 2;
1053 case Instruction::SetGE: return 3;
1054 case Instruction::SetLT: return 4;
1055 case Instruction::SetNE: return 5;
1056 case Instruction::SetLE: return 6;
1057 // True -> 7
1058 default:
1059 assert(0 && "Invalid SetCC opcode!");
1060 return 0;
1061 }
1062}
1063
1064/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1065/// opcode and two operands into either a constant true or false, or a brand new
1066/// SetCC instruction.
1067static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1068 switch (Opcode) {
1069 case 0: return ConstantBool::False;
1070 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1071 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1072 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1073 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1074 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1075 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1076 case 7: return ConstantBool::True;
1077 default: assert(0 && "Illegal SetCCCode!"); return 0;
1078 }
1079}
1080
1081// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1082struct FoldSetCCLogical {
1083 InstCombiner &IC;
1084 Value *LHS, *RHS;
1085 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1086 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1087 bool shouldApply(Value *V) const {
1088 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1089 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1090 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1091 return false;
1092 }
1093 Instruction *apply(BinaryOperator &Log) const {
1094 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1095 if (SCI->getOperand(0) != LHS) {
1096 assert(SCI->getOperand(1) == LHS);
1097 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1098 }
1099
1100 unsigned LHSCode = getSetCondCode(SCI);
1101 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1102 unsigned Code;
1103 switch (Log.getOpcode()) {
1104 case Instruction::And: Code = LHSCode & RHSCode; break;
1105 case Instruction::Or: Code = LHSCode | RHSCode; break;
1106 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00001107 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001108 }
1109
1110 Value *RV = getSetCCValue(Code, LHS, RHS);
1111 if (Instruction *I = dyn_cast<Instruction>(RV))
1112 return I;
1113 // Otherwise, it's a constant boolean value...
1114 return IC.ReplaceInstUsesWith(Log, RV);
1115 }
1116};
1117
1118
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001119// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1120// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1121// guaranteed to be either a shift instruction or a binary operator.
1122Instruction *InstCombiner::OptAndOp(Instruction *Op,
1123 ConstantIntegral *OpRHS,
1124 ConstantIntegral *AndRHS,
1125 BinaryOperator &TheAnd) {
1126 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00001127 Constant *Together = 0;
1128 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00001129 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001130
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001131 switch (Op->getOpcode()) {
1132 case Instruction::Xor:
Chris Lattner7c4049c2004-01-12 19:35:11 +00001133 if (Together->isNullValue()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001134 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattner48595f12004-06-10 02:07:29 +00001135 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001136 } else if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001137 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1138 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001139 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001140 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001141 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001142 }
1143 break;
1144 case Instruction::Or:
1145 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattner7c4049c2004-01-12 19:35:11 +00001146 if (Together->isNullValue())
Chris Lattner48595f12004-06-10 02:07:29 +00001147 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001148 else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001149 if (Together == AndRHS) // (X | C) & C --> C
1150 return ReplaceInstUsesWith(TheAnd, AndRHS);
1151
Chris Lattnerfd059242003-10-15 16:48:29 +00001152 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001153 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1154 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001155 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001156 InsertNewInstBefore(Or, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001157 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001158 }
1159 }
1160 break;
1161 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00001162 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001163 // Adding a one to a single bit bit-field should be turned into an XOR
1164 // of the bit. First thing to check is to see if this AND is with a
1165 // single bit constant.
Chris Lattner457dd822004-06-09 07:59:58 +00001166 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001167
1168 // Clear bits that are not part of the constant.
1169 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1170
1171 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00001172 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001173 // Ok, at this point, we know that we are masking the result of the
1174 // ADD down to exactly one bit. If the constant we are adding has
1175 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner457dd822004-06-09 07:59:58 +00001176 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001177
1178 // Check to see if any bits below the one bit set in AndRHSV are set.
1179 if ((AddRHS & (AndRHSV-1)) == 0) {
1180 // If not, the only thing that can effect the output of the AND is
1181 // the bit specified by AndRHSV. If that bit is set, the effect of
1182 // the XOR is to toggle the bit. If it is clear, then the ADD has
1183 // no effect.
1184 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1185 TheAnd.setOperand(0, X);
1186 return &TheAnd;
1187 } else {
1188 std::string Name = Op->getName(); Op->setName("");
1189 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00001190 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001191 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001192 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001193 }
1194 }
1195 }
1196 }
1197 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00001198
1199 case Instruction::Shl: {
1200 // We know that the AND will not produce any of the bits shifted in, so if
1201 // the anded constant includes them, clear them now!
1202 //
1203 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001204 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1205 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1206
1207 if (CI == ShlMask) { // Masking out bits that the shift already masks
1208 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1209 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00001210 TheAnd.setOperand(1, CI);
1211 return &TheAnd;
1212 }
1213 break;
1214 }
1215 case Instruction::Shr:
1216 // We know that the AND will not produce any of the bits shifted in, so if
1217 // the anded constant includes them, clear them now! This only applies to
1218 // unsigned shifts, because a signed shr may bring in set bits!
1219 //
1220 if (AndRHS->getType()->isUnsigned()) {
1221 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001222 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1223 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1224
1225 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1226 return ReplaceInstUsesWith(TheAnd, Op);
1227 } else if (CI != AndRHS) {
1228 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner62a355c2003-09-19 19:05:02 +00001229 return &TheAnd;
1230 }
Chris Lattner0c967662004-09-24 15:21:34 +00001231 } else { // Signed shr.
1232 // See if this is shifting in some sign extension, then masking it out
1233 // with an and.
1234 if (Op->hasOneUse()) {
1235 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1236 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1237 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1238 if (CI == ShrMask) { // Masking out bits shifted in.
1239 // Make the argument unsigned.
1240 Value *ShVal = Op->getOperand(0);
1241 ShVal = InsertCastBefore(ShVal,
1242 ShVal->getType()->getUnsignedVersion(),
1243 TheAnd);
1244 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1245 OpRHS, Op->getName()),
1246 TheAnd);
1247 return new CastInst(ShVal, Op->getType());
1248 }
1249 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001250 }
1251 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001252 }
1253 return 0;
1254}
1255
Chris Lattner8b170942002-08-09 23:47:40 +00001256
Chris Lattnera96879a2004-09-29 17:40:11 +00001257/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1258/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1259/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1260/// insert new instructions.
1261Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1262 bool Inside, Instruction &IB) {
1263 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1264 "Lo is not <= Hi in range emission code!");
1265 if (Inside) {
1266 if (Lo == Hi) // Trivially false.
1267 return new SetCondInst(Instruction::SetNE, V, V);
1268 if (cast<ConstantIntegral>(Lo)->isMinValue())
1269 return new SetCondInst(Instruction::SetLT, V, Hi);
1270
1271 Constant *AddCST = ConstantExpr::getNeg(Lo);
1272 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1273 InsertNewInstBefore(Add, IB);
1274 // Convert to unsigned for the comparison.
1275 const Type *UnsType = Add->getType()->getUnsignedVersion();
1276 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1277 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1278 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1279 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1280 }
1281
1282 if (Lo == Hi) // Trivially true.
1283 return new SetCondInst(Instruction::SetEQ, V, V);
1284
1285 Hi = SubOne(cast<ConstantInt>(Hi));
1286 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1287 return new SetCondInst(Instruction::SetGT, V, Hi);
1288
1289 // Emit X-Lo > Hi-Lo-1
1290 Constant *AddCST = ConstantExpr::getNeg(Lo);
1291 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1292 InsertNewInstBefore(Add, IB);
1293 // Convert to unsigned for the comparison.
1294 const Type *UnsType = Add->getType()->getUnsignedVersion();
1295 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1296 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1297 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1298 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1299}
1300
1301
Chris Lattner7e708292002-06-25 16:13:24 +00001302Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001303 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001304 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001305
1306 // and X, X = X and X, 0 == 0
Chris Lattner233f7dc2002-08-12 21:17:25 +00001307 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1308 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001309
1310 // and X, -1 == X
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001311 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner233f7dc2002-08-12 21:17:25 +00001312 if (RHS->isAllOnesValue())
1313 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001314
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001315 // Optimize a variety of ((val OP C1) & C2) combinations...
1316 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1317 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner06782f82003-07-23 19:36:21 +00001318 Value *X = Op0I->getOperand(0);
Chris Lattner58403262003-07-23 19:25:52 +00001319 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001320 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1321 return Res;
Chris Lattner06782f82003-07-23 19:36:21 +00001322 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001323
1324 // Try to fold constant and into select arguments.
1325 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1326 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1327 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001328 if (isa<PHINode>(Op0))
1329 if (Instruction *NV = FoldOpIntoPhi(I))
1330 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001331 }
1332
Chris Lattner8d969642003-03-10 23:06:50 +00001333 Value *Op0NotVal = dyn_castNotVal(Op0);
1334 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001335
Chris Lattner5b62aa72004-06-18 06:07:51 +00001336 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1337 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1338
Misha Brukmancb6267b2004-07-30 12:50:08 +00001339 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00001340 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00001341 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1342 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001343 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00001344 return BinaryOperator::createNot(Or);
1345 }
1346
Chris Lattner955f3312004-09-28 21:48:02 +00001347 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1348 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001349 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1350 return R;
1351
Chris Lattner955f3312004-09-28 21:48:02 +00001352 Value *LHSVal, *RHSVal;
1353 ConstantInt *LHSCst, *RHSCst;
1354 Instruction::BinaryOps LHSCC, RHSCC;
1355 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1356 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1357 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1358 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1359 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1360 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1361 // Ensure that the larger constant is on the RHS.
1362 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1363 SetCondInst *LHS = cast<SetCondInst>(Op0);
1364 if (cast<ConstantBool>(Cmp)->getValue()) {
1365 std::swap(LHS, RHS);
1366 std::swap(LHSCst, RHSCst);
1367 std::swap(LHSCC, RHSCC);
1368 }
1369
1370 // At this point, we know we have have two setcc instructions
1371 // comparing a value against two constants and and'ing the result
1372 // together. Because of the above check, we know that we only have
1373 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1374 // FoldSetCCLogical check above), that the two constants are not
1375 // equal.
1376 assert(LHSCst != RHSCst && "Compares not folded above?");
1377
1378 switch (LHSCC) {
1379 default: assert(0 && "Unknown integer condition code!");
1380 case Instruction::SetEQ:
1381 switch (RHSCC) {
1382 default: assert(0 && "Unknown integer condition code!");
1383 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1384 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1385 return ReplaceInstUsesWith(I, ConstantBool::False);
1386 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1387 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1388 return ReplaceInstUsesWith(I, LHS);
1389 }
1390 case Instruction::SetNE:
1391 switch (RHSCC) {
1392 default: assert(0 && "Unknown integer condition code!");
1393 case Instruction::SetLT:
1394 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1395 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1396 break; // (X != 13 & X < 15) -> no change
1397 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1398 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1399 return ReplaceInstUsesWith(I, RHS);
1400 case Instruction::SetNE:
1401 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1402 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1403 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1404 LHSVal->getName()+".off");
1405 InsertNewInstBefore(Add, I);
1406 const Type *UnsType = Add->getType()->getUnsignedVersion();
1407 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1408 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1409 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1410 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1411 }
1412 break; // (X != 13 & X != 15) -> no change
1413 }
1414 break;
1415 case Instruction::SetLT:
1416 switch (RHSCC) {
1417 default: assert(0 && "Unknown integer condition code!");
1418 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1419 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1420 return ReplaceInstUsesWith(I, ConstantBool::False);
1421 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1422 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1423 return ReplaceInstUsesWith(I, LHS);
1424 }
1425 case Instruction::SetGT:
1426 switch (RHSCC) {
1427 default: assert(0 && "Unknown integer condition code!");
1428 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1429 return ReplaceInstUsesWith(I, LHS);
1430 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1431 return ReplaceInstUsesWith(I, RHS);
1432 case Instruction::SetNE:
1433 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1434 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1435 break; // (X > 13 & X != 15) -> no change
Chris Lattnera96879a2004-09-29 17:40:11 +00001436 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1437 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner955f3312004-09-28 21:48:02 +00001438 }
1439 }
1440 }
1441 }
1442
Chris Lattner7e708292002-06-25 16:13:24 +00001443 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001444}
1445
Chris Lattner7e708292002-06-25 16:13:24 +00001446Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001447 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001448 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001449
1450 // or X, X = X or X, 0 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00001451 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1452 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001453
1454 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001455 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner233f7dc2002-08-12 21:17:25 +00001456 if (RHS->isAllOnesValue())
1457 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001458
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001459 ConstantInt *C1; Value *X;
1460 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1461 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1462 std::string Op0Name = Op0->getName(); Op0->setName("");
1463 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1464 InsertNewInstBefore(Or, I);
1465 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1466 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001467
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001468 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1469 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1470 std::string Op0Name = Op0->getName(); Op0->setName("");
1471 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1472 InsertNewInstBefore(Or, I);
1473 return BinaryOperator::createXor(Or,
1474 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001475 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001476
1477 // Try to fold constant and into select arguments.
1478 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1479 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1480 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001481 if (isa<PHINode>(Op0))
1482 if (Instruction *NV = FoldOpIntoPhi(I))
1483 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001484 }
1485
Chris Lattner67ca7682003-08-12 19:11:07 +00001486 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001487 Value *A, *B; ConstantInt *C1, *C2;
1488 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1489 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1490 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner67ca7682003-08-12 19:11:07 +00001491
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001492 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1493 if (A == Op1) // ~A | A == -1
1494 return ReplaceInstUsesWith(I,
1495 ConstantIntegral::getAllOnesValue(I.getType()));
1496 } else {
1497 A = 0;
1498 }
Chris Lattnera2881962003-02-18 19:28:33 +00001499
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001500 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1501 if (Op0 == B)
1502 return ReplaceInstUsesWith(I,
1503 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00001504
Misha Brukmancb6267b2004-07-30 12:50:08 +00001505 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001506 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1507 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1508 I.getName()+".demorgan"), I);
1509 return BinaryOperator::createNot(And);
1510 }
Chris Lattnera27231a2003-03-10 23:13:59 +00001511 }
Chris Lattnera2881962003-02-18 19:28:33 +00001512
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001513 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerb4f40d22004-09-28 22:33:08 +00001514 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001515 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1516 return R;
1517
Chris Lattnerb4f40d22004-09-28 22:33:08 +00001518 Value *LHSVal, *RHSVal;
1519 ConstantInt *LHSCst, *RHSCst;
1520 Instruction::BinaryOps LHSCC, RHSCC;
1521 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1522 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1523 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1524 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1525 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1526 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1527 // Ensure that the larger constant is on the RHS.
1528 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1529 SetCondInst *LHS = cast<SetCondInst>(Op0);
1530 if (cast<ConstantBool>(Cmp)->getValue()) {
1531 std::swap(LHS, RHS);
1532 std::swap(LHSCst, RHSCst);
1533 std::swap(LHSCC, RHSCC);
1534 }
1535
1536 // At this point, we know we have have two setcc instructions
1537 // comparing a value against two constants and or'ing the result
1538 // together. Because of the above check, we know that we only have
1539 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1540 // FoldSetCCLogical check above), that the two constants are not
1541 // equal.
1542 assert(LHSCst != RHSCst && "Compares not folded above?");
1543
1544 switch (LHSCC) {
1545 default: assert(0 && "Unknown integer condition code!");
1546 case Instruction::SetEQ:
1547 switch (RHSCC) {
1548 default: assert(0 && "Unknown integer condition code!");
1549 case Instruction::SetEQ:
1550 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1551 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1552 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1553 LHSVal->getName()+".off");
1554 InsertNewInstBefore(Add, I);
1555 const Type *UnsType = Add->getType()->getUnsignedVersion();
1556 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1557 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1558 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1559 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1560 }
1561 break; // (X == 13 | X == 15) -> no change
1562
1563 case Instruction::SetGT:
1564 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1565 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1566 break; // (X == 13 | X > 15) -> no change
1567 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1568 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1569 return ReplaceInstUsesWith(I, RHS);
1570 }
1571 break;
1572 case Instruction::SetNE:
1573 switch (RHSCC) {
1574 default: assert(0 && "Unknown integer condition code!");
1575 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1576 return ReplaceInstUsesWith(I, RHS);
1577 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1578 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1579 return ReplaceInstUsesWith(I, LHS);
1580 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1581 return ReplaceInstUsesWith(I, ConstantBool::True);
1582 }
1583 break;
1584 case Instruction::SetLT:
1585 switch (RHSCC) {
1586 default: assert(0 && "Unknown integer condition code!");
1587 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1588 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00001589 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1590 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00001591 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1592 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1593 return ReplaceInstUsesWith(I, RHS);
1594 }
1595 break;
1596 case Instruction::SetGT:
1597 switch (RHSCC) {
1598 default: assert(0 && "Unknown integer condition code!");
1599 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1600 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1601 return ReplaceInstUsesWith(I, LHS);
1602 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1603 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1604 return ReplaceInstUsesWith(I, ConstantBool::True);
1605 }
1606 }
1607 }
1608 }
Chris Lattner7e708292002-06-25 16:13:24 +00001609 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001610}
1611
Chris Lattnerc317d392004-02-16 01:20:27 +00001612// XorSelf - Implements: X ^ X --> 0
1613struct XorSelf {
1614 Value *RHS;
1615 XorSelf(Value *rhs) : RHS(rhs) {}
1616 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1617 Instruction *apply(BinaryOperator &Xor) const {
1618 return &Xor;
1619 }
1620};
Chris Lattner3f5b8772002-05-06 16:14:14 +00001621
1622
Chris Lattner7e708292002-06-25 16:13:24 +00001623Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001624 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001625 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001626
Chris Lattnerc317d392004-02-16 01:20:27 +00001627 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1628 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1629 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00001630 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00001631 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001632
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001633 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner8b170942002-08-09 23:47:40 +00001634 // xor X, 0 == X
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001635 if (RHS->isNullValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00001636 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8b170942002-08-09 23:47:40 +00001637
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001638 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00001639 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001640 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerfd059242003-10-15 16:48:29 +00001641 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00001642 return new SetCondInst(SCI->getInverseCondition(),
1643 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001644
Chris Lattnerd65460f2003-11-05 01:06:05 +00001645 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00001646 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1647 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00001648 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1649 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00001650 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00001651 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001652 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00001653
1654 // ~(~X & Y) --> (X | ~Y)
1655 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1656 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1657 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1658 Instruction *NotY =
1659 BinaryOperator::createNot(Op0I->getOperand(1),
1660 Op0I->getOperand(1)->getName()+".not");
1661 InsertNewInstBefore(NotY, I);
1662 return BinaryOperator::createOr(Op0NotVal, NotY);
1663 }
1664 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001665
1666 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001667 switch (Op0I->getOpcode()) {
1668 case Instruction::Add:
Chris Lattner689d24b2003-11-04 23:37:10 +00001669 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00001670 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00001671 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1672 return BinaryOperator::createSub(
1673 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00001674 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00001675 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00001676 }
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001677 break;
1678 case Instruction::And:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001679 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattner48595f12004-06-10 02:07:29 +00001680 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1681 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001682 break;
1683 case Instruction::Or:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001684 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattner48595f12004-06-10 02:07:29 +00001685 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattner448c3232004-06-10 02:12:35 +00001686 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001687 break;
1688 default: break;
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001689 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00001690 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001691
1692 // Try to fold constant and into select arguments.
1693 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1694 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1695 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001696 if (isa<PHINode>(Op0))
1697 if (Instruction *NV = FoldOpIntoPhi(I))
1698 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001699 }
1700
Chris Lattner8d969642003-03-10 23:06:50 +00001701 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00001702 if (X == Op1)
1703 return ReplaceInstUsesWith(I,
1704 ConstantIntegral::getAllOnesValue(I.getType()));
1705
Chris Lattner8d969642003-03-10 23:06:50 +00001706 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00001707 if (X == Op0)
1708 return ReplaceInstUsesWith(I,
1709 ConstantIntegral::getAllOnesValue(I.getType()));
1710
Chris Lattnercb40a372003-03-10 18:24:17 +00001711 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00001712 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00001713 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1714 cast<BinaryOperator>(Op1I)->swapOperands();
1715 I.swapOperands();
1716 std::swap(Op0, Op1);
1717 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1718 I.swapOperands();
1719 std::swap(Op0, Op1);
Chris Lattner26ca7e12004-02-16 03:54:20 +00001720 }
1721 } else if (Op1I->getOpcode() == Instruction::Xor) {
1722 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1723 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1724 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1725 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1726 }
Chris Lattnercb40a372003-03-10 18:24:17 +00001727
1728 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00001729 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00001730 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1731 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00001732 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerf523d062004-06-09 05:08:07 +00001733 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1734 Op1->getName()+".not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00001735 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00001736 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00001737 } else if (Op0I->getOpcode() == Instruction::Xor) {
1738 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1739 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1740 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1741 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnercb40a372003-03-10 18:24:17 +00001742 }
1743
Chris Lattner14840892004-08-01 19:42:59 +00001744 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001745 Value *A, *B; ConstantInt *C1, *C2;
1746 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1747 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner14840892004-08-01 19:42:59 +00001748 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001749 return BinaryOperator::createOr(Op0, Op1);
Chris Lattnerc8802d22003-03-11 00:12:48 +00001750
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001751 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1752 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1753 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1754 return R;
1755
Chris Lattner7e708292002-06-25 16:13:24 +00001756 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001757}
1758
Chris Lattnera96879a2004-09-29 17:40:11 +00001759/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1760/// overflowed for this type.
1761static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1762 ConstantInt *In2) {
1763 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1764 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1765}
1766
1767static bool isPositive(ConstantInt *C) {
1768 return cast<ConstantSInt>(C)->getValue() >= 0;
1769}
1770
1771/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1772/// overflowed for this type.
1773static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1774 ConstantInt *In2) {
1775 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1776
1777 if (In1->getType()->isUnsigned())
1778 return cast<ConstantUInt>(Result)->getValue() <
1779 cast<ConstantUInt>(In1)->getValue();
1780 if (isPositive(In1) != isPositive(In2))
1781 return false;
1782 if (isPositive(In1))
1783 return cast<ConstantSInt>(Result)->getValue() <
1784 cast<ConstantSInt>(In1)->getValue();
1785 return cast<ConstantSInt>(Result)->getValue() >
1786 cast<ConstantSInt>(In1)->getValue();
1787}
1788
Chris Lattner7e708292002-06-25 16:13:24 +00001789Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001790 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00001791 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1792 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00001793
1794 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00001795 if (Op0 == Op1)
1796 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00001797
Chris Lattner3ccd17e2003-08-13 05:38:46 +00001798 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1799 if (isa<ConstantPointerNull>(Op1) &&
1800 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner8b170942002-08-09 23:47:40 +00001801 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1802
Chris Lattner3ccd17e2003-08-13 05:38:46 +00001803
Chris Lattner8b170942002-08-09 23:47:40 +00001804 // setcc's with boolean values can always be turned into bitwise operations
1805 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-08-11 00:50:51 +00001806 switch (I.getOpcode()) {
1807 default: assert(0 && "Invalid setcc instruction!");
1808 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00001809 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00001810 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00001811 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00001812 }
Chris Lattner5dbef222004-08-11 00:50:51 +00001813 case Instruction::SetNE:
1814 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00001815
Chris Lattner5dbef222004-08-11 00:50:51 +00001816 case Instruction::SetGT:
1817 std::swap(Op0, Op1); // Change setgt -> setlt
1818 // FALL THROUGH
1819 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1820 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1821 InsertNewInstBefore(Not, I);
1822 return BinaryOperator::createAnd(Not, Op1);
1823 }
1824 case Instruction::SetGE:
Chris Lattner8b170942002-08-09 23:47:40 +00001825 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-08-11 00:50:51 +00001826 // FALL THROUGH
1827 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1828 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1829 InsertNewInstBefore(Not, I);
1830 return BinaryOperator::createOr(Not, Op1);
1831 }
1832 }
Chris Lattner8b170942002-08-09 23:47:40 +00001833 }
1834
Chris Lattner2be51ae2004-06-09 04:24:29 +00001835 // See if we are doing a comparison between a constant and an instruction that
1836 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00001837 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera96879a2004-09-29 17:40:11 +00001838 // Check to see if we are comparing against the minimum or maximum value...
1839 if (CI->isMinValue()) {
1840 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1841 return ReplaceInstUsesWith(I, ConstantBool::False);
1842 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1843 return ReplaceInstUsesWith(I, ConstantBool::True);
1844 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1845 return BinaryOperator::createSetEQ(Op0, Op1);
1846 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1847 return BinaryOperator::createSetNE(Op0, Op1);
1848
1849 } else if (CI->isMaxValue()) {
1850 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1851 return ReplaceInstUsesWith(I, ConstantBool::False);
1852 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1853 return ReplaceInstUsesWith(I, ConstantBool::True);
1854 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1855 return BinaryOperator::createSetEQ(Op0, Op1);
1856 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1857 return BinaryOperator::createSetNE(Op0, Op1);
1858
1859 // Comparing against a value really close to min or max?
1860 } else if (isMinValuePlusOne(CI)) {
1861 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1862 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
1863 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1864 return BinaryOperator::createSetNE(Op0, SubOne(CI));
1865
1866 } else if (isMaxValueMinusOne(CI)) {
1867 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1868 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
1869 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1870 return BinaryOperator::createSetNE(Op0, AddOne(CI));
1871 }
1872
1873 // If we still have a setle or setge instruction, turn it into the
1874 // appropriate setlt or setgt instruction. Since the border cases have
1875 // already been handled above, this requires little checking.
1876 //
1877 if (I.getOpcode() == Instruction::SetLE)
1878 return BinaryOperator::createSetLT(Op0, AddOne(CI));
1879 if (I.getOpcode() == Instruction::SetGE)
1880 return BinaryOperator::createSetGT(Op0, SubOne(CI));
1881
Chris Lattner3c6a0d42004-05-25 06:32:08 +00001882 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00001883 switch (LHSI->getOpcode()) {
Chris Lattner4e998b22004-09-29 05:07:12 +00001884 case Instruction::PHI:
1885 if (Instruction *NV = FoldOpIntoPhi(I))
1886 return NV;
1887 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00001888 case Instruction::And:
1889 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1890 LHSI->getOperand(0)->hasOneUse()) {
1891 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1892 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1893 // happens a LOT in code produced by the C front-end, for bitfield
1894 // access.
1895 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1896 ConstantUInt *ShAmt;
1897 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1898 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1899 const Type *Ty = LHSI->getType();
1900
1901 // We can fold this as long as we can't shift unknown bits
1902 // into the mask. This can only happen with signed shift
1903 // rights, as they sign-extend.
1904 if (ShAmt) {
1905 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner0cba71b2004-09-28 17:54:07 +00001906 Shift->getType()->isUnsigned();
Chris Lattner648e3bc2004-09-23 21:52:49 +00001907 if (!CanFold) {
1908 // To test for the bad case of the signed shr, see if any
1909 // of the bits shifted in could be tested after the mask.
1910 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerf0cacc02004-07-21 20:14:10 +00001911 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattner648e3bc2004-09-23 21:52:49 +00001912 Constant *ShVal =
1913 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1914 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1915 CanFold = true;
1916 }
1917
1918 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00001919 Constant *NewCst;
1920 if (Shift->getOpcode() == Instruction::Shl)
1921 NewCst = ConstantExpr::getUShr(CI, ShAmt);
1922 else
1923 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00001924
Chris Lattner648e3bc2004-09-23 21:52:49 +00001925 // Check to see if we are shifting out any of the bits being
1926 // compared.
1927 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1928 // If we shifted bits out, the fold is not going to work out.
1929 // As a special case, check to see if this means that the
1930 // result is always true or false now.
1931 if (I.getOpcode() == Instruction::SetEQ)
1932 return ReplaceInstUsesWith(I, ConstantBool::False);
1933 if (I.getOpcode() == Instruction::SetNE)
1934 return ReplaceInstUsesWith(I, ConstantBool::True);
1935 } else {
1936 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00001937 Constant *NewAndCST;
1938 if (Shift->getOpcode() == Instruction::Shl)
1939 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
1940 else
1941 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1942 LHSI->setOperand(1, NewAndCST);
Chris Lattner648e3bc2004-09-23 21:52:49 +00001943 LHSI->setOperand(0, Shift->getOperand(0));
1944 WorkList.push_back(Shift); // Shift is dead.
1945 AddUsesToWorkList(I);
1946 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00001947 }
1948 }
Chris Lattner457dd822004-06-09 07:59:58 +00001949 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00001950 }
1951 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00001952
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00001953 case Instruction::Cast: { // (setcc (cast X to larger), CI)
1954 const Type *SrcTy = LHSI->getOperand(0)->getType();
1955 if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) {
Chris Lattnerdd763f42004-09-29 03:16:24 +00001956 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00001957 if (SrcTy == Type::BoolTy) SrcBits = 1;
Chris Lattnerdd763f42004-09-29 03:16:24 +00001958 unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00001959 if (LHSI->getType() == Type::BoolTy) DestBits = 1;
1960 if (SrcBits < DestBits) {
1961 // Check to see if the comparison is always true or false.
1962 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
1963 if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
1964 Constant *Min = ConstantIntegral::getMinValue(SrcTy);
1965 Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
1966 Min = ConstantExpr::getCast(Min, LHSI->getType());
1967 Max = ConstantExpr::getCast(Max, LHSI->getType());
1968 switch (I.getOpcode()) {
1969 default: assert(0 && "unknown integer comparison");
1970 case Instruction::SetEQ:
1971 return ReplaceInstUsesWith(I, ConstantBool::False);
1972 case Instruction::SetNE:
1973 return ReplaceInstUsesWith(I, ConstantBool::True);
1974 case Instruction::SetLT:
1975 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00001976 case Instruction::SetGT:
1977 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
Chris Lattnerf6d1d7d2004-09-29 03:09:18 +00001978 }
1979 }
1980
1981 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
1982 ConstantExpr::getCast(CI, SrcTy));
1983 }
1984 }
1985 break;
1986 }
Chris Lattner18d19ca2004-09-28 18:22:15 +00001987 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
1988 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
1989 switch (I.getOpcode()) {
1990 default: break;
1991 case Instruction::SetEQ:
1992 case Instruction::SetNE: {
1993 // If we are comparing against bits always shifted out, the
1994 // comparison cannot succeed.
1995 Constant *Comp =
1996 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
1997 if (Comp != CI) {// Comparing against a bit that we know is zero.
1998 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
1999 Constant *Cst = ConstantBool::get(IsSetNE);
2000 return ReplaceInstUsesWith(I, Cst);
2001 }
2002
2003 if (LHSI->hasOneUse()) {
2004 // Otherwise strength reduce the shift into an and.
2005 unsigned ShAmtVal = ShAmt->getValue();
2006 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2007 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2008
2009 Constant *Mask;
2010 if (CI->getType()->isUnsigned()) {
2011 Mask = ConstantUInt::get(CI->getType(), Val);
2012 } else if (ShAmtVal != 0) {
2013 Mask = ConstantSInt::get(CI->getType(), Val);
2014 } else {
2015 Mask = ConstantInt::getAllOnesValue(CI->getType());
2016 }
2017
2018 Instruction *AndI =
2019 BinaryOperator::createAnd(LHSI->getOperand(0),
2020 Mask, LHSI->getName()+".mask");
2021 Value *And = InsertNewInstBefore(AndI, I);
2022 return new SetCondInst(I.getOpcode(), And,
2023 ConstantExpr::getUShr(CI, ShAmt));
2024 }
2025 }
2026 }
2027 }
2028 break;
2029
Chris Lattner83c4ec02004-09-27 19:29:18 +00002030 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattnerf63f6472004-09-27 16:18:50 +00002031 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerf63f6472004-09-27 16:18:50 +00002032 switch (I.getOpcode()) {
2033 default: break;
2034 case Instruction::SetEQ:
2035 case Instruction::SetNE: {
2036 // If we are comparing against bits always shifted out, the
2037 // comparison cannot succeed.
2038 Constant *Comp =
2039 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2040
2041 if (Comp != CI) {// Comparing against a bit that we know is zero.
2042 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2043 Constant *Cst = ConstantBool::get(IsSetNE);
2044 return ReplaceInstUsesWith(I, Cst);
2045 }
2046
2047 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner18d19ca2004-09-28 18:22:15 +00002048 unsigned ShAmtVal = ShAmt->getValue();
2049
Chris Lattnerf63f6472004-09-27 16:18:50 +00002050 // Otherwise strength reduce the shift into an and.
2051 uint64_t Val = ~0ULL; // All ones.
2052 Val <<= ShAmtVal; // Shift over to the right spot.
2053
2054 Constant *Mask;
2055 if (CI->getType()->isUnsigned()) {
2056 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2057 Val &= (1ULL << TypeBits)-1;
2058 Mask = ConstantUInt::get(CI->getType(), Val);
2059 } else {
2060 Mask = ConstantSInt::get(CI->getType(), Val);
2061 }
2062
2063 Instruction *AndI =
2064 BinaryOperator::createAnd(LHSI->getOperand(0),
2065 Mask, LHSI->getName()+".mask");
2066 Value *And = InsertNewInstBefore(AndI, I);
2067 return new SetCondInst(I.getOpcode(), And,
2068 ConstantExpr::getShl(CI, ShAmt));
2069 }
2070 break;
2071 }
2072 }
2073 }
2074 break;
Chris Lattner0c967662004-09-24 15:21:34 +00002075
Chris Lattnera96879a2004-09-29 17:40:11 +00002076 case Instruction::Div:
2077 // Fold: (div X, C1) op C2 -> range check
2078 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2079 // Fold this div into the comparison, producing a range check.
2080 // Determine, based on the divide type, what the range is being
2081 // checked. If there is an overflow on the low or high side, remember
2082 // it, otherwise compute the range [low, hi) bounding the new value.
2083 bool LoOverflow = false, HiOverflow = 0;
2084 ConstantInt *LoBound = 0, *HiBound = 0;
2085
2086 ConstantInt *Prod;
2087 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2088
2089 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2090 } else if (LHSI->getType()->isUnsigned()) { // udiv
2091 LoBound = Prod;
2092 LoOverflow = ProdOV;
2093 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2094 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2095 if (CI->isNullValue()) { // (X / pos) op 0
2096 // Can't overflow.
2097 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2098 HiBound = DivRHS;
2099 } else if (isPositive(CI)) { // (X / pos) op pos
2100 LoBound = Prod;
2101 LoOverflow = ProdOV;
2102 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2103 } else { // (X / pos) op neg
2104 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2105 LoOverflow = AddWithOverflow(LoBound, Prod,
2106 cast<ConstantInt>(DivRHSH));
2107 HiBound = Prod;
2108 HiOverflow = ProdOV;
2109 }
2110 } else { // Divisor is < 0.
2111 if (CI->isNullValue()) { // (X / neg) op 0
2112 LoBound = AddOne(DivRHS);
2113 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2114 } else if (isPositive(CI)) { // (X / neg) op pos
2115 HiOverflow = LoOverflow = ProdOV;
2116 if (!LoOverflow)
2117 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2118 HiBound = AddOne(Prod);
2119 } else { // (X / neg) op neg
2120 LoBound = Prod;
2121 LoOverflow = HiOverflow = ProdOV;
2122 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2123 }
2124 }
2125
2126 if (LoBound) {
2127 Value *X = LHSI->getOperand(0);
Chris Lattnera96879a2004-09-29 17:40:11 +00002128 switch (I.getOpcode()) {
2129 default: assert(0 && "Unhandled setcc opcode!");
2130 case Instruction::SetEQ:
2131 if (LoOverflow && HiOverflow)
2132 return ReplaceInstUsesWith(I, ConstantBool::False);
2133 else if (HiOverflow)
2134 return new SetCondInst(Instruction::SetGE, X, LoBound);
2135 else if (LoOverflow)
2136 return new SetCondInst(Instruction::SetLT, X, HiBound);
2137 else
2138 return InsertRangeTest(X, LoBound, HiBound, true, I);
2139 case Instruction::SetNE:
2140 if (LoOverflow && HiOverflow)
2141 return ReplaceInstUsesWith(I, ConstantBool::True);
2142 else if (HiOverflow)
2143 return new SetCondInst(Instruction::SetLT, X, LoBound);
2144 else if (LoOverflow)
2145 return new SetCondInst(Instruction::SetGE, X, HiBound);
2146 else
2147 return InsertRangeTest(X, LoBound, HiBound, false, I);
2148 case Instruction::SetLT:
2149 if (LoOverflow)
2150 return ReplaceInstUsesWith(I, ConstantBool::False);
2151 return new SetCondInst(Instruction::SetLT, X, LoBound);
2152 case Instruction::SetGT:
2153 if (HiOverflow)
2154 return ReplaceInstUsesWith(I, ConstantBool::False);
2155 return new SetCondInst(Instruction::SetGE, X, HiBound);
2156 }
2157 }
2158 }
2159 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00002160 case Instruction::Select:
2161 // If either operand of the select is a constant, we can fold the
2162 // comparison into the select arms, which will cause one to be
2163 // constant folded and the select turned into a bitwise or.
2164 Value *Op1 = 0, *Op2 = 0;
2165 if (LHSI->hasOneUse()) {
Chris Lattner457dd822004-06-09 07:59:58 +00002166 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2be51ae2004-06-09 04:24:29 +00002167 // Fold the known value into the constant operand.
2168 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2169 // Insert a new SetCC of the other select operand.
2170 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner457dd822004-06-09 07:59:58 +00002171 LHSI->getOperand(2), CI,
Chris Lattner2be51ae2004-06-09 04:24:29 +00002172 I.getName()), I);
Chris Lattner457dd822004-06-09 07:59:58 +00002173 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2be51ae2004-06-09 04:24:29 +00002174 // Fold the known value into the constant operand.
2175 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2176 // Insert a new SetCC of the other select operand.
2177 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner457dd822004-06-09 07:59:58 +00002178 LHSI->getOperand(1), CI,
Chris Lattner2be51ae2004-06-09 04:24:29 +00002179 I.getName()), I);
2180 }
Chris Lattner2be51ae2004-06-09 04:24:29 +00002181 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00002182
2183 if (Op1)
2184 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2185 break;
2186 }
2187
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002188 // Simplify seteq and setne instructions...
2189 if (I.getOpcode() == Instruction::SetEQ ||
2190 I.getOpcode() == Instruction::SetNE) {
2191 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2192
Chris Lattner00b1a7e2003-07-23 17:26:36 +00002193 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002194 // operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00002195 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2196 switch (BO->getOpcode()) {
Chris Lattner3571b722004-07-06 07:38:18 +00002197 case Instruction::Rem:
2198 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2199 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2200 BO->hasOneUse() &&
2201 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2202 if (unsigned L2 =
2203 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2204 const Type *UTy = BO->getType()->getUnsignedVersion();
2205 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2206 UTy, "tmp"), I);
2207 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2208 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2209 RHSCst, BO->getName()), I);
2210 return BinaryOperator::create(I.getOpcode(), NewRem,
2211 Constant::getNullValue(UTy));
2212 }
2213 break;
2214
Chris Lattner934754b2003-08-13 05:33:12 +00002215 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00002216 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2217 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00002218 if (BO->hasOneUse())
2219 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2220 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00002221 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00002222 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2223 // efficiently invertible, or if the add has just this one use.
2224 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner15d58b62004-06-27 22:51:36 +00002225
Chris Lattner934754b2003-08-13 05:33:12 +00002226 if (Value *NegVal = dyn_castNegVal(BOp1))
2227 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2228 else if (Value *NegVal = dyn_castNegVal(BOp0))
2229 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00002230 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00002231 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2232 BO->setName("");
2233 InsertNewInstBefore(Neg, I);
2234 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2235 }
2236 }
2237 break;
2238 case Instruction::Xor:
2239 // For the xor case, we can xor two constants together, eliminating
2240 // the explicit xor.
2241 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2242 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002243 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00002244
2245 // FALLTHROUGH
2246 case Instruction::Sub:
2247 // Replace (([sub|xor] A, B) != 0) with (A != B)
2248 if (CI->isNullValue())
2249 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2250 BO->getOperand(1));
2251 break;
2252
2253 case Instruction::Or:
2254 // If bits are being or'd in that are not present in the constant we
2255 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00002256 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00002257 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00002258 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002259 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00002260 }
Chris Lattner934754b2003-08-13 05:33:12 +00002261 break;
2262
2263 case Instruction::And:
2264 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002265 // If bits are being compared against that are and'd out, then the
2266 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00002267 if (!ConstantExpr::getAnd(CI,
2268 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002269 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00002270
Chris Lattner457dd822004-06-09 07:59:58 +00002271 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00002272 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00002273 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2274 Instruction::SetNE, Op0,
2275 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00002276
Chris Lattner934754b2003-08-13 05:33:12 +00002277 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2278 // to be a signed value as appropriate.
2279 if (isSignBit(BOC)) {
2280 Value *X = BO->getOperand(0);
2281 // If 'X' is not signed, insert a cast now...
2282 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00002283 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner83c4ec02004-09-27 19:29:18 +00002284 X = InsertCastBefore(X, DestTy, I);
Chris Lattner934754b2003-08-13 05:33:12 +00002285 }
2286 return new SetCondInst(isSetNE ? Instruction::SetLT :
2287 Instruction::SetGE, X,
2288 Constant::getNullValue(X->getType()));
2289 }
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002290
Chris Lattner83c4ec02004-09-27 19:29:18 +00002291 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002292 if (CI->isNullValue() && isHighOnes(BOC)) {
2293 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00002294 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002295
2296 // If 'X' is signed, insert a cast now.
Chris Lattner83c4ec02004-09-27 19:29:18 +00002297 if (NegX->getType()->isSigned()) {
2298 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2299 X = InsertCastBefore(X, DestTy, I);
2300 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002301 }
2302
2303 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattner83c4ec02004-09-27 19:29:18 +00002304 Instruction::SetLT, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002305 }
2306
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002307 }
Chris Lattner934754b2003-08-13 05:33:12 +00002308 default: break;
2309 }
2310 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002311 } else { // Not a SetEQ/SetNE
2312 // If the LHS is a cast from an integral value of the same size,
2313 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2314 Value *CastOp = Cast->getOperand(0);
2315 const Type *SrcTy = CastOp->getType();
2316 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2317 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2318 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2319 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2320 "Source and destination signednesses should differ!");
2321 if (Cast->getType()->isSigned()) {
2322 // If this is a signed comparison, check for comparisons in the
2323 // vicinity of zero.
2324 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2325 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00002326 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002327 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2328 else if (I.getOpcode() == Instruction::SetGT &&
2329 cast<ConstantSInt>(CI)->getValue() == -1)
2330 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00002331 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002332 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2333 } else {
2334 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2335 if (I.getOpcode() == Instruction::SetLT &&
2336 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2337 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00002338 return BinaryOperator::createSetGT(CastOp,
2339 ConstantSInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002340 else if (I.getOpcode() == Instruction::SetGT &&
2341 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2342 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00002343 return BinaryOperator::createSetLT(CastOp,
2344 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00002345 }
2346 }
2347 }
Chris Lattner40f5d702003-06-04 05:10:11 +00002348 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002349 }
2350
Chris Lattnerde90b762003-11-03 04:25:02 +00002351 // Test to see if the operands of the setcc are casted versions of other
2352 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00002353 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2354 Value *CastOp0 = CI->getOperand(0);
2355 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner0cea42a2004-03-13 23:54:27 +00002356 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattnerde90b762003-11-03 04:25:02 +00002357 (I.getOpcode() == Instruction::SetEQ ||
2358 I.getOpcode() == Instruction::SetNE)) {
2359 // We keep moving the cast from the left operand over to the right
2360 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00002361 Op0 = CastOp0;
Chris Lattnerde90b762003-11-03 04:25:02 +00002362
2363 // If operand #1 is a cast instruction, see if we can eliminate it as
2364 // well.
Chris Lattner68708052003-11-03 05:17:03 +00002365 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2366 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00002367 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00002368 Op1 = CI2->getOperand(0);
Chris Lattnerde90b762003-11-03 04:25:02 +00002369
2370 // If Op1 is a constant, we can fold the cast into the constant.
2371 if (Op1->getType() != Op0->getType())
2372 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2373 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2374 } else {
2375 // Otherwise, cast the RHS right before the setcc
2376 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2377 InsertNewInstBefore(cast<Instruction>(Op1), I);
2378 }
2379 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2380 }
2381
Chris Lattner68708052003-11-03 05:17:03 +00002382 // Handle the special case of: setcc (cast bool to X), <cst>
2383 // This comes up when you have code like
2384 // int X = A < B;
2385 // if (X) ...
2386 // For generality, we handle any zero-extension of any operand comparison
2387 // with a constant.
2388 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2389 const Type *SrcTy = CastOp0->getType();
2390 const Type *DestTy = Op0->getType();
2391 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2392 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2393 // Ok, we have an expansion of operand 0 into a new type. Get the
2394 // constant value, masink off bits which are not set in the RHS. These
2395 // could be set if the destination value is signed.
2396 uint64_t ConstVal = ConstantRHS->getRawValue();
2397 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2398
2399 // If the constant we are comparing it with has high bits set, which
2400 // don't exist in the original value, the values could never be equal,
2401 // because the source would be zero extended.
2402 unsigned SrcBits =
2403 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner1bcc70d2003-11-05 17:31:36 +00002404 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2405 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner68708052003-11-03 05:17:03 +00002406 switch (I.getOpcode()) {
2407 default: assert(0 && "Unknown comparison type!");
2408 case Instruction::SetEQ:
2409 return ReplaceInstUsesWith(I, ConstantBool::False);
2410 case Instruction::SetNE:
2411 return ReplaceInstUsesWith(I, ConstantBool::True);
2412 case Instruction::SetLT:
2413 case Instruction::SetLE:
2414 if (DestTy->isSigned() && HasSignBit)
2415 return ReplaceInstUsesWith(I, ConstantBool::False);
2416 return ReplaceInstUsesWith(I, ConstantBool::True);
2417 case Instruction::SetGT:
2418 case Instruction::SetGE:
2419 if (DestTy->isSigned() && HasSignBit)
2420 return ReplaceInstUsesWith(I, ConstantBool::True);
2421 return ReplaceInstUsesWith(I, ConstantBool::False);
2422 }
2423 }
2424
2425 // Otherwise, we can replace the setcc with a setcc of the smaller
2426 // operand value.
2427 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2428 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2429 }
2430 }
2431 }
Chris Lattner7e708292002-06-25 16:13:24 +00002432 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002433}
2434
2435
2436
Chris Lattnerea340052003-03-10 19:16:08 +00002437Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002438 assert(I.getOperand(1)->getType() == Type::UByteTy);
2439 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00002440 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002441
2442 // shl X, 0 == X and shr X, 0 == X
2443 // shl 0, X == 0 and shr 0, X == 0
2444 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00002445 Op0 == Constant::getNullValue(Op0->getType()))
2446 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002447
Chris Lattnerdf17af12003-08-12 21:53:41 +00002448 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2449 if (!isLeftShift)
2450 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2451 if (CSI->isAllOnesValue())
2452 return ReplaceInstUsesWith(I, CSI);
2453
Chris Lattner2eefe512004-04-09 19:05:30 +00002454 // Try to fold constant and into select arguments.
2455 if (isa<Constant>(Op0))
2456 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2457 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2458 return R;
2459
Chris Lattner3f5b8772002-05-06 16:14:14 +00002460 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002461 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2462 // of a signed value.
2463 //
Chris Lattnerea340052003-03-10 19:16:08 +00002464 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner8adac752004-02-23 20:30:06 +00002465 if (CUI->getValue() >= TypeBits) {
2466 if (!Op0->getType()->isSigned() || isLeftShift)
2467 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2468 else {
2469 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2470 return &I;
2471 }
2472 }
Chris Lattnerf2836082002-09-10 23:04:09 +00002473
Chris Lattnere92d2f42003-08-13 04:18:28 +00002474 // ((X*C1) << C2) == (X * (C1 << C2))
2475 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2476 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2477 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002478 return BinaryOperator::createMul(BO->getOperand(0),
2479 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnere92d2f42003-08-13 04:18:28 +00002480
Chris Lattner2eefe512004-04-09 19:05:30 +00002481 // Try to fold constant and into select arguments.
2482 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2483 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2484 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002485 if (isa<PHINode>(Op0))
2486 if (Instruction *NV = FoldOpIntoPhi(I))
2487 return NV;
Chris Lattnere92d2f42003-08-13 04:18:28 +00002488
Chris Lattnerdf17af12003-08-12 21:53:41 +00002489 // If the operand is an bitwise operator with a constant RHS, and the
2490 // shift is the only use, we can pull it out of the shift.
Chris Lattnerfd059242003-10-15 16:48:29 +00002491 if (Op0->hasOneUse())
Chris Lattnerdf17af12003-08-12 21:53:41 +00002492 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2493 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2494 bool isValid = true; // Valid only for And, Or, Xor
2495 bool highBitSet = false; // Transform if high bit of constant set?
2496
2497 switch (Op0BO->getOpcode()) {
2498 default: isValid = false; break; // Do not perform transform!
2499 case Instruction::Or:
2500 case Instruction::Xor:
2501 highBitSet = false;
2502 break;
2503 case Instruction::And:
2504 highBitSet = true;
2505 break;
2506 }
2507
2508 // If this is a signed shift right, and the high bit is modified
2509 // by the logical operation, do not perform the transformation.
2510 // The highBitSet boolean indicates the value of the high bit of
2511 // the constant which would cause it to be modified for this
2512 // operation.
2513 //
2514 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2515 uint64_t Val = Op0C->getRawValue();
2516 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2517 }
2518
2519 if (isValid) {
Chris Lattner7c4049c2004-01-12 19:35:11 +00002520 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdf17af12003-08-12 21:53:41 +00002521
2522 Instruction *NewShift =
2523 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2524 Op0BO->getName());
2525 Op0BO->setName("");
2526 InsertNewInstBefore(NewShift, I);
2527
2528 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2529 NewRHS);
2530 }
2531 }
2532
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002533 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdf17af12003-08-12 21:53:41 +00002534 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattner943c7132003-07-24 18:38:56 +00002535 if (ConstantUInt *ShiftAmt1C =
2536 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002537 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2538 unsigned ShiftAmt2 = CUI->getValue();
2539
2540 // Check for (A << c1) << c2 and (A >> c1) >> c2
2541 if (I.getOpcode() == Op0SI->getOpcode()) {
2542 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattner8adac752004-02-23 20:30:06 +00002543 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2544 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002545 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2546 ConstantUInt::get(Type::UByteTy, Amt));
2547 }
2548
Chris Lattner943c7132003-07-24 18:38:56 +00002549 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2550 // signed types, we can only support the (A >> c1) << c2 configuration,
2551 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdf17af12003-08-12 21:53:41 +00002552 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002553 // Calculate bitmask for what gets shifted off the edge...
2554 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00002555 if (isLeftShift)
Chris Lattner48595f12004-06-10 02:07:29 +00002556 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdf17af12003-08-12 21:53:41 +00002557 else
Chris Lattner48595f12004-06-10 02:07:29 +00002558 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002559
2560 Instruction *Mask =
Chris Lattner48595f12004-06-10 02:07:29 +00002561 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2562 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002563 InsertNewInstBefore(Mask, I);
2564
2565 // Figure out what flavor of shift we should use...
2566 if (ShiftAmt1 == ShiftAmt2)
2567 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2568 else if (ShiftAmt1 < ShiftAmt2) {
2569 return new ShiftInst(I.getOpcode(), Mask,
2570 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2571 } else {
2572 return new ShiftInst(Op0SI->getOpcode(), Mask,
2573 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2574 }
2575 }
2576 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002577 }
Chris Lattner6eaeb572002-10-08 16:16:40 +00002578
Chris Lattner3f5b8772002-05-06 16:14:14 +00002579 return 0;
2580}
2581
Chris Lattnerbee7e762004-07-20 00:59:32 +00002582enum CastType {
2583 Noop = 0,
2584 Truncate = 1,
2585 Signext = 2,
2586 Zeroext = 3
2587};
2588
2589/// getCastType - In the future, we will split the cast instruction into these
2590/// various types. Until then, we have to do the analysis here.
2591static CastType getCastType(const Type *Src, const Type *Dest) {
2592 assert(Src->isIntegral() && Dest->isIntegral() &&
2593 "Only works on integral types!");
2594 unsigned SrcSize = Src->getPrimitiveSize()*8;
2595 if (Src == Type::BoolTy) SrcSize = 1;
2596 unsigned DestSize = Dest->getPrimitiveSize()*8;
2597 if (Dest == Type::BoolTy) DestSize = 1;
2598
2599 if (SrcSize == DestSize) return Noop;
2600 if (SrcSize > DestSize) return Truncate;
2601 if (Src->isSigned()) return Signext;
2602 return Zeroext;
2603}
2604
Chris Lattner3f5b8772002-05-06 16:14:14 +00002605
Chris Lattnera1be5662002-05-02 17:06:02 +00002606// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2607// instruction.
2608//
Chris Lattner24c8e382003-07-24 17:35:25 +00002609static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner59a20772004-07-20 05:21:00 +00002610 const Type *DstTy, TargetData *TD) {
Chris Lattnera1be5662002-05-02 17:06:02 +00002611
Chris Lattner8fd217c2002-08-02 20:00:25 +00002612 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2613 // are identical and the bits don't get reinterpreted (for example
Chris Lattner5eb91942004-07-21 19:50:44 +00002614 // int->float->int would not be allowed).
Misha Brukmanf117cc92003-05-20 18:45:36 +00002615 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner8fd217c2002-08-02 20:00:25 +00002616 return true;
Chris Lattnera1be5662002-05-02 17:06:02 +00002617
Chris Lattnere8a7e592004-07-21 04:27:24 +00002618 // If we are casting between pointer and integer types, treat pointers as
2619 // integers of the appropriate size for the code below.
2620 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2621 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2622 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner59a20772004-07-20 05:21:00 +00002623
Chris Lattnera1be5662002-05-02 17:06:02 +00002624 // Allow free casting and conversion of sizes as long as the sign doesn't
2625 // change...
Chris Lattner0c4e8862002-09-03 01:08:28 +00002626 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattnerbee7e762004-07-20 00:59:32 +00002627 CastType FirstCast = getCastType(SrcTy, MidTy);
2628 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner8fd217c2002-08-02 20:00:25 +00002629
Chris Lattnerbee7e762004-07-20 00:59:32 +00002630 // Capture the effect of these two casts. If the result is a legal cast,
2631 // the CastType is stored here, otherwise a special code is used.
2632 static const unsigned CastResult[] = {
2633 // First cast is noop
2634 0, 1, 2, 3,
2635 // First cast is a truncate
2636 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2637 // First cast is a sign ext
Chris Lattner5eb91942004-07-21 19:50:44 +00002638 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattnerbee7e762004-07-20 00:59:32 +00002639 // First cast is a zero ext
Chris Lattner5eb91942004-07-21 19:50:44 +00002640 3, 5, 3, 3,
Chris Lattnerbee7e762004-07-20 00:59:32 +00002641 };
2642
2643 unsigned Result = CastResult[FirstCast*4+SecondCast];
2644 switch (Result) {
2645 default: assert(0 && "Illegal table value!");
2646 case 0:
2647 case 1:
2648 case 2:
2649 case 3:
2650 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2651 // truncates, we could eliminate more casts.
2652 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2653 case 4:
2654 return false; // Not possible to eliminate this here.
2655 case 5:
Chris Lattner5eb91942004-07-21 19:50:44 +00002656 // Sign or zero extend followed by truncate is always ok if the result
2657 // is a truncate or noop.
2658 CastType ResultCast = getCastType(SrcTy, DstTy);
2659 if (ResultCast == Noop || ResultCast == Truncate)
2660 return true;
2661 // Otherwise we are still growing the value, we are only safe if the
2662 // result will match the sign/zeroextendness of the result.
2663 return ResultCast == FirstCast;
Chris Lattner3ecce662002-08-15 16:15:25 +00002664 }
Chris Lattner8fd217c2002-08-02 20:00:25 +00002665 }
Chris Lattnera1be5662002-05-02 17:06:02 +00002666 return false;
2667}
2668
Chris Lattner59a20772004-07-20 05:21:00 +00002669static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattner24c8e382003-07-24 17:35:25 +00002670 if (V->getType() == Ty || isa<Constant>(V)) return false;
2671 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner59a20772004-07-20 05:21:00 +00002672 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2673 TD))
Chris Lattner24c8e382003-07-24 17:35:25 +00002674 return false;
2675 return true;
2676}
2677
2678/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2679/// InsertBefore instruction. This is specialized a bit to avoid inserting
2680/// casts that are known to not do anything...
2681///
2682Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2683 Instruction *InsertBefore) {
2684 if (V->getType() == DestTy) return V;
2685 if (Constant *C = dyn_cast<Constant>(V))
2686 return ConstantExpr::getCast(C, DestTy);
2687
2688 CastInst *CI = new CastInst(V, DestTy, V->getName());
2689 InsertNewInstBefore(CI, *InsertBefore);
2690 return CI;
2691}
Chris Lattnera1be5662002-05-02 17:06:02 +00002692
2693// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002694//
Chris Lattner7e708292002-06-25 16:13:24 +00002695Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00002696 Value *Src = CI.getOperand(0);
2697
Chris Lattnera1be5662002-05-02 17:06:02 +00002698 // If the user is casting a value to the same type, eliminate this cast
2699 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00002700 if (CI.getType() == Src->getType())
2701 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00002702
Chris Lattnera1be5662002-05-02 17:06:02 +00002703 // If casting the result of another cast instruction, try to eliminate this
2704 // one!
2705 //
Chris Lattner79d35b32003-06-23 21:59:52 +00002706 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00002707 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner59a20772004-07-20 05:21:00 +00002708 CSrc->getType(), CI.getType(), TD)) {
Chris Lattnera1be5662002-05-02 17:06:02 +00002709 // This instruction now refers directly to the cast's src operand. This
2710 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00002711 CI.setOperand(0, CSrc->getOperand(0));
2712 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00002713 }
2714
Chris Lattner8fd217c2002-08-02 20:00:25 +00002715 // If this is an A->B->A cast, and we are dealing with integral types, try
2716 // to convert this into a logical 'and' instruction.
2717 //
2718 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00002719 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner8fd217c2002-08-02 20:00:25 +00002720 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2721 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2722 assert(CSrc->getType() != Type::ULongTy &&
2723 "Cannot have type bigger than ulong!");
Chris Lattnerbd4ecf72003-05-26 23:41:32 +00002724 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner8fd217c2002-08-02 20:00:25 +00002725 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattner48595f12004-06-10 02:07:29 +00002726 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner8fd217c2002-08-02 20:00:25 +00002727 }
2728 }
2729
Chris Lattnera710ddc2004-05-25 04:29:21 +00002730 // If this is a cast to bool, turn it into the appropriate setne instruction.
2731 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00002732 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00002733 Constant::getNullValue(CI.getOperand(0)->getType()));
2734
Chris Lattner797249b2003-06-21 23:12:02 +00002735 // If casting the result of a getelementptr instruction with no offset, turn
2736 // this into a cast of the original pointer!
2737 //
Chris Lattner79d35b32003-06-23 21:59:52 +00002738 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00002739 bool AllZeroOperands = true;
2740 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2741 if (!isa<Constant>(GEP->getOperand(i)) ||
2742 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2743 AllZeroOperands = false;
2744 break;
2745 }
2746 if (AllZeroOperands) {
2747 CI.setOperand(0, GEP->getOperand(0));
2748 return &CI;
2749 }
2750 }
2751
Chris Lattnerbc61e662003-11-02 05:57:39 +00002752 // If we are casting a malloc or alloca to a pointer to a type of the same
2753 // size, rewrite the allocation instruction to allocate the "right" type.
2754 //
2755 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerfc07a342003-11-02 06:54:48 +00002756 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerbc61e662003-11-02 05:57:39 +00002757 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2758 // Get the type really allocated and the type casted to...
2759 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerbc61e662003-11-02 05:57:39 +00002760 const Type *CastElTy = PTy->getElementType();
Chris Lattnerfae10102004-07-06 19:28:42 +00002761 if (AllocElTy->isSized() && CastElTy->isSized()) {
2762 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2763 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner1bcc70d2003-11-05 17:31:36 +00002764
Chris Lattnerfae10102004-07-06 19:28:42 +00002765 // If the allocation is for an even multiple of the cast type size
2766 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2767 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerbc61e662003-11-02 05:57:39 +00002768 AllocElTySize/CastElTySize);
Chris Lattnerfae10102004-07-06 19:28:42 +00002769 std::string Name = AI->getName(); AI->setName("");
2770 AllocationInst *New;
2771 if (isa<MallocInst>(AI))
2772 New = new MallocInst(CastElTy, Amt, Name);
2773 else
2774 New = new AllocaInst(CastElTy, Amt, Name);
2775 InsertNewInstBefore(New, *AI);
2776 return ReplaceInstUsesWith(CI, New);
2777 }
Chris Lattnerbc61e662003-11-02 05:57:39 +00002778 }
2779 }
2780
Chris Lattner4e998b22004-09-29 05:07:12 +00002781 if (isa<PHINode>(Src))
2782 if (Instruction *NV = FoldOpIntoPhi(CI))
2783 return NV;
2784
Chris Lattner24c8e382003-07-24 17:35:25 +00002785 // If the source value is an instruction with only this use, we can attempt to
2786 // propagate the cast into the instruction. Also, only handle integral types
2787 // for now.
2788 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerfd059242003-10-15 16:48:29 +00002789 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00002790 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2791 const Type *DestTy = CI.getType();
2792 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2793 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2794
2795 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2796 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2797
2798 switch (SrcI->getOpcode()) {
2799 case Instruction::Add:
2800 case Instruction::Mul:
2801 case Instruction::And:
2802 case Instruction::Or:
2803 case Instruction::Xor:
2804 // If we are discarding information, or just changing the sign, rewrite.
2805 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2806 // Don't insert two casts if they cannot be eliminated. We allow two
2807 // casts to be inserted if the sizes are the same. This could only be
2808 // converting signedness, which is a noop.
Chris Lattner59a20772004-07-20 05:21:00 +00002809 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2810 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00002811 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2812 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2813 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2814 ->getOpcode(), Op0c, Op1c);
2815 }
2816 }
2817 break;
2818 case Instruction::Shl:
2819 // Allow changing the sign of the source operand. Do not allow changing
2820 // the size of the shift, UNLESS the shift amount is a constant. We
2821 // mush not change variable sized shifts to a smaller size, because it
2822 // is undefined to shift more bits out than exist in the value.
2823 if (DestBitSize == SrcBitSize ||
2824 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2825 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2826 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2827 }
2828 break;
2829 }
2830 }
2831
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002832 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00002833}
2834
Chris Lattnere576b912004-04-09 23:46:01 +00002835/// GetSelectFoldableOperands - We want to turn code that looks like this:
2836/// %C = or %A, %B
2837/// %D = select %cond, %C, %A
2838/// into:
2839/// %C = select %cond, %B, 0
2840/// %D = or %A, %C
2841///
2842/// Assuming that the specified instruction is an operand to the select, return
2843/// a bitmask indicating which operands of this instruction are foldable if they
2844/// equal the other incoming value of the select.
2845///
2846static unsigned GetSelectFoldableOperands(Instruction *I) {
2847 switch (I->getOpcode()) {
2848 case Instruction::Add:
2849 case Instruction::Mul:
2850 case Instruction::And:
2851 case Instruction::Or:
2852 case Instruction::Xor:
2853 return 3; // Can fold through either operand.
2854 case Instruction::Sub: // Can only fold on the amount subtracted.
2855 case Instruction::Shl: // Can only fold on the shift amount.
2856 case Instruction::Shr:
2857 return 1;
2858 default:
2859 return 0; // Cannot fold
2860 }
2861}
2862
2863/// GetSelectFoldableConstant - For the same transformation as the previous
2864/// function, return the identity constant that goes into the select.
2865static Constant *GetSelectFoldableConstant(Instruction *I) {
2866 switch (I->getOpcode()) {
2867 default: assert(0 && "This cannot happen!"); abort();
2868 case Instruction::Add:
2869 case Instruction::Sub:
2870 case Instruction::Or:
2871 case Instruction::Xor:
2872 return Constant::getNullValue(I->getType());
2873 case Instruction::Shl:
2874 case Instruction::Shr:
2875 return Constant::getNullValue(Type::UByteTy);
2876 case Instruction::And:
2877 return ConstantInt::getAllOnesValue(I->getType());
2878 case Instruction::Mul:
2879 return ConstantInt::get(I->getType(), 1);
2880 }
2881}
2882
Chris Lattner3d69f462004-03-12 05:52:32 +00002883Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002884 Value *CondVal = SI.getCondition();
2885 Value *TrueVal = SI.getTrueValue();
2886 Value *FalseVal = SI.getFalseValue();
2887
2888 // select true, X, Y -> X
2889 // select false, X, Y -> Y
2890 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner3d69f462004-03-12 05:52:32 +00002891 if (C == ConstantBool::True)
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002892 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00002893 else {
2894 assert(C == ConstantBool::False);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002895 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00002896 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002897
2898 // select C, X, X -> X
2899 if (TrueVal == FalseVal)
2900 return ReplaceInstUsesWith(SI, TrueVal);
2901
Chris Lattner0c199a72004-04-08 04:43:23 +00002902 if (SI.getType() == Type::BoolTy)
2903 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2904 if (C == ConstantBool::True) {
2905 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00002906 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00002907 } else {
2908 // Change: A = select B, false, C --> A = and !B, C
2909 Value *NotCond =
2910 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2911 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00002912 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00002913 }
2914 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2915 if (C == ConstantBool::False) {
2916 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00002917 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00002918 } else {
2919 // Change: A = select B, C, true --> A = or !B, C
2920 Value *NotCond =
2921 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2922 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00002923 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00002924 }
2925 }
2926
Chris Lattner2eefe512004-04-09 19:05:30 +00002927 // Selecting between two integer constants?
2928 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2929 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2930 // select C, 1, 0 -> cast C to int
2931 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2932 return new CastInst(CondVal, SI.getType());
2933 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2934 // select C, 0, 1 -> cast !C to int
2935 Value *NotCond =
2936 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00002937 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00002938 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00002939 }
Chris Lattner457dd822004-06-09 07:59:58 +00002940
2941 // If one of the constants is zero (we know they can't both be) and we
2942 // have a setcc instruction with zero, and we have an 'and' with the
2943 // non-constant value, eliminate this whole mess. This corresponds to
2944 // cases like this: ((X & 27) ? 27 : 0)
2945 if (TrueValC->isNullValue() || FalseValC->isNullValue())
2946 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
2947 if ((IC->getOpcode() == Instruction::SetEQ ||
2948 IC->getOpcode() == Instruction::SetNE) &&
2949 isa<ConstantInt>(IC->getOperand(1)) &&
2950 cast<Constant>(IC->getOperand(1))->isNullValue())
2951 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
2952 if (ICA->getOpcode() == Instruction::And &&
2953 isa<ConstantInt>(ICA->getOperand(1)) &&
2954 (ICA->getOperand(1) == TrueValC ||
2955 ICA->getOperand(1) == FalseValC) &&
2956 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
2957 // Okay, now we know that everything is set up, we just don't
2958 // know whether we have a setne or seteq and whether the true or
2959 // false val is the zero.
2960 bool ShouldNotVal = !TrueValC->isNullValue();
2961 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
2962 Value *V = ICA;
2963 if (ShouldNotVal)
2964 V = InsertNewInstBefore(BinaryOperator::create(
2965 Instruction::Xor, V, ICA->getOperand(1)), SI);
2966 return ReplaceInstUsesWith(SI, V);
2967 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002968 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00002969
2970 // See if we are selecting two values based on a comparison of the two values.
2971 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
2972 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
2973 // Transform (X == Y) ? X : Y -> Y
2974 if (SCI->getOpcode() == Instruction::SetEQ)
2975 return ReplaceInstUsesWith(SI, FalseVal);
2976 // Transform (X != Y) ? X : Y -> X
2977 if (SCI->getOpcode() == Instruction::SetNE)
2978 return ReplaceInstUsesWith(SI, TrueVal);
2979 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2980
2981 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
2982 // Transform (X == Y) ? Y : X -> X
2983 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00002984 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00002985 // Transform (X != Y) ? Y : X -> Y
2986 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00002987 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00002988 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2989 }
2990 }
Chris Lattner0c199a72004-04-08 04:43:23 +00002991
Chris Lattnere576b912004-04-09 23:46:01 +00002992 // See if we can fold the select into one of our operands.
2993 if (SI.getType()->isInteger()) {
2994 // See the comment above GetSelectFoldableOperands for a description of the
2995 // transformation we are doing here.
2996 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
2997 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
2998 !isa<Constant>(FalseVal))
2999 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3000 unsigned OpToFold = 0;
3001 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3002 OpToFold = 1;
3003 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3004 OpToFold = 2;
3005 }
3006
3007 if (OpToFold) {
3008 Constant *C = GetSelectFoldableConstant(TVI);
3009 std::string Name = TVI->getName(); TVI->setName("");
3010 Instruction *NewSel =
3011 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3012 Name);
3013 InsertNewInstBefore(NewSel, SI);
3014 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3015 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3016 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3017 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3018 else {
3019 assert(0 && "Unknown instruction!!");
3020 }
3021 }
3022 }
Chris Lattnera96879a2004-09-29 17:40:11 +00003023
Chris Lattnere576b912004-04-09 23:46:01 +00003024 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3025 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3026 !isa<Constant>(TrueVal))
3027 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3028 unsigned OpToFold = 0;
3029 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3030 OpToFold = 1;
3031 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3032 OpToFold = 2;
3033 }
3034
3035 if (OpToFold) {
3036 Constant *C = GetSelectFoldableConstant(FVI);
3037 std::string Name = FVI->getName(); FVI->setName("");
3038 Instruction *NewSel =
3039 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3040 Name);
3041 InsertNewInstBefore(NewSel, SI);
3042 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3043 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3044 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3045 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3046 else {
3047 assert(0 && "Unknown instruction!!");
3048 }
3049 }
3050 }
3051 }
Chris Lattner3d69f462004-03-12 05:52:32 +00003052 return 0;
3053}
3054
3055
Chris Lattner9fe38862003-06-19 17:00:31 +00003056// CallInst simplification
3057//
3058Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003059 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3060 // visitCallSite.
3061 if (Function *F = CI.getCalledFunction())
3062 switch (F->getIntrinsicID()) {
3063 case Intrinsic::memmove:
3064 case Intrinsic::memcpy:
3065 case Intrinsic::memset:
3066 // memmove/cpy/set of zero bytes is a noop.
3067 if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
3068 if (NumBytes->isNullValue())
3069 return EraseInstFromFunction(CI);
3070 }
3071 break;
3072 default:
3073 break;
3074 }
3075
Chris Lattnera44d8a22003-10-07 22:32:43 +00003076 return visitCallSite(&CI);
Chris Lattner9fe38862003-06-19 17:00:31 +00003077}
3078
3079// InvokeInst simplification
3080//
3081Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00003082 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00003083}
3084
Chris Lattnera44d8a22003-10-07 22:32:43 +00003085// visitCallSite - Improvements for call and invoke instructions.
3086//
3087Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00003088 bool Changed = false;
3089
3090 // If the callee is a constexpr cast of a function, attempt to move the cast
3091 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00003092 if (transformConstExprCastCall(CS)) return 0;
3093
Chris Lattner6c266db2003-10-07 22:54:13 +00003094 Value *Callee = CS.getCalledValue();
3095 const PointerType *PTy = cast<PointerType>(Callee->getType());
3096 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3097 if (FTy->isVarArg()) {
3098 // See if we can optimize any arguments passed through the varargs area of
3099 // the call.
3100 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3101 E = CS.arg_end(); I != E; ++I)
3102 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3103 // If this cast does not effect the value passed through the varargs
3104 // area, we can eliminate the use of the cast.
3105 Value *Op = CI->getOperand(0);
3106 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3107 *I = Op;
3108 Changed = true;
3109 }
3110 }
3111 }
Chris Lattnera44d8a22003-10-07 22:32:43 +00003112
Chris Lattner6c266db2003-10-07 22:54:13 +00003113 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00003114}
3115
Chris Lattner9fe38862003-06-19 17:00:31 +00003116// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3117// attempt to move the cast to the arguments of the call/invoke.
3118//
3119bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3120 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3121 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattner9db07b92004-07-18 18:59:44 +00003122 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00003123 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00003124 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00003125 Instruction *Caller = CS.getInstruction();
3126
3127 // Okay, this is a cast from a function to a different type. Unless doing so
3128 // would cause a type conversion of one of our arguments, change this call to
3129 // be a direct call with arguments casted to the appropriate types.
3130 //
3131 const FunctionType *FT = Callee->getFunctionType();
3132 const Type *OldRetTy = Caller->getType();
3133
Chris Lattnerf78616b2004-01-14 06:06:08 +00003134 // Check to see if we are changing the return type...
3135 if (OldRetTy != FT->getReturnType()) {
3136 if (Callee->isExternal() &&
3137 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3138 !Caller->use_empty())
3139 return false; // Cannot transform this return value...
3140
3141 // If the callsite is an invoke instruction, and the return value is used by
3142 // a PHI node in a successor, we cannot change the return type of the call
3143 // because there is no place to put the cast instruction (without breaking
3144 // the critical edge). Bail out in this case.
3145 if (!Caller->use_empty())
3146 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3147 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3148 UI != E; ++UI)
3149 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3150 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00003151 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00003152 return false;
3153 }
Chris Lattner9fe38862003-06-19 17:00:31 +00003154
3155 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3156 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3157
3158 CallSite::arg_iterator AI = CS.arg_begin();
3159 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3160 const Type *ParamTy = FT->getParamType(i);
3161 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3162 if (Callee->isExternal() && !isConvertible) return false;
3163 }
3164
3165 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3166 Callee->isExternal())
3167 return false; // Do not delete arguments unless we have a function body...
3168
3169 // Okay, we decided that this is a safe thing to do: go ahead and start
3170 // inserting cast instructions as necessary...
3171 std::vector<Value*> Args;
3172 Args.reserve(NumActualArgs);
3173
3174 AI = CS.arg_begin();
3175 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3176 const Type *ParamTy = FT->getParamType(i);
3177 if ((*AI)->getType() == ParamTy) {
3178 Args.push_back(*AI);
3179 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00003180 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3181 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00003182 }
3183 }
3184
3185 // If the function takes more arguments than the call was taking, add them
3186 // now...
3187 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3188 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3189
3190 // If we are removing arguments to the function, emit an obnoxious warning...
3191 if (FT->getNumParams() < NumActualArgs)
3192 if (!FT->isVarArg()) {
3193 std::cerr << "WARNING: While resolving call to function '"
3194 << Callee->getName() << "' arguments were dropped!\n";
3195 } else {
3196 // Add all of the arguments in their promoted form to the arg list...
3197 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3198 const Type *PTy = getPromotedType((*AI)->getType());
3199 if (PTy != (*AI)->getType()) {
3200 // Must promote to pass through va_arg area!
3201 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3202 InsertNewInstBefore(Cast, *Caller);
3203 Args.push_back(Cast);
3204 } else {
3205 Args.push_back(*AI);
3206 }
3207 }
3208 }
3209
3210 if (FT->getReturnType() == Type::VoidTy)
3211 Caller->setName(""); // Void type should not have a name...
3212
3213 Instruction *NC;
3214 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00003215 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00003216 Args, Caller->getName(), Caller);
3217 } else {
3218 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3219 }
3220
3221 // Insert a cast of the return type as necessary...
3222 Value *NV = NC;
3223 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3224 if (NV->getType() != Type::VoidTy) {
3225 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00003226
3227 // If this is an invoke instruction, we should insert it after the first
3228 // non-phi, instruction in the normal successor block.
3229 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3230 BasicBlock::iterator I = II->getNormalDest()->begin();
3231 while (isa<PHINode>(I)) ++I;
3232 InsertNewInstBefore(NC, *I);
3233 } else {
3234 // Otherwise, it's a call, just insert cast right after the call instr
3235 InsertNewInstBefore(NC, *Caller);
3236 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003237 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00003238 } else {
3239 NV = Constant::getNullValue(Caller->getType());
3240 }
3241 }
3242
3243 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3244 Caller->replaceAllUsesWith(NV);
3245 Caller->getParent()->getInstList().erase(Caller);
3246 removeFromWorkList(Caller);
3247 return true;
3248}
3249
3250
Chris Lattnera1be5662002-05-02 17:06:02 +00003251
Chris Lattner473945d2002-05-06 18:06:38 +00003252// PHINode simplification
3253//
Chris Lattner7e708292002-06-25 16:13:24 +00003254Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner60921c92003-12-19 05:58:40 +00003255 if (Value *V = hasConstantValue(&PN))
3256 return ReplaceInstUsesWith(PN, V);
Chris Lattner7059f2e2004-02-16 05:07:08 +00003257
3258 // If the only user of this instruction is a cast instruction, and all of the
3259 // incoming values are constants, change this PHI to merge together the casted
3260 // constants.
3261 if (PN.hasOneUse())
3262 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3263 if (CI->getType() != PN.getType()) { // noop casts will be folded
3264 bool AllConstant = true;
3265 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3266 if (!isa<Constant>(PN.getIncomingValue(i))) {
3267 AllConstant = false;
3268 break;
3269 }
3270 if (AllConstant) {
3271 // Make a new PHI with all casted values.
3272 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3273 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3274 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3275 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3276 PN.getIncomingBlock(i));
3277 }
3278
3279 // Update the cast instruction.
3280 CI->setOperand(0, New);
3281 WorkList.push_back(CI); // revisit the cast instruction to fold.
3282 WorkList.push_back(New); // Make sure to revisit the new Phi
3283 return &PN; // PN is now dead!
3284 }
3285 }
Chris Lattner60921c92003-12-19 05:58:40 +00003286 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00003287}
3288
Chris Lattner28977af2004-04-05 01:30:19 +00003289static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3290 Instruction *InsertPoint,
3291 InstCombiner *IC) {
3292 unsigned PS = IC->getTargetData().getPointerSize();
3293 const Type *VTy = V->getType();
3294 Instruction *Cast;
3295 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3296 // We must insert a cast to ensure we sign-extend.
3297 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3298 V->getName()), *InsertPoint);
3299 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3300 *InsertPoint);
3301}
3302
Chris Lattnera1be5662002-05-02 17:06:02 +00003303
Chris Lattner7e708292002-06-25 16:13:24 +00003304Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00003305 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00003306 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00003307 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00003308 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00003309 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00003310
3311 bool HasZeroPointerIndex = false;
3312 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3313 HasZeroPointerIndex = C->isNullValue();
3314
3315 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00003316 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00003317
Chris Lattner28977af2004-04-05 01:30:19 +00003318 // Eliminate unneeded casts for indices.
3319 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00003320 gep_type_iterator GTI = gep_type_begin(GEP);
3321 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3322 if (isa<SequentialType>(*GTI)) {
3323 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3324 Value *Src = CI->getOperand(0);
3325 const Type *SrcTy = Src->getType();
3326 const Type *DestTy = CI->getType();
3327 if (Src->getType()->isInteger()) {
3328 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3329 // We can always eliminate a cast from ulong or long to the other.
3330 // We can always eliminate a cast from uint to int or the other on
3331 // 32-bit pointer platforms.
3332 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3333 MadeChange = true;
3334 GEP.setOperand(i, Src);
3335 }
3336 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3337 SrcTy->getPrimitiveSize() == 4) {
3338 // We can always eliminate a cast from int to [u]long. We can
3339 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3340 // pointer target.
3341 if (SrcTy->isSigned() ||
3342 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3343 MadeChange = true;
3344 GEP.setOperand(i, Src);
3345 }
Chris Lattner28977af2004-04-05 01:30:19 +00003346 }
3347 }
3348 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00003349 // If we are using a wider index than needed for this platform, shrink it
3350 // to what we need. If the incoming value needs a cast instruction,
3351 // insert it. This explicit cast can make subsequent optimizations more
3352 // obvious.
3353 Value *Op = GEP.getOperand(i);
3354 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00003355 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00003356 GEP.setOperand(i, ConstantExpr::getCast(C,
3357 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00003358 MadeChange = true;
3359 } else {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00003360 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3361 Op->getName()), GEP);
3362 GEP.setOperand(i, Op);
3363 MadeChange = true;
3364 }
Chris Lattner67769e52004-07-20 01:48:15 +00003365
3366 // If this is a constant idx, make sure to canonicalize it to be a signed
3367 // operand, otherwise CSE and other optimizations are pessimized.
3368 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3369 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3370 CUI->getType()->getSignedVersion()));
3371 MadeChange = true;
3372 }
Chris Lattner28977af2004-04-05 01:30:19 +00003373 }
3374 if (MadeChange) return &GEP;
3375
Chris Lattner90ac28c2002-08-02 19:29:35 +00003376 // Combine Indices - If the source pointer to this getelementptr instruction
3377 // is a getelementptr instruction, combine the indices of the two
3378 // getelementptr instructions into a single instruction.
3379 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00003380 std::vector<Value*> SrcGEPOperands;
Chris Lattner620ce142004-05-07 22:09:22 +00003381 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattnerebd985c2004-03-25 22:59:29 +00003382 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner620ce142004-05-07 22:09:22 +00003383 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattnerebd985c2004-03-25 22:59:29 +00003384 if (CE->getOpcode() == Instruction::GetElementPtr)
3385 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3386 }
3387
3388 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00003389 // Note that if our source is a gep chain itself that we wait for that
3390 // chain to be resolved before we perform this transformation. This
3391 // avoids us creating a TON of code in some cases.
3392 //
3393 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3394 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3395 return 0; // Wait until our source is folded to completion.
3396
Chris Lattner90ac28c2002-08-02 19:29:35 +00003397 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00003398
3399 // Find out whether the last index in the source GEP is a sequential idx.
3400 bool EndsWithSequential = false;
3401 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3402 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00003403 EndsWithSequential = !isa<StructType>(*I);
Chris Lattner8a2a3112001-12-14 16:52:21 +00003404
Chris Lattner90ac28c2002-08-02 19:29:35 +00003405 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00003406 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00003407 // Replace: gep (gep %P, long B), long A, ...
3408 // With: T = long A+B; gep %P, T, ...
3409 //
Chris Lattner620ce142004-05-07 22:09:22 +00003410 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00003411 if (SO1 == Constant::getNullValue(SO1->getType())) {
3412 Sum = GO1;
3413 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3414 Sum = SO1;
3415 } else {
3416 // If they aren't the same type, convert both to an integer of the
3417 // target's pointer size.
3418 if (SO1->getType() != GO1->getType()) {
3419 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3420 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3421 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3422 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3423 } else {
3424 unsigned PS = TD->getPointerSize();
3425 Instruction *Cast;
3426 if (SO1->getType()->getPrimitiveSize() == PS) {
3427 // Convert GO1 to SO1's type.
3428 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3429
3430 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3431 // Convert SO1 to GO1's type.
3432 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3433 } else {
3434 const Type *PT = TD->getIntPtrType();
3435 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3436 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3437 }
3438 }
3439 }
Chris Lattner620ce142004-05-07 22:09:22 +00003440 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3441 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3442 else {
Chris Lattner48595f12004-06-10 02:07:29 +00003443 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3444 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00003445 }
Chris Lattner28977af2004-04-05 01:30:19 +00003446 }
Chris Lattner620ce142004-05-07 22:09:22 +00003447
3448 // Recycle the GEP we already have if possible.
3449 if (SrcGEPOperands.size() == 2) {
3450 GEP.setOperand(0, SrcGEPOperands[0]);
3451 GEP.setOperand(1, Sum);
3452 return &GEP;
3453 } else {
3454 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3455 SrcGEPOperands.end()-1);
3456 Indices.push_back(Sum);
3457 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3458 }
Chris Lattner28977af2004-04-05 01:30:19 +00003459 } else if (isa<Constant>(*GEP.idx_begin()) &&
3460 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerebd985c2004-03-25 22:59:29 +00003461 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00003462 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00003463 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3464 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00003465 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3466 }
3467
3468 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00003469 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00003470
Chris Lattner620ce142004-05-07 22:09:22 +00003471 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00003472 // GEP of global variable. If all of the indices for this GEP are
3473 // constants, we can promote this to a constexpr instead of an instruction.
3474
3475 // Scan for nonconstants...
3476 std::vector<Constant*> Indices;
3477 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3478 for (; I != E && isa<Constant>(*I); ++I)
3479 Indices.push_back(cast<Constant>(*I));
3480
3481 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00003482 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00003483
3484 // Replace all uses of the GEP with the new constexpr...
3485 return ReplaceInstUsesWith(GEP, CE);
3486 }
Chris Lattner620ce142004-05-07 22:09:22 +00003487 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattnerc6bd1952004-02-22 05:25:17 +00003488 if (CE->getOpcode() == Instruction::Cast) {
3489 if (HasZeroPointerIndex) {
3490 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3491 // into : GEP [10 x ubyte]* X, long 0, ...
3492 //
3493 // This occurs when the program declares an array extern like "int X[];"
3494 //
3495 Constant *X = CE->getOperand(0);
3496 const PointerType *CPTy = cast<PointerType>(CE->getType());
3497 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3498 if (const ArrayType *XATy =
3499 dyn_cast<ArrayType>(XTy->getElementType()))
3500 if (const ArrayType *CATy =
3501 dyn_cast<ArrayType>(CPTy->getElementType()))
3502 if (CATy->getElementType() == XATy->getElementType()) {
3503 // At this point, we know that the cast source type is a pointer
3504 // to an array of the same type as the destination pointer
3505 // array. Because the array type is never stepped over (there
3506 // is a leading zero) we can fold the cast into this GEP.
3507 GEP.setOperand(0, X);
3508 return &GEP;
3509 }
3510 }
3511 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00003512 }
3513
Chris Lattner8a2a3112001-12-14 16:52:21 +00003514 return 0;
3515}
3516
Chris Lattner0864acf2002-11-04 16:18:53 +00003517Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3518 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3519 if (AI.isArrayAllocation()) // Check C != 1
3520 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3521 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00003522 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00003523
3524 // Create and insert the replacement instruction...
3525 if (isa<MallocInst>(AI))
Chris Lattner7c881df2004-03-19 06:08:10 +00003526 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00003527 else {
3528 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner7c881df2004-03-19 06:08:10 +00003529 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00003530 }
Chris Lattner7c881df2004-03-19 06:08:10 +00003531
3532 InsertNewInstBefore(New, AI);
Chris Lattner0864acf2002-11-04 16:18:53 +00003533
3534 // Scan to the end of the allocation instructions, to skip over a block of
3535 // allocas if possible...
3536 //
3537 BasicBlock::iterator It = New;
3538 while (isa<AllocationInst>(*It)) ++It;
3539
3540 // Now that I is pointing to the first non-allocation-inst in the block,
3541 // insert our getelementptr instruction...
3542 //
Chris Lattner28977af2004-04-05 01:30:19 +00003543 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner0864acf2002-11-04 16:18:53 +00003544 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3545
3546 // Now make everything use the getelementptr instead of the original
3547 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00003548 return ReplaceInstUsesWith(AI, V);
Chris Lattner0864acf2002-11-04 16:18:53 +00003549 }
Chris Lattner7c881df2004-03-19 06:08:10 +00003550
3551 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3552 // Note that we only do this for alloca's, because malloc should allocate and
3553 // return a unique pointer, even for a zero byte allocation.
Chris Lattnercf27afb2004-07-02 22:55:47 +00003554 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3555 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00003556 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3557
Chris Lattner0864acf2002-11-04 16:18:53 +00003558 return 0;
3559}
3560
Chris Lattner67b1e1b2003-12-07 01:24:23 +00003561Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3562 Value *Op = FI.getOperand(0);
3563
3564 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3565 if (CastInst *CI = dyn_cast<CastInst>(Op))
3566 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3567 FI.setOperand(0, CI->getOperand(0));
3568 return &FI;
3569 }
3570
Chris Lattner6160e852004-02-28 04:57:37 +00003571 // If we have 'free null' delete the instruction. This can happen in stl code
3572 // when lots of inlining happens.
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003573 if (isa<ConstantPointerNull>(Op))
3574 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00003575
Chris Lattner67b1e1b2003-12-07 01:24:23 +00003576 return 0;
3577}
3578
3579
Chris Lattner833b8a42003-06-26 05:06:25 +00003580/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3581/// constantexpr, return the constant value being addressed by the constant
3582/// expression, or null if something is funny.
3583///
3584static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner28977af2004-04-05 01:30:19 +00003585 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner833b8a42003-06-26 05:06:25 +00003586 return 0; // Do not allow stepping over the value!
3587
3588 // Loop over all of the operands, tracking down which value we are
3589 // addressing...
Chris Lattnere1368ae2004-05-27 17:30:27 +00003590 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3591 for (++I; I != E; ++I)
3592 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3593 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3594 assert(CU->getValue() < STy->getNumElements() &&
3595 "Struct index out of range!");
3596 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +00003597 C = CS->getOperand(CU->getValue());
Chris Lattnere1368ae2004-05-27 17:30:27 +00003598 } else if (isa<ConstantAggregateZero>(C)) {
3599 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
3600 } else {
3601 return 0;
3602 }
3603 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3604 const ArrayType *ATy = cast<ArrayType>(*I);
3605 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3606 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +00003607 C = CA->getOperand(CI->getRawValue());
Chris Lattnere1368ae2004-05-27 17:30:27 +00003608 else if (isa<ConstantAggregateZero>(C))
3609 C = Constant::getNullValue(ATy->getElementType());
3610 else
3611 return 0;
3612 } else {
Chris Lattner833b8a42003-06-26 05:06:25 +00003613 return 0;
Chris Lattnere1368ae2004-05-27 17:30:27 +00003614 }
Chris Lattner833b8a42003-06-26 05:06:25 +00003615 return C;
3616}
3617
Chris Lattnerb89e0712004-07-13 01:49:43 +00003618static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3619 User *CI = cast<User>(LI.getOperand(0));
3620
3621 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3622 if (const PointerType *SrcTy =
3623 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3624 const Type *SrcPTy = SrcTy->getElementType();
3625 if (SrcPTy->isSized() && DestPTy->isSized() &&
3626 IC.getTargetData().getTypeSize(SrcPTy) ==
3627 IC.getTargetData().getTypeSize(DestPTy) &&
3628 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3629 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3630 // Okay, we are casting from one integer or pointer type to another of
3631 // the same size. Instead of casting the pointer before the load, cast
3632 // the result of the loaded value.
3633 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerc10aced2004-09-19 18:43:46 +00003634 CI->getName(),
3635 LI.isVolatile()),LI);
Chris Lattnerb89e0712004-07-13 01:49:43 +00003636 // Now cast the result of the load.
3637 return new CastInst(NewLoad, LI.getType());
3638 }
3639 }
3640 return 0;
3641}
3642
Chris Lattnerc10aced2004-09-19 18:43:46 +00003643/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00003644/// from this value cannot trap. If it is not obviously safe to load from the
3645/// specified pointer, we do a quick local scan of the basic block containing
3646/// ScanFrom, to determine if the address is already accessed.
3647static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3648 // If it is an alloca or global variable, it is always safe to load from.
3649 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3650
3651 // Otherwise, be a little bit agressive by scanning the local block where we
3652 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00003653 // from/to. If so, the previous load or store would have already trapped,
3654 // so there is no harm doing an extra load (also, CSE will later eliminate
3655 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00003656 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3657
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00003658 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00003659 --BBI;
3660
3661 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3662 if (LI->getOperand(0) == V) return true;
3663 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3664 if (SI->getOperand(1) == V) return true;
3665
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00003666 }
Chris Lattner8a375202004-09-19 19:18:10 +00003667 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00003668}
3669
Chris Lattner833b8a42003-06-26 05:06:25 +00003670Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3671 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00003672
Chris Lattnerd9955aa2004-04-14 03:28:36 +00003673 if (Constant *C = dyn_cast<Constant>(Op))
Chris Lattnerc10aced2004-09-19 18:43:46 +00003674 if (C->isNullValue() && !LI.isVolatile()) // load null -> 0
Chris Lattnerd9955aa2004-04-14 03:28:36 +00003675 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner833b8a42003-06-26 05:06:25 +00003676
3677 // Instcombine load (constant global) into the value loaded...
3678 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00003679 if (GV->isConstant() && !GV->isExternal())
Chris Lattner833b8a42003-06-26 05:06:25 +00003680 return ReplaceInstUsesWith(LI, GV->getInitializer());
3681
3682 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
3683 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
Chris Lattnerb89e0712004-07-13 01:49:43 +00003684 if (CE->getOpcode() == Instruction::GetElementPtr) {
Reid Spencer8863f182004-07-18 00:38:32 +00003685 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3686 if (GV->isConstant() && !GV->isExternal())
3687 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3688 return ReplaceInstUsesWith(LI, V);
Chris Lattnerb89e0712004-07-13 01:49:43 +00003689 } else if (CE->getOpcode() == Instruction::Cast) {
3690 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3691 return Res;
3692 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00003693
3694 // load (cast X) --> cast (load X) iff safe
Chris Lattnerb89e0712004-07-13 01:49:43 +00003695 if (CastInst *CI = dyn_cast<CastInst>(Op))
3696 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3697 return Res;
Chris Lattnerf499eac2004-04-08 20:39:49 +00003698
Chris Lattnerc10aced2004-09-19 18:43:46 +00003699 if (!LI.isVolatile() && Op->hasOneUse()) {
3700 // Change select and PHI nodes to select values instead of addresses: this
3701 // helps alias analysis out a lot, allows many others simplifications, and
3702 // exposes redundancy in the code.
3703 //
3704 // Note that we cannot do the transformation unless we know that the
3705 // introduced loads cannot trap! Something like this is valid as long as
3706 // the condition is always false: load (select bool %C, int* null, int* %G),
3707 // but it would not be valid if we transformed it to load from null
3708 // unconditionally.
3709 //
3710 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3711 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00003712 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3713 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00003714 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003715 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00003716 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003717 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00003718 return new SelectInst(SI->getCondition(), V1, V2);
3719 }
3720
Chris Lattner684fe212004-09-23 15:46:00 +00003721 // load (select (cond, null, P)) -> load P
3722 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3723 if (C->isNullValue()) {
3724 LI.setOperand(0, SI->getOperand(2));
3725 return &LI;
3726 }
3727
3728 // load (select (cond, P, null)) -> load P
3729 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3730 if (C->isNullValue()) {
3731 LI.setOperand(0, SI->getOperand(1));
3732 return &LI;
3733 }
3734
Chris Lattnerc10aced2004-09-19 18:43:46 +00003735 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3736 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003737 bool Safe = PN->getParent() == LI.getParent();
3738
3739 // Scan all of the instructions between the PHI and the load to make
3740 // sure there are no instructions that might possibly alter the value
3741 // loaded from the PHI.
3742 if (Safe) {
3743 BasicBlock::iterator I = &LI;
3744 for (--I; !isa<PHINode>(I); --I)
3745 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3746 Safe = false;
3747 break;
3748 }
3749 }
3750
3751 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattner8a375202004-09-19 19:18:10 +00003752 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003753 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerc10aced2004-09-19 18:43:46 +00003754 Safe = false;
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003755
Chris Lattnerc10aced2004-09-19 18:43:46 +00003756 if (Safe) {
3757 // Create the PHI.
3758 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3759 InsertNewInstBefore(NewPN, *PN);
3760 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3761
3762 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3763 BasicBlock *BB = PN->getIncomingBlock(i);
3764 Value *&TheLoad = LoadMap[BB];
3765 if (TheLoad == 0) {
3766 Value *InVal = PN->getIncomingValue(i);
3767 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3768 InVal->getName()+".val"),
3769 *BB->getTerminator());
3770 }
3771 NewPN->addIncoming(TheLoad, BB);
3772 }
3773 return ReplaceInstUsesWith(LI, NewPN);
3774 }
3775 }
3776 }
Chris Lattner833b8a42003-06-26 05:06:25 +00003777 return 0;
3778}
3779
3780
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00003781Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3782 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003783 Value *X;
3784 BasicBlock *TrueDest;
3785 BasicBlock *FalseDest;
3786 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3787 !isa<Constant>(X)) {
3788 // Swap Destinations and condition...
3789 BI.setCondition(X);
3790 BI.setSuccessor(0, FalseDest);
3791 BI.setSuccessor(1, TrueDest);
3792 return &BI;
3793 }
3794
3795 // Cannonicalize setne -> seteq
3796 Instruction::BinaryOps Op; Value *Y;
3797 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3798 TrueDest, FalseDest)))
3799 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3800 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3801 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3802 std::string Name = I->getName(); I->setName("");
3803 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3804 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00003805 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003806 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00003807 BI.setSuccessor(0, FalseDest);
3808 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003809 removeFromWorkList(I);
3810 I->getParent()->getInstList().erase(I);
3811 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00003812 return &BI;
3813 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003814
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00003815 return 0;
3816}
Chris Lattner0864acf2002-11-04 16:18:53 +00003817
Chris Lattner46238a62004-07-03 00:26:11 +00003818Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3819 Value *Cond = SI.getCondition();
3820 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3821 if (I->getOpcode() == Instruction::Add)
3822 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3823 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3824 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
3825 SI.setOperand(i, ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
3826 AddRHS));
3827 SI.setOperand(0, I->getOperand(0));
3828 WorkList.push_back(I);
3829 return &SI;
3830 }
3831 }
3832 return 0;
3833}
3834
Chris Lattner8a2a3112001-12-14 16:52:21 +00003835
Chris Lattner62b14df2002-09-02 04:59:56 +00003836void InstCombiner::removeFromWorkList(Instruction *I) {
3837 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3838 WorkList.end());
3839}
3840
Chris Lattner7e708292002-06-25 16:13:24 +00003841bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003842 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00003843 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00003844
Chris Lattner216d4d82004-05-01 23:19:52 +00003845 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3846 WorkList.push_back(&*i);
Chris Lattner6ffe5512004-04-27 15:13:33 +00003847
Chris Lattner8a2a3112001-12-14 16:52:21 +00003848
3849 while (!WorkList.empty()) {
3850 Instruction *I = WorkList.back(); // Get an instruction from the worklist
3851 WorkList.pop_back();
3852
Misha Brukmana3bbcb52002-10-29 23:06:16 +00003853 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner62b14df2002-09-02 04:59:56 +00003854 // Check to see if we can DIE the instruction...
3855 if (isInstructionTriviallyDead(I)) {
3856 // Add operands to the worklist...
Chris Lattner4bb7c022003-10-06 17:11:01 +00003857 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003858 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00003859 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00003860
3861 I->getParent()->getInstList().erase(I);
3862 removeFromWorkList(I);
3863 continue;
3864 }
Chris Lattner62b14df2002-09-02 04:59:56 +00003865
Misha Brukmana3bbcb52002-10-29 23:06:16 +00003866 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner62b14df2002-09-02 04:59:56 +00003867 if (Constant *C = ConstantFoldInstruction(I)) {
3868 // Add operands to the worklist...
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003869 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00003870 ReplaceInstUsesWith(*I, C);
3871
Chris Lattner62b14df2002-09-02 04:59:56 +00003872 ++NumConstProp;
Chris Lattner4bb7c022003-10-06 17:11:01 +00003873 I->getParent()->getInstList().erase(I);
Chris Lattner60610002003-10-07 15:17:02 +00003874 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003875 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00003876 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00003877
Chris Lattner8a2a3112001-12-14 16:52:21 +00003878 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00003879 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00003880 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003881 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00003882 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00003883 DEBUG(std::cerr << "IC: Old = " << *I
3884 << " New = " << *Result);
3885
Chris Lattnerf523d062004-06-09 05:08:07 +00003886 // Everything uses the new instruction now.
3887 I->replaceAllUsesWith(Result);
3888
3889 // Push the new instruction and any users onto the worklist.
3890 WorkList.push_back(Result);
3891 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003892
3893 // Move the name to the new instruction first...
3894 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00003895 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003896
3897 // Insert the new instruction into the basic block...
3898 BasicBlock *InstParent = I->getParent();
3899 InstParent->getInstList().insert(I, Result);
3900
Chris Lattner00d51312004-05-01 23:27:23 +00003901 // Make sure that we reprocess all operands now that we reduced their
3902 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00003903 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3904 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3905 WorkList.push_back(OpI);
3906
Chris Lattnerf523d062004-06-09 05:08:07 +00003907 // Instructions can end up on the worklist more than once. Make sure
3908 // we do not process an instruction that has been deleted.
3909 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003910
3911 // Erase the old instruction.
3912 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003913 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00003914 DEBUG(std::cerr << "IC: MOD = " << *I);
3915
Chris Lattner90ac28c2002-08-02 19:29:35 +00003916 // If the instruction was modified, it's possible that it is now dead.
3917 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00003918 if (isInstructionTriviallyDead(I)) {
3919 // Make sure we process all operands now that we are reducing their
3920 // use counts.
3921 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3922 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3923 WorkList.push_back(OpI);
3924
3925 // Instructions may end up in the worklist more than once. Erase all
3926 // occurrances of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00003927 removeFromWorkList(I);
Chris Lattner00d51312004-05-01 23:27:23 +00003928 I->getParent()->getInstList().erase(I);
Chris Lattnerf523d062004-06-09 05:08:07 +00003929 } else {
3930 WorkList.push_back(Result);
3931 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00003932 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00003933 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003934 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00003935 }
3936 }
3937
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003938 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00003939}
3940
Brian Gaeke96d4bf72004-07-27 17:43:21 +00003941FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003942 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00003943}
Brian Gaeked0fde302003-11-11 22:41:34 +00003944