blob: fad2730d84c370f696878c4e1e5f821d9cd9eb45 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000032// N. This list is incomplete
33//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner471bd762003-05-22 19:07:21 +000038#include "llvm/Instructions.h"
Chris Lattner51ea1272004-02-28 05:22:00 +000039#include "llvm/Intrinsics.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner34428442003-05-27 16:40:51 +000041#include "llvm/Constants.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000042#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000043#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
48#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner60a65912002-02-12 21:07:25 +000049#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattner7d2a5392004-03-13 23:54:27 +000051#include "Support/Debug.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000052#include "Support/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000053#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000054using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000055
Chris Lattner260ab202002-04-18 17:39:14 +000056namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000057 Statistic<> NumCombined ("instcombine", "Number of insts combined");
58 Statistic<> NumConstProp("instcombine", "Number of constant folds");
59 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
60
Chris Lattnerc8e66542002-04-27 06:56:12 +000061 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000062 public InstVisitor<InstCombiner, Instruction*> {
63 // Worklist of all of the instructions that need to be simplified.
64 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000065 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000066
Chris Lattner51ea1272004-02-28 05:22:00 +000067 /// AddUsersToWorkList - When an instruction is simplified, add all users of
68 /// the instruction to the work lists because they might get more simplified
69 /// now.
70 ///
71 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000072 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000073 UI != UE; ++UI)
74 WorkList.push_back(cast<Instruction>(*UI));
75 }
76
Chris Lattner51ea1272004-02-28 05:22:00 +000077 /// AddUsesToWorkList - When an instruction is simplified, add operands to
78 /// the work lists because they might get more simplified now.
79 ///
80 void AddUsesToWorkList(Instruction &I) {
81 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
82 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
83 WorkList.push_back(Op);
84 }
85
Chris Lattner99f48c62002-09-02 04:59:56 +000086 // removeFromWorkList - remove all instances of I from the worklist.
87 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000088 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000089 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000090
Chris Lattnerf12cc842002-04-28 21:27:06 +000091 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000092 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000093 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000094 }
95
Chris Lattner69193f92004-04-05 01:30:19 +000096 TargetData &getTargetData() const { return *TD; }
97
Chris Lattner260ab202002-04-18 17:39:14 +000098 // Visitation implementation - Implement instruction combining for different
99 // instruction types. The semantics are as follows:
100 // Return Value:
101 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000102 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000103 // otherwise - Change was made, replace I with returned instruction
104 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000105 Instruction *visitAdd(BinaryOperator &I);
106 Instruction *visitSub(BinaryOperator &I);
107 Instruction *visitMul(BinaryOperator &I);
108 Instruction *visitDiv(BinaryOperator &I);
109 Instruction *visitRem(BinaryOperator &I);
110 Instruction *visitAnd(BinaryOperator &I);
111 Instruction *visitOr (BinaryOperator &I);
112 Instruction *visitXor(BinaryOperator &I);
113 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000114 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000115 Instruction *visitCastInst(CastInst &CI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000116 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000117 Instruction *visitCallInst(CallInst &CI);
118 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000119 Instruction *visitPHINode(PHINode &PN);
120 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000121 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000122 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000123 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000124 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000125 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000126
127 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000128 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000129
Chris Lattner970c33a2003-06-19 17:00:31 +0000130 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000131 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000132 bool transformConstExprCastCall(CallSite CS);
133
Chris Lattner69193f92004-04-05 01:30:19 +0000134 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000135 // InsertNewInstBefore - insert an instruction New before instruction Old
136 // in the program. Add the new instruction to the worklist.
137 //
Chris Lattnere79e8542004-02-23 06:38:22 +0000138 Value *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000139 assert(New && New->getParent() == 0 &&
140 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000141 BasicBlock *BB = Old.getParent();
142 BB->getInstList().insert(&Old, New); // Insert inst
143 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000144 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000145 }
146
147 // ReplaceInstUsesWith - This method is to be used when an instruction is
148 // found to be dead, replacable with another preexisting expression. Here
149 // we add all uses of I to the worklist, replace all uses of I with the new
150 // value, then return I, so that the inst combiner will know that I was
151 // modified.
152 //
153 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000154 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000155 if (&I != V) {
156 I.replaceAllUsesWith(V);
157 return &I;
158 } else {
159 // If we are replacing the instruction with itself, this must be in a
160 // segment of unreachable code, so just clobber the instruction.
161 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
162 return &I;
163 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000164 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000165
166 // EraseInstFromFunction - When dealing with an instruction that has side
167 // effects or produces a void value, we can't rely on DCE to delete the
168 // instruction. Instead, visit methods should return the value returned by
169 // this function.
170 Instruction *EraseInstFromFunction(Instruction &I) {
171 assert(I.use_empty() && "Cannot erase instruction that is used!");
172 AddUsesToWorkList(I);
173 removeFromWorkList(&I);
174 I.getParent()->getInstList().erase(&I);
175 return 0; // Don't do anything with FI
176 }
177
178
Chris Lattner3ac7c262003-08-13 20:16:26 +0000179 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000180 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
181 /// InsertBefore instruction. This is specialized a bit to avoid inserting
182 /// casts that are known to not do anything...
183 ///
184 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
185 Instruction *InsertBefore);
186
Chris Lattner7fb29e12003-03-11 00:12:48 +0000187 // SimplifyCommutative - This performs a few simplifications for commutative
188 // operators...
189 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000190
191 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
192 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner260ab202002-04-18 17:39:14 +0000193 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000194
Chris Lattnerc8b70922002-07-26 21:12:46 +0000195 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000196}
197
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000198// getComplexity: Assign a complexity or rank value to LLVM Values...
199// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
200static unsigned getComplexity(Value *V) {
201 if (isa<Instruction>(V)) {
202 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
203 return 2;
204 return 3;
205 }
206 if (isa<Argument>(V)) return 2;
207 return isa<Constant>(V) ? 0 : 1;
208}
Chris Lattner260ab202002-04-18 17:39:14 +0000209
Chris Lattner7fb29e12003-03-11 00:12:48 +0000210// isOnlyUse - Return true if this instruction will be deleted if we stop using
211// it.
212static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000213 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000214}
215
Chris Lattnere79e8542004-02-23 06:38:22 +0000216// getPromotedType - Return the specified type promoted as it would be to pass
217// though a va_arg area...
218static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000219 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000220 case Type::SByteTyID:
221 case Type::ShortTyID: return Type::IntTy;
222 case Type::UByteTyID:
223 case Type::UShortTyID: return Type::UIntTy;
224 case Type::FloatTyID: return Type::DoubleTy;
225 default: return Ty;
226 }
227}
228
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000229// SimplifyCommutative - This performs a few simplifications for commutative
230// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000231//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000232// 1. Order operands such that they are listed from right (least complex) to
233// left (most complex). This puts constants before unary operators before
234// binary operators.
235//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000236// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
237// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000238//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000239bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000240 bool Changed = false;
241 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
242 Changed = !I.swapOperands();
243
244 if (!I.isAssociative()) return Changed;
245 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000246 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
247 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
248 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000249 Constant *Folded = ConstantExpr::get(I.getOpcode(),
250 cast<Constant>(I.getOperand(1)),
251 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000252 I.setOperand(0, Op->getOperand(0));
253 I.setOperand(1, Folded);
254 return true;
255 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
256 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
257 isOnlyUse(Op) && isOnlyUse(Op1)) {
258 Constant *C1 = cast<Constant>(Op->getOperand(1));
259 Constant *C2 = cast<Constant>(Op1->getOperand(1));
260
261 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000262 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000263 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
264 Op1->getOperand(0),
265 Op1->getName(), &I);
266 WorkList.push_back(New);
267 I.setOperand(0, New);
268 I.setOperand(1, Folded);
269 return true;
270 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000271 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000272 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000273}
Chris Lattnerca081252001-12-14 16:52:21 +0000274
Chris Lattnerbb74e222003-03-10 23:06:50 +0000275// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
276// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000277//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000278static inline Value *dyn_castNegVal(Value *V) {
279 if (BinaryOperator::isNeg(V))
280 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
281
Chris Lattner9244df62003-04-30 22:19:10 +0000282 // Constants can be considered to be negated values if they can be folded...
283 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000284 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000285 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000286}
287
Chris Lattnerbb74e222003-03-10 23:06:50 +0000288static inline Value *dyn_castNotVal(Value *V) {
289 if (BinaryOperator::isNot(V))
290 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
291
292 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000293 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000294 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000295 return 0;
296}
297
Chris Lattner7fb29e12003-03-11 00:12:48 +0000298// dyn_castFoldableMul - If this value is a multiply that can be folded into
299// other computations (because it has a constant operand), return the
300// non-constant operand of the multiply.
301//
302static inline Value *dyn_castFoldableMul(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000303 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000304 if (Instruction *I = dyn_cast<Instruction>(V))
305 if (I->getOpcode() == Instruction::Mul)
306 if (isa<Constant>(I->getOperand(1)))
307 return I->getOperand(0);
308 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000309}
Chris Lattner31ae8632002-08-14 17:51:49 +0000310
Chris Lattner7fb29e12003-03-11 00:12:48 +0000311// dyn_castMaskingAnd - If this value is an And instruction masking a value with
312// a constant, return the constant being anded with.
313//
Chris Lattner01d56392003-08-12 19:17:27 +0000314template<class ValueType>
315static inline Constant *dyn_castMaskingAnd(ValueType *V) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000316 if (Instruction *I = dyn_cast<Instruction>(V))
317 if (I->getOpcode() == Instruction::And)
318 return dyn_cast<Constant>(I->getOperand(1));
319
320 // If this is a constant, it acts just like we were masking with it.
321 return dyn_cast<Constant>(V);
322}
Chris Lattner3082c5a2003-02-18 19:28:33 +0000323
324// Log2 - Calculate the log base 2 for the specified value if it is exactly a
325// power of 2.
326static unsigned Log2(uint64_t Val) {
327 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
328 unsigned Count = 0;
329 while (Val != 1) {
330 if (Val & 1) return 0; // Multiple bits set?
331 Val >>= 1;
332 ++Count;
333 }
334 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000335}
336
Chris Lattnerb8b97502003-08-13 19:01:45 +0000337
338/// AssociativeOpt - Perform an optimization on an associative operator. This
339/// function is designed to check a chain of associative operators for a
340/// potential to apply a certain optimization. Since the optimization may be
341/// applicable if the expression was reassociated, this checks the chain, then
342/// reassociates the expression as necessary to expose the optimization
343/// opportunity. This makes use of a special Functor, which must define
344/// 'shouldApply' and 'apply' methods.
345///
346template<typename Functor>
347Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
348 unsigned Opcode = Root.getOpcode();
349 Value *LHS = Root.getOperand(0);
350
351 // Quick check, see if the immediate LHS matches...
352 if (F.shouldApply(LHS))
353 return F.apply(Root);
354
355 // Otherwise, if the LHS is not of the same opcode as the root, return.
356 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000357 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000358 // Should we apply this transform to the RHS?
359 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
360
361 // If not to the RHS, check to see if we should apply to the LHS...
362 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
363 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
364 ShouldApply = true;
365 }
366
367 // If the functor wants to apply the optimization to the RHS of LHSI,
368 // reassociate the expression from ((? op A) op B) to (? op (A op B))
369 if (ShouldApply) {
370 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000371
372 // Now all of the instructions are in the current basic block, go ahead
373 // and perform the reassociation.
374 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
375
376 // First move the selected RHS to the LHS of the root...
377 Root.setOperand(0, LHSI->getOperand(1));
378
379 // Make what used to be the LHS of the root be the user of the root...
380 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000381 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000382 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
383 return 0;
384 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000385 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000386 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000387 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
388 BasicBlock::iterator ARI = &Root; ++ARI;
389 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
390 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000391
392 // Now propagate the ExtraOperand down the chain of instructions until we
393 // get to LHSI.
394 while (TmpLHSI != LHSI) {
395 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000396 // Move the instruction to immediately before the chain we are
397 // constructing to avoid breaking dominance properties.
398 NextLHSI->getParent()->getInstList().remove(NextLHSI);
399 BB->getInstList().insert(ARI, NextLHSI);
400 ARI = NextLHSI;
401
Chris Lattnerb8b97502003-08-13 19:01:45 +0000402 Value *NextOp = NextLHSI->getOperand(1);
403 NextLHSI->setOperand(1, ExtraOperand);
404 TmpLHSI = NextLHSI;
405 ExtraOperand = NextOp;
406 }
407
408 // Now that the instructions are reassociated, have the functor perform
409 // the transformation...
410 return F.apply(Root);
411 }
412
413 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
414 }
415 return 0;
416}
417
418
419// AddRHS - Implements: X + X --> X << 1
420struct AddRHS {
421 Value *RHS;
422 AddRHS(Value *rhs) : RHS(rhs) {}
423 bool shouldApply(Value *LHS) const { return LHS == RHS; }
424 Instruction *apply(BinaryOperator &Add) const {
425 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
426 ConstantInt::get(Type::UByteTy, 1));
427 }
428};
429
430// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
431// iff C1&C2 == 0
432struct AddMaskingAnd {
433 Constant *C2;
434 AddMaskingAnd(Constant *c) : C2(c) {}
435 bool shouldApply(Value *LHS) const {
436 if (Constant *C1 = dyn_castMaskingAnd(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000437 return ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000438 return false;
439 }
440 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000441 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000442 }
443};
444
Chris Lattner183b3362004-04-09 19:05:30 +0000445static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
446 InstCombiner *IC) {
447 // Figure out if the constant is the left or the right argument.
448 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
449 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000450
Chris Lattner183b3362004-04-09 19:05:30 +0000451 if (Constant *SOC = dyn_cast<Constant>(SO)) {
452 if (ConstIsRHS)
453 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
454 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
455 }
456
457 Value *Op0 = SO, *Op1 = ConstOperand;
458 if (!ConstIsRHS)
459 std::swap(Op0, Op1);
460 Instruction *New;
461 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
462 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
463 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
464 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattnerf9d96652004-04-10 19:15:56 +0000465 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000466 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000467 abort();
468 }
Chris Lattner183b3362004-04-09 19:05:30 +0000469 return IC->InsertNewInstBefore(New, BI);
470}
471
472// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
473// constant as the other operand, try to fold the binary operator into the
474// select arguments.
475static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
476 InstCombiner *IC) {
477 // Don't modify shared select instructions
478 if (!SI->hasOneUse()) return 0;
479 Value *TV = SI->getOperand(1);
480 Value *FV = SI->getOperand(2);
481
482 if (isa<Constant>(TV) || isa<Constant>(FV)) {
483 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
484 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
485
486 return new SelectInst(SI->getCondition(), SelectTrueVal,
487 SelectFalseVal);
488 }
489 return 0;
490}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000491
Chris Lattner113f4f42002-06-25 16:13:24 +0000492Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000493 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000494 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000495
Chris Lattnercf4a9962004-04-10 22:01:55 +0000496 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
497 // X + 0 --> X
498 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
499 RHSC->isNullValue())
500 return ReplaceInstUsesWith(I, LHS);
501
502 // X + (signbit) --> X ^ signbit
503 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
504 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
505 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
506 if (Val == (1ULL << NumBits-1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000507 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000508 }
509 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000510
Chris Lattnerb8b97502003-08-13 19:01:45 +0000511 // X + X --> X << 1
512 if (I.getType()->isInteger())
513 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattnerede3fe02003-08-13 04:18:28 +0000514
Chris Lattner147e9752002-05-08 22:46:53 +0000515 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000516 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000517 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000518
519 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000520 if (!isa<Constant>(RHS))
521 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000522 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000523
Chris Lattner57c8d992003-02-18 19:57:07 +0000524 // X*C + X --> X * (C+1)
525 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000526 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000527 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000528 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
529 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000530 return BinaryOperator::createMul(RHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000531 }
532
533 // X + X*C --> X * (C+1)
534 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000535 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000536 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000537 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
538 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000539 return BinaryOperator::createMul(LHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000540 }
541
Chris Lattnerb8b97502003-08-13 19:01:45 +0000542 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
543 if (Constant *C2 = dyn_castMaskingAnd(RHS))
544 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000545
Chris Lattnerb9cde762003-10-02 15:11:26 +0000546 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
547 if (Instruction *ILHS = dyn_cast<Instruction>(LHS)) {
548 switch (ILHS->getOpcode()) {
549 case Instruction::Xor:
550 // ~X + C --> (C-1) - X
551 if (ConstantInt *XorRHS = dyn_cast<ConstantInt>(ILHS->getOperand(1)))
552 if (XorRHS->isAllOnesValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000553 return BinaryOperator::createSub(ConstantExpr::getSub(CRHS,
554 ConstantInt::get(I.getType(), 1)),
Chris Lattnerb9cde762003-10-02 15:11:26 +0000555 ILHS->getOperand(0));
556 break;
Chris Lattner183b3362004-04-09 19:05:30 +0000557 case Instruction::Select:
558 // Try to fold constant add into select arguments.
559 if (Instruction *R = FoldBinOpIntoSelect(I,cast<SelectInst>(ILHS),this))
560 return R;
561
Chris Lattnerb9cde762003-10-02 15:11:26 +0000562 default: break;
563 }
564 }
565 }
566
Chris Lattner113f4f42002-06-25 16:13:24 +0000567 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000568}
569
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000570// isSignBit - Return true if the value represented by the constant only has the
571// highest order bit set.
572static bool isSignBit(ConstantInt *CI) {
573 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
574 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
575}
576
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000577static unsigned getTypeSizeInBits(const Type *Ty) {
578 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
579}
580
Chris Lattner022167f2004-03-13 00:11:49 +0000581/// RemoveNoopCast - Strip off nonconverting casts from the value.
582///
583static Value *RemoveNoopCast(Value *V) {
584 if (CastInst *CI = dyn_cast<CastInst>(V)) {
585 const Type *CTy = CI->getType();
586 const Type *OpTy = CI->getOperand(0)->getType();
587 if (CTy->isInteger() && OpTy->isInteger()) {
588 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
589 return RemoveNoopCast(CI->getOperand(0));
590 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
591 return RemoveNoopCast(CI->getOperand(0));
592 }
593 return V;
594}
595
Chris Lattner113f4f42002-06-25 16:13:24 +0000596Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000597 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000598
Chris Lattnere6794492002-08-12 21:17:25 +0000599 if (Op0 == Op1) // sub X, X -> 0
600 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000601
Chris Lattnere6794492002-08-12 21:17:25 +0000602 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000603 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000604 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000605
Chris Lattner8f2f5982003-11-05 01:06:05 +0000606 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
607 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000608 if (C->isAllOnesValue())
609 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000610
Chris Lattner8f2f5982003-11-05 01:06:05 +0000611 // C - ~X == X + (1+C)
612 if (BinaryOperator::isNot(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000613 return BinaryOperator::createAdd(
614 BinaryOperator::getNotArgument(cast<BinaryOperator>(Op1)),
615 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000616 // -((uint)X >> 31) -> ((int)X >> 31)
617 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000618 if (C->isNullValue()) {
619 Value *NoopCastedRHS = RemoveNoopCast(Op1);
620 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000621 if (SI->getOpcode() == Instruction::Shr)
622 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
623 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000624 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000625 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000626 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000627 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000628 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000629 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000630 // Ok, the transformation is safe. Insert a cast of the incoming
631 // value, then the new shift, then the new cast.
632 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
633 SI->getOperand(0)->getName());
634 Value *InV = InsertNewInstBefore(FirstCast, I);
635 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
636 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000637 if (NewShift->getType() == I.getType())
638 return NewShift;
639 else {
640 InV = InsertNewInstBefore(NewShift, I);
641 return new CastInst(NewShift, I.getType());
642 }
Chris Lattner92295c52004-03-12 23:53:13 +0000643 }
644 }
Chris Lattner022167f2004-03-13 00:11:49 +0000645 }
Chris Lattner183b3362004-04-09 19:05:30 +0000646
647 // Try to fold constant sub into select arguments.
648 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
649 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
650 return R;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000651 }
652
Chris Lattner3082c5a2003-02-18 19:28:33 +0000653 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000654 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000655 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
656 // is not used by anyone else...
657 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000658 if (Op1I->getOpcode() == Instruction::Sub &&
659 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000660 // Swap the two operands of the subexpr...
661 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
662 Op1I->setOperand(0, IIOp1);
663 Op1I->setOperand(1, IIOp0);
664
665 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000666 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000667 }
668
669 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
670 //
671 if (Op1I->getOpcode() == Instruction::And &&
672 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
673 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
674
Chris Lattner396dbfe2004-06-09 05:08:07 +0000675 Value *NewNot =
676 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000677 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000678 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000679
680 // X - X*C --> X * (1-C)
681 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000682 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000683 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner34428442003-05-27 16:40:51 +0000684 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000685 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000686 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000687 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000688 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000689
Chris Lattner57c8d992003-02-18 19:57:07 +0000690 // X*C - X --> X * (C-1)
691 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000692 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000693 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner34428442003-05-27 16:40:51 +0000694 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000695 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000696 return BinaryOperator::createMul(Op1, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000697 }
698
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000699 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000700}
701
Chris Lattnere79e8542004-02-23 06:38:22 +0000702/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
703/// really just returns true if the most significant (sign) bit is set.
704static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
705 if (RHS->getType()->isSigned()) {
706 // True if source is LHS < 0 or LHS <= -1
707 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
708 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
709 } else {
710 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
711 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
712 // the size of the integer type.
713 if (Opcode == Instruction::SetGE)
714 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
715 if (Opcode == Instruction::SetGT)
716 return RHSC->getValue() ==
717 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
718 }
719 return false;
720}
721
Chris Lattner113f4f42002-06-25 16:13:24 +0000722Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000723 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000724 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000725
Chris Lattnere6794492002-08-12 21:17:25 +0000726 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000727 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
728 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000729
730 // ((X << C1)*C2) == (X * (C2 << C1))
731 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
732 if (SI->getOpcode() == Instruction::Shl)
733 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000734 return BinaryOperator::createMul(SI->getOperand(0),
735 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000736
Chris Lattnercce81be2003-09-11 22:24:54 +0000737 if (CI->isNullValue())
738 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
739 if (CI->equalsInt(1)) // X * 1 == X
740 return ReplaceInstUsesWith(I, Op0);
741 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000742 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000743
Chris Lattnercce81be2003-09-11 22:24:54 +0000744 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000745 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
746 return new ShiftInst(Instruction::Shl, Op0,
747 ConstantUInt::get(Type::UByteTy, C));
748 } else {
749 ConstantFP *Op1F = cast<ConstantFP>(Op1);
750 if (Op1F->isNullValue())
751 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000752
Chris Lattner3082c5a2003-02-18 19:28:33 +0000753 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
754 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
755 if (Op1F->getValue() == 1.0)
756 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
757 }
Chris Lattner183b3362004-04-09 19:05:30 +0000758
759 // Try to fold constant mul into select arguments.
760 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
761 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
762 return R;
Chris Lattner260ab202002-04-18 17:39:14 +0000763 }
764
Chris Lattner934a64cf2003-03-10 23:23:04 +0000765 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
766 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000767 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000768
Chris Lattner2635b522004-02-23 05:39:21 +0000769 // If one of the operands of the multiply is a cast from a boolean value, then
770 // we know the bool is either zero or one, so this is a 'masking' multiply.
771 // See if we can simplify things based on how the boolean was originally
772 // formed.
773 CastInst *BoolCast = 0;
774 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
775 if (CI->getOperand(0)->getType() == Type::BoolTy)
776 BoolCast = CI;
777 if (!BoolCast)
778 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
779 if (CI->getOperand(0)->getType() == Type::BoolTy)
780 BoolCast = CI;
781 if (BoolCast) {
782 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
783 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
784 const Type *SCOpTy = SCIOp0->getType();
785
Chris Lattnere79e8542004-02-23 06:38:22 +0000786 // If the setcc is true iff the sign bit of X is set, then convert this
787 // multiply into a shift/and combination.
788 if (isa<ConstantInt>(SCIOp1) &&
789 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000790 // Shift the X value right to turn it into "all signbits".
791 Constant *Amt = ConstantUInt::get(Type::UByteTy,
792 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000793 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000794 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000795 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
796 SCIOp0->getName()), I);
797 }
798
799 Value *V =
800 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
801 BoolCast->getOperand(0)->getName()+
802 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000803
804 // If the multiply type is not the same as the source type, sign extend
805 // or truncate to the multiply type.
806 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000807 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000808
809 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000810 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000811 }
812 }
813 }
814
Chris Lattner113f4f42002-06-25 16:13:24 +0000815 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000816}
817
Chris Lattner113f4f42002-06-25 16:13:24 +0000818Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000819 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000820 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000821 if (RHS->equalsInt(1))
822 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000823
Chris Lattnere20c3342004-04-26 14:01:59 +0000824 // div X, -1 == -X
825 if (RHS->isAllOnesValue())
826 return BinaryOperator::createNeg(I.getOperand(0));
827
Chris Lattner3082c5a2003-02-18 19:28:33 +0000828 // Check to see if this is an unsigned division with an exact power of 2,
829 // if so, convert to a right shift.
830 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
831 if (uint64_t Val = C->getValue()) // Don't break X / 0
832 if (uint64_t C = Log2(Val))
833 return new ShiftInst(Instruction::Shr, I.getOperand(0),
834 ConstantUInt::get(Type::UByteTy, C));
835 }
836
837 // 0 / X == 0, we don't need to preserve faults!
838 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
839 if (LHS->equalsInt(0))
840 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
841
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000842 return 0;
843}
844
845
Chris Lattner113f4f42002-06-25 16:13:24 +0000846Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000847 if (I.getType()->isSigned())
848 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
849 if (RHSNeg != I.getOperand(1)) { // Avoid problems with MININT
850 // X % -Y -> X % Y
851 AddUsesToWorkList(I);
852 I.setOperand(1, RHSNeg);
853 return &I;
854 }
855
Chris Lattner3082c5a2003-02-18 19:28:33 +0000856 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
857 if (RHS->equalsInt(1)) // X % 1 == 0
858 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
859
860 // Check to see if this is an unsigned remainder with an exact power of 2,
861 // if so, convert to a bitwise and.
862 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
863 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +0000864 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000865 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattner3082c5a2003-02-18 19:28:33 +0000866 ConstantUInt::get(I.getType(), Val-1));
867 }
868
869 // 0 % X == 0, we don't need to preserve faults!
870 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
871 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000872 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
873
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000874 return 0;
875}
876
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000877// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000878static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000879 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
880 // Calculate -1 casted to the right type...
881 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
882 uint64_t Val = ~0ULL; // All ones
883 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
884 return CU->getValue() == Val-1;
885 }
886
887 const ConstantSInt *CS = cast<ConstantSInt>(C);
888
889 // Calculate 0111111111..11111
890 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
891 int64_t Val = INT64_MAX; // All ones
892 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
893 return CS->getValue() == Val-1;
894}
895
896// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000897static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000898 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
899 return CU->getValue() == 1;
900
901 const ConstantSInt *CS = cast<ConstantSInt>(C);
902
903 // Calculate 1111111111000000000000
904 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
905 int64_t Val = -1; // All ones
906 Val <<= TypeBits-1; // Shift over to the right spot
907 return CS->getValue() == Val+1;
908}
909
Chris Lattner35167c32004-06-09 07:59:58 +0000910// isOneBitSet - Return true if there is exactly one bit set in the specified
911// constant.
912static bool isOneBitSet(const ConstantInt *CI) {
913 uint64_t V = CI->getRawValue();
914 return V && (V & (V-1)) == 0;
915}
916
Chris Lattner3ac7c262003-08-13 20:16:26 +0000917/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
918/// are carefully arranged to allow folding of expressions such as:
919///
920/// (A < B) | (A > B) --> (A != B)
921///
922/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
923/// represents that the comparison is true if A == B, and bit value '1' is true
924/// if A < B.
925///
926static unsigned getSetCondCode(const SetCondInst *SCI) {
927 switch (SCI->getOpcode()) {
928 // False -> 0
929 case Instruction::SetGT: return 1;
930 case Instruction::SetEQ: return 2;
931 case Instruction::SetGE: return 3;
932 case Instruction::SetLT: return 4;
933 case Instruction::SetNE: return 5;
934 case Instruction::SetLE: return 6;
935 // True -> 7
936 default:
937 assert(0 && "Invalid SetCC opcode!");
938 return 0;
939 }
940}
941
942/// getSetCCValue - This is the complement of getSetCondCode, which turns an
943/// opcode and two operands into either a constant true or false, or a brand new
944/// SetCC instruction.
945static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
946 switch (Opcode) {
947 case 0: return ConstantBool::False;
948 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
949 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
950 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
951 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
952 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
953 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
954 case 7: return ConstantBool::True;
955 default: assert(0 && "Illegal SetCCCode!"); return 0;
956 }
957}
958
959// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
960struct FoldSetCCLogical {
961 InstCombiner &IC;
962 Value *LHS, *RHS;
963 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
964 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
965 bool shouldApply(Value *V) const {
966 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
967 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
968 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
969 return false;
970 }
971 Instruction *apply(BinaryOperator &Log) const {
972 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
973 if (SCI->getOperand(0) != LHS) {
974 assert(SCI->getOperand(1) == LHS);
975 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
976 }
977
978 unsigned LHSCode = getSetCondCode(SCI);
979 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
980 unsigned Code;
981 switch (Log.getOpcode()) {
982 case Instruction::And: Code = LHSCode & RHSCode; break;
983 case Instruction::Or: Code = LHSCode | RHSCode; break;
984 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +0000985 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +0000986 }
987
988 Value *RV = getSetCCValue(Code, LHS, RHS);
989 if (Instruction *I = dyn_cast<Instruction>(RV))
990 return I;
991 // Otherwise, it's a constant boolean value...
992 return IC.ReplaceInstUsesWith(Log, RV);
993 }
994};
995
996
Chris Lattnerba1cb382003-09-19 17:17:26 +0000997// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
998// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
999// guaranteed to be either a shift instruction or a binary operator.
1000Instruction *InstCombiner::OptAndOp(Instruction *Op,
1001 ConstantIntegral *OpRHS,
1002 ConstantIntegral *AndRHS,
1003 BinaryOperator &TheAnd) {
1004 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001005 Constant *Together = 0;
1006 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001007 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001008
Chris Lattnerba1cb382003-09-19 17:17:26 +00001009 switch (Op->getOpcode()) {
1010 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001011 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001012 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001013 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001014 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001015 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1016 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001017 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001018 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001019 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001020 }
1021 break;
1022 case Instruction::Or:
1023 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001024 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001025 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001026 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001027 if (Together == AndRHS) // (X | C) & C --> C
1028 return ReplaceInstUsesWith(TheAnd, AndRHS);
1029
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001030 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001031 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1032 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001033 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001034 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001035 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001036 }
1037 }
1038 break;
1039 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001040 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001041 // Adding a one to a single bit bit-field should be turned into an XOR
1042 // of the bit. First thing to check is to see if this AND is with a
1043 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001044 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001045
1046 // Clear bits that are not part of the constant.
1047 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1048
1049 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001050 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001051 // Ok, at this point, we know that we are masking the result of the
1052 // ADD down to exactly one bit. If the constant we are adding has
1053 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001054 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001055
1056 // Check to see if any bits below the one bit set in AndRHSV are set.
1057 if ((AddRHS & (AndRHSV-1)) == 0) {
1058 // If not, the only thing that can effect the output of the AND is
1059 // the bit specified by AndRHSV. If that bit is set, the effect of
1060 // the XOR is to toggle the bit. If it is clear, then the ADD has
1061 // no effect.
1062 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1063 TheAnd.setOperand(0, X);
1064 return &TheAnd;
1065 } else {
1066 std::string Name = Op->getName(); Op->setName("");
1067 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001068 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001069 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001070 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001071 }
1072 }
1073 }
1074 }
1075 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001076
1077 case Instruction::Shl: {
1078 // We know that the AND will not produce any of the bits shifted in, so if
1079 // the anded constant includes them, clear them now!
1080 //
1081 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001082 Constant *CI = ConstantExpr::getAnd(AndRHS,
1083 ConstantExpr::getShl(AllOne, OpRHS));
Chris Lattner2da29172003-09-19 19:05:02 +00001084 if (CI != AndRHS) {
1085 TheAnd.setOperand(1, CI);
1086 return &TheAnd;
1087 }
1088 break;
1089 }
1090 case Instruction::Shr:
1091 // We know that the AND will not produce any of the bits shifted in, so if
1092 // the anded constant includes them, clear them now! This only applies to
1093 // unsigned shifts, because a signed shr may bring in set bits!
1094 //
1095 if (AndRHS->getType()->isUnsigned()) {
1096 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001097 Constant *CI = ConstantExpr::getAnd(AndRHS,
1098 ConstantExpr::getShr(AllOne, OpRHS));
Chris Lattner2da29172003-09-19 19:05:02 +00001099 if (CI != AndRHS) {
1100 TheAnd.setOperand(1, CI);
1101 return &TheAnd;
1102 }
1103 }
1104 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001105 }
1106 return 0;
1107}
1108
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001109
Chris Lattner113f4f42002-06-25 16:13:24 +00001110Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001111 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001112 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001113
1114 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001115 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1116 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001117
1118 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001119 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001120 if (RHS->isAllOnesValue())
1121 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001122
Chris Lattnerba1cb382003-09-19 17:17:26 +00001123 // Optimize a variety of ((val OP C1) & C2) combinations...
1124 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1125 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001126 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001127 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001128 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1129 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001130 }
Chris Lattner183b3362004-04-09 19:05:30 +00001131
1132 // Try to fold constant and into select arguments.
1133 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1134 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1135 return R;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001136 }
1137
Chris Lattnerbb74e222003-03-10 23:06:50 +00001138 Value *Op0NotVal = dyn_castNotVal(Op0);
1139 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001140
Chris Lattner023a4832004-06-18 06:07:51 +00001141 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1142 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1143
Chris Lattner3082c5a2003-02-18 19:28:33 +00001144 // (~A & ~B) == (~(A | B)) - Demorgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001145 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001146 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1147 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001148 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001149 return BinaryOperator::createNot(Or);
1150 }
1151
Chris Lattner3ac7c262003-08-13 20:16:26 +00001152 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1153 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1154 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1155 return R;
1156
Chris Lattner113f4f42002-06-25 16:13:24 +00001157 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001158}
1159
1160
1161
Chris Lattner113f4f42002-06-25 16:13:24 +00001162Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001163 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001164 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001165
1166 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001167 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1168 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001169
1170 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001171 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001172 if (RHS->isAllOnesValue())
1173 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001174
Chris Lattner8f0d1562003-07-23 18:29:44 +00001175 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1176 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1177 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
1178 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
1179 std::string Op0Name = Op0I->getName(); Op0I->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001180 Instruction *Or = BinaryOperator::createOr(Op0I->getOperand(0), RHS,
1181 Op0Name);
Chris Lattner8f0d1562003-07-23 18:29:44 +00001182 InsertNewInstBefore(Or, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001183 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, Op0CI));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001184 }
1185
1186 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1187 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
1188 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
1189 std::string Op0Name = Op0I->getName(); Op0I->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001190 Instruction *Or = BinaryOperator::createOr(Op0I->getOperand(0), RHS,
1191 Op0Name);
Chris Lattner8f0d1562003-07-23 18:29:44 +00001192 InsertNewInstBefore(Or, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001193 return BinaryOperator::createXor(Or,
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001194 ConstantExpr::getAnd(Op0CI,
1195 ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001196 }
1197 }
Chris Lattner183b3362004-04-09 19:05:30 +00001198
1199 // Try to fold constant and into select arguments.
1200 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1201 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1202 return R;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001203 }
1204
Chris Lattner812aab72003-08-12 19:11:07 +00001205 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattner01d56392003-08-12 19:17:27 +00001206 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
1207 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
1208 if (LHS->getOperand(0) == RHS->getOperand(0))
1209 if (Constant *C0 = dyn_castMaskingAnd(LHS))
1210 if (Constant *C1 = dyn_castMaskingAnd(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001211 return BinaryOperator::createAnd(LHS->getOperand(0),
1212 ConstantExpr::getOr(C0, C1));
Chris Lattner812aab72003-08-12 19:11:07 +00001213
Chris Lattner3e327a42003-03-10 23:13:59 +00001214 Value *Op0NotVal = dyn_castNotVal(Op0);
1215 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001216
Chris Lattner3e327a42003-03-10 23:13:59 +00001217 if (Op1 == Op0NotVal) // ~A | A == -1
1218 return ReplaceInstUsesWith(I,
1219 ConstantIntegral::getAllOnesValue(I.getType()));
1220
1221 if (Op0 == Op1NotVal) // A | ~A == -1
1222 return ReplaceInstUsesWith(I,
1223 ConstantIntegral::getAllOnesValue(I.getType()));
1224
1225 // (~A | ~B) == (~(A & B)) - Demorgan's Law
1226 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner396dbfe2004-06-09 05:08:07 +00001227 Value *And = InsertNewInstBefore(
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001228 BinaryOperator::createAnd(Op0NotVal,
1229 Op1NotVal,I.getName()+".demorgan"),I);
Chris Lattner3e327a42003-03-10 23:13:59 +00001230 return BinaryOperator::createNot(And);
1231 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001232
Chris Lattner3ac7c262003-08-13 20:16:26 +00001233 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
1234 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1235 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1236 return R;
1237
Chris Lattner113f4f42002-06-25 16:13:24 +00001238 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001239}
1240
Chris Lattnerc2076352004-02-16 01:20:27 +00001241// XorSelf - Implements: X ^ X --> 0
1242struct XorSelf {
1243 Value *RHS;
1244 XorSelf(Value *rhs) : RHS(rhs) {}
1245 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1246 Instruction *apply(BinaryOperator &Xor) const {
1247 return &Xor;
1248 }
1249};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001250
1251
Chris Lattner113f4f42002-06-25 16:13:24 +00001252Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001253 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001254 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001255
Chris Lattnerc2076352004-02-16 01:20:27 +00001256 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1257 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1258 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001259 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001260 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001261
Chris Lattner97638592003-07-23 21:37:07 +00001262 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001263 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001264 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001265 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001266
Chris Lattner97638592003-07-23 21:37:07 +00001267 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001268 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001269 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001270 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001271 return new SetCondInst(SCI->getInverseCondition(),
1272 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001273
Chris Lattner8f2f5982003-11-05 01:06:05 +00001274 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001275 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1276 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001277 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1278 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001279 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001280 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001281 }
Chris Lattner023a4832004-06-18 06:07:51 +00001282
1283 // ~(~X & Y) --> (X | ~Y)
1284 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1285 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1286 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1287 Instruction *NotY =
1288 BinaryOperator::createNot(Op0I->getOperand(1),
1289 Op0I->getOperand(1)->getName()+".not");
1290 InsertNewInstBefore(NotY, I);
1291 return BinaryOperator::createOr(Op0NotVal, NotY);
1292 }
1293 }
Chris Lattner97638592003-07-23 21:37:07 +00001294
1295 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001296 switch (Op0I->getOpcode()) {
1297 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001298 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001299 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001300 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1301 return BinaryOperator::createSub(
1302 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001303 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001304 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001305 }
Chris Lattnere5806662003-11-04 23:50:51 +00001306 break;
1307 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001308 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001309 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1310 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001311 break;
1312 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001313 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001314 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001315 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001316 break;
1317 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001318 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001319 }
Chris Lattner183b3362004-04-09 19:05:30 +00001320
1321 // Try to fold constant and into select arguments.
1322 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1323 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1324 return R;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001325 }
1326
Chris Lattnerbb74e222003-03-10 23:06:50 +00001327 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001328 if (X == Op1)
1329 return ReplaceInstUsesWith(I,
1330 ConstantIntegral::getAllOnesValue(I.getType()));
1331
Chris Lattnerbb74e222003-03-10 23:06:50 +00001332 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001333 if (X == Op0)
1334 return ReplaceInstUsesWith(I,
1335 ConstantIntegral::getAllOnesValue(I.getType()));
1336
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001337 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001338 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001339 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1340 cast<BinaryOperator>(Op1I)->swapOperands();
1341 I.swapOperands();
1342 std::swap(Op0, Op1);
1343 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1344 I.swapOperands();
1345 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001346 }
1347 } else if (Op1I->getOpcode() == Instruction::Xor) {
1348 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1349 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1350 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1351 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1352 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001353
1354 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001355 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001356 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1357 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001358 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001359 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1360 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001361 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001362 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001363 } else if (Op0I->getOpcode() == Instruction::Xor) {
1364 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1365 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1366 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1367 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001368 }
1369
Chris Lattner7fb29e12003-03-11 00:12:48 +00001370 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
1371 if (Constant *C1 = dyn_castMaskingAnd(Op0))
1372 if (Constant *C2 = dyn_castMaskingAnd(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001373 if (ConstantExpr::getAnd(C1, C2)->isNullValue())
1374 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001375
Chris Lattner3ac7c262003-08-13 20:16:26 +00001376 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1377 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1378 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1379 return R;
1380
Chris Lattner113f4f42002-06-25 16:13:24 +00001381 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001382}
1383
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001384// AddOne, SubOne - Add or subtract a constant one from an integer constant...
1385static Constant *AddOne(ConstantInt *C) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001386 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001387}
1388static Constant *SubOne(ConstantInt *C) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001389 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001390}
1391
Chris Lattner1fc23f32002-05-09 20:11:54 +00001392// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1393// true when both operands are equal...
1394//
Chris Lattner113f4f42002-06-25 16:13:24 +00001395static bool isTrueWhenEqual(Instruction &I) {
1396 return I.getOpcode() == Instruction::SetEQ ||
1397 I.getOpcode() == Instruction::SetGE ||
1398 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +00001399}
1400
Chris Lattner113f4f42002-06-25 16:13:24 +00001401Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001402 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001403 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1404 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001405
1406 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001407 if (Op0 == Op1)
1408 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001409
Chris Lattnerd07283a2003-08-13 05:38:46 +00001410 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1411 if (isa<ConstantPointerNull>(Op1) &&
1412 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001413 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1414
Chris Lattnerd07283a2003-08-13 05:38:46 +00001415
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001416 // setcc's with boolean values can always be turned into bitwise operations
1417 if (Ty == Type::BoolTy) {
1418 // If this is <, >, or !=, we can change this into a simple xor instruction
1419 if (!isTrueWhenEqual(I))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001420 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001421
1422 // Otherwise we need to make a temporary intermediate instruction and insert
1423 // it into the instruction stream. This is what we are after:
1424 //
1425 // seteq bool %A, %B -> ~(A^B)
1426 // setle bool %A, %B -> ~A | B
1427 // setge bool %A, %B -> A | ~B
1428 //
1429 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001430 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001431 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001432 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001433 }
1434
1435 // Handle the setXe cases...
1436 assert(I.getOpcode() == Instruction::SetGE ||
1437 I.getOpcode() == Instruction::SetLE);
1438
1439 if (I.getOpcode() == Instruction::SetGE)
1440 std::swap(Op0, Op1); // Change setge -> setle
1441
1442 // Now we just have the SetLE case.
Chris Lattner31ae8632002-08-14 17:51:49 +00001443 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001444 InsertNewInstBefore(Not, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001445 return BinaryOperator::createOr(Not, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001446 }
1447
Chris Lattner2dd01742004-06-09 04:24:29 +00001448 // See if we are doing a comparison between a constant and an instruction that
1449 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001450 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere1e10e12004-05-25 06:32:08 +00001451 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner2dd01742004-06-09 04:24:29 +00001452 if (LHSI->hasOneUse())
Chris Lattner35167c32004-06-09 07:59:58 +00001453 switch (LHSI->getOpcode()) {
1454 case Instruction::And:
1455 if (isa<ConstantInt>(LHSI->getOperand(1))) {
1456
Chris Lattnere1e10e12004-05-25 06:32:08 +00001457
Chris Lattner35167c32004-06-09 07:59:58 +00001458 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1459 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1460 // happens a LOT in code produced by the C front-end, for bitfield
1461 // access.
1462 if (LHSI->getOperand(0)->hasOneUse())
1463 if (ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0)))
1464 if (ConstantUInt *ShAmt =
1465 dyn_cast<ConstantUInt>(Shift->getOperand(1))) {
1466 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1467
1468 // We can fold this as long as we can't shift unknown bits
1469 // into the mask. This can only happen with signed shift
1470 // rights, as they sign-extend.
1471 const Type *Ty = Shift->getType();
1472 if (Shift->getOpcode() != Instruction::Shr ||
1473 Shift->getType()->isUnsigned() ||
1474 // To test for the bad case of the signed shr, see if any
1475 // of the bits shifted in could be tested after the mask.
1476 ConstantExpr::getAnd(ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), ConstantUInt::get(Type::UByteTy, Ty->getPrimitiveSize()*8-ShAmt->getValue())), AndCST)->isNullValue()) {
1477 unsigned ShiftOp = Shift->getOpcode() == Instruction::Shl
1478 ? Instruction::Shr : Instruction::Shl;
1479 I.setOperand(1, ConstantExpr::get(ShiftOp, CI, ShAmt));
1480 LHSI->setOperand(1,ConstantExpr::get(ShiftOp,AndCST,ShAmt));
1481 LHSI->setOperand(0, Shift->getOperand(0));
1482 WorkList.push_back(Shift); // Shift is probably dead.
1483 AddUsesToWorkList(I);
1484 return &I;
1485 }
Chris Lattner2dd01742004-06-09 04:24:29 +00001486 }
Chris Lattner35167c32004-06-09 07:59:58 +00001487 }
1488 break;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001489 case Instruction::Div:
1490 if (0 && isa<ConstantInt>(LHSI->getOperand(1))) {
1491 std::cerr << "COULD FOLD: " << *LHSI;
1492 std::cerr << "COULD FOLD: " << I << "\n";
1493 }
1494 break;
Chris Lattner35167c32004-06-09 07:59:58 +00001495 case Instruction::Select:
Chris Lattner2dd01742004-06-09 04:24:29 +00001496 // If either operand of the select is a constant, we can fold the
1497 // comparison into the select arms, which will cause one to be
1498 // constant folded and the select turned into a bitwise or.
1499 Value *Op1 = 0, *Op2 = 0;
Chris Lattner35167c32004-06-09 07:59:58 +00001500 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00001501 // Fold the known value into the constant operand.
1502 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
1503 // Insert a new SetCC of the other select operand.
1504 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00001505 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00001506 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00001507 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00001508 // Fold the known value into the constant operand.
1509 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
1510 // Insert a new SetCC of the other select operand.
1511 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00001512 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00001513 I.getName()), I);
1514 }
1515
1516 if (Op1)
Chris Lattner35167c32004-06-09 07:59:58 +00001517 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
1518 break;
Chris Lattner2dd01742004-06-09 04:24:29 +00001519 }
Chris Lattnere1e10e12004-05-25 06:32:08 +00001520
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001521 // Simplify seteq and setne instructions...
1522 if (I.getOpcode() == Instruction::SetEQ ||
1523 I.getOpcode() == Instruction::SetNE) {
1524 bool isSetNE = I.getOpcode() == Instruction::SetNE;
1525
Chris Lattnercfbce7c2003-07-23 17:26:36 +00001526 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001527 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00001528 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1529 switch (BO->getOpcode()) {
1530 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00001531 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1532 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1533 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1534 ConstantExpr::getSub(CI, BOp1C));
1535 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00001536 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1537 // efficiently invertible, or if the add has just this one use.
1538 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00001539
Chris Lattnerc992add2003-08-13 05:33:12 +00001540 if (Value *NegVal = dyn_castNegVal(BOp1))
1541 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1542 else if (Value *NegVal = dyn_castNegVal(BOp0))
1543 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001544 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00001545 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1546 BO->setName("");
1547 InsertNewInstBefore(Neg, I);
1548 return new SetCondInst(I.getOpcode(), BOp0, Neg);
1549 }
1550 }
1551 break;
1552 case Instruction::Xor:
1553 // For the xor case, we can xor two constants together, eliminating
1554 // the explicit xor.
1555 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1556 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001557 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00001558
1559 // FALLTHROUGH
1560 case Instruction::Sub:
1561 // Replace (([sub|xor] A, B) != 0) with (A != B)
1562 if (CI->isNullValue())
1563 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1564 BO->getOperand(1));
1565 break;
1566
1567 case Instruction::Or:
1568 // If bits are being or'd in that are not present in the constant we
1569 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001570 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001571 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001572 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001573 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001574 }
Chris Lattnerc992add2003-08-13 05:33:12 +00001575 break;
1576
1577 case Instruction::And:
1578 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001579 // If bits are being compared against that are and'd out, then the
1580 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001581 if (!ConstantExpr::getAnd(CI,
1582 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001583 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00001584
Chris Lattner35167c32004-06-09 07:59:58 +00001585 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00001586 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00001587 return new SetCondInst(isSetNE ? Instruction::SetEQ :
1588 Instruction::SetNE, Op0,
1589 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00001590
Chris Lattnerc992add2003-08-13 05:33:12 +00001591 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
1592 // to be a signed value as appropriate.
1593 if (isSignBit(BOC)) {
1594 Value *X = BO->getOperand(0);
1595 // If 'X' is not signed, insert a cast now...
1596 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001597 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerc992add2003-08-13 05:33:12 +00001598 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1599 InsertNewInstBefore(NewCI, I);
1600 X = NewCI;
1601 }
1602 return new SetCondInst(isSetNE ? Instruction::SetLT :
1603 Instruction::SetGE, X,
1604 Constant::getNullValue(X->getType()));
1605 }
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001606 }
Chris Lattnerc992add2003-08-13 05:33:12 +00001607 default: break;
1608 }
1609 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00001610 } else { // Not a SetEQ/SetNE
1611 // If the LHS is a cast from an integral value of the same size,
1612 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
1613 Value *CastOp = Cast->getOperand(0);
1614 const Type *SrcTy = CastOp->getType();
1615 unsigned SrcTySize = SrcTy->getPrimitiveSize();
1616 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
1617 SrcTySize == Cast->getType()->getPrimitiveSize()) {
1618 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
1619 "Source and destination signednesses should differ!");
1620 if (Cast->getType()->isSigned()) {
1621 // If this is a signed comparison, check for comparisons in the
1622 // vicinity of zero.
1623 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
1624 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001625 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00001626 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
1627 else if (I.getOpcode() == Instruction::SetGT &&
1628 cast<ConstantSInt>(CI)->getValue() == -1)
1629 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001630 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00001631 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
1632 } else {
1633 ConstantUInt *CUI = cast<ConstantUInt>(CI);
1634 if (I.getOpcode() == Instruction::SetLT &&
1635 CUI->getValue() == 1ULL << (SrcTySize*8-1))
1636 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001637 return BinaryOperator::createSetGT(CastOp,
1638 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00001639 else if (I.getOpcode() == Instruction::SetGT &&
1640 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
1641 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001642 return BinaryOperator::createSetLT(CastOp,
1643 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00001644 }
1645 }
1646 }
Chris Lattnere967b342003-06-04 05:10:11 +00001647 }
Chris Lattner791ac1a2003-06-01 03:35:25 +00001648
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001649 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +00001650 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001651 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1652 return ReplaceInstUsesWith(I, ConstantBool::False);
1653 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1654 return ReplaceInstUsesWith(I, ConstantBool::True);
1655 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001656 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001657 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001658 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001659
Chris Lattnere6794492002-08-12 21:17:25 +00001660 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001661 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1662 return ReplaceInstUsesWith(I, ConstantBool::False);
1663 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1664 return ReplaceInstUsesWith(I, ConstantBool::True);
1665 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001666 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001667 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001668 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001669
1670 // Comparing against a value really close to min or max?
1671 } else if (isMinValuePlusOne(CI)) {
1672 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001673 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001674 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001675 return BinaryOperator::createSetNE(Op0, SubOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001676
1677 } else if (isMaxValueMinusOne(CI)) {
1678 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001679 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001680 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001681 return BinaryOperator::createSetNE(Op0, AddOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001682 }
Chris Lattner59611142004-02-23 05:47:48 +00001683
1684 // If we still have a setle or setge instruction, turn it into the
1685 // appropriate setlt or setgt instruction. Since the border cases have
1686 // already been handled above, this requires little checking.
1687 //
1688 if (I.getOpcode() == Instruction::SetLE)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001689 return BinaryOperator::createSetLT(Op0, AddOne(CI));
Chris Lattner59611142004-02-23 05:47:48 +00001690 if (I.getOpcode() == Instruction::SetGE)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001691 return BinaryOperator::createSetGT(Op0, SubOne(CI));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001692 }
1693
Chris Lattner16930792003-11-03 04:25:02 +00001694 // Test to see if the operands of the setcc are casted versions of other
1695 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00001696 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1697 Value *CastOp0 = CI->getOperand(0);
1698 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00001699 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00001700 (I.getOpcode() == Instruction::SetEQ ||
1701 I.getOpcode() == Instruction::SetNE)) {
1702 // We keep moving the cast from the left operand over to the right
1703 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00001704 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00001705
1706 // If operand #1 is a cast instruction, see if we can eliminate it as
1707 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00001708 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
1709 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00001710 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00001711 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00001712
1713 // If Op1 is a constant, we can fold the cast into the constant.
1714 if (Op1->getType() != Op0->getType())
1715 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1716 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
1717 } else {
1718 // Otherwise, cast the RHS right before the setcc
1719 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
1720 InsertNewInstBefore(cast<Instruction>(Op1), I);
1721 }
1722 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
1723 }
1724
Chris Lattner6444c372003-11-03 05:17:03 +00001725 // Handle the special case of: setcc (cast bool to X), <cst>
1726 // This comes up when you have code like
1727 // int X = A < B;
1728 // if (X) ...
1729 // For generality, we handle any zero-extension of any operand comparison
1730 // with a constant.
1731 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
1732 const Type *SrcTy = CastOp0->getType();
1733 const Type *DestTy = Op0->getType();
1734 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
1735 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
1736 // Ok, we have an expansion of operand 0 into a new type. Get the
1737 // constant value, masink off bits which are not set in the RHS. These
1738 // could be set if the destination value is signed.
1739 uint64_t ConstVal = ConstantRHS->getRawValue();
1740 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
1741
1742 // If the constant we are comparing it with has high bits set, which
1743 // don't exist in the original value, the values could never be equal,
1744 // because the source would be zero extended.
1745 unsigned SrcBits =
1746 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00001747 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
1748 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00001749 switch (I.getOpcode()) {
1750 default: assert(0 && "Unknown comparison type!");
1751 case Instruction::SetEQ:
1752 return ReplaceInstUsesWith(I, ConstantBool::False);
1753 case Instruction::SetNE:
1754 return ReplaceInstUsesWith(I, ConstantBool::True);
1755 case Instruction::SetLT:
1756 case Instruction::SetLE:
1757 if (DestTy->isSigned() && HasSignBit)
1758 return ReplaceInstUsesWith(I, ConstantBool::False);
1759 return ReplaceInstUsesWith(I, ConstantBool::True);
1760 case Instruction::SetGT:
1761 case Instruction::SetGE:
1762 if (DestTy->isSigned() && HasSignBit)
1763 return ReplaceInstUsesWith(I, ConstantBool::True);
1764 return ReplaceInstUsesWith(I, ConstantBool::False);
1765 }
1766 }
1767
1768 // Otherwise, we can replace the setcc with a setcc of the smaller
1769 // operand value.
1770 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
1771 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
1772 }
1773 }
1774 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001775 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001776}
1777
1778
1779
Chris Lattnere8d6c602003-03-10 19:16:08 +00001780Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001781 assert(I.getOperand(1)->getType() == Type::UByteTy);
1782 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001783 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001784
1785 // shl X, 0 == X and shr X, 0 == X
1786 // shl 0, X == 0 and shr 0, X == 0
1787 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00001788 Op0 == Constant::getNullValue(Op0->getType()))
1789 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001790
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001791 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
1792 if (!isLeftShift)
1793 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1794 if (CSI->isAllOnesValue())
1795 return ReplaceInstUsesWith(I, CSI);
1796
Chris Lattner183b3362004-04-09 19:05:30 +00001797 // Try to fold constant and into select arguments.
1798 if (isa<Constant>(Op0))
1799 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1800 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1801 return R;
1802
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001803 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001804 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1805 // of a signed value.
1806 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00001807 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00001808 if (CUI->getValue() >= TypeBits) {
1809 if (!Op0->getType()->isSigned() || isLeftShift)
1810 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
1811 else {
1812 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
1813 return &I;
1814 }
1815 }
Chris Lattner55f3d942002-09-10 23:04:09 +00001816
Chris Lattnerede3fe02003-08-13 04:18:28 +00001817 // ((X*C1) << C2) == (X * (C1 << C2))
1818 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1819 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1820 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001821 return BinaryOperator::createMul(BO->getOperand(0),
1822 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00001823
Chris Lattner183b3362004-04-09 19:05:30 +00001824 // Try to fold constant and into select arguments.
1825 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1826 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1827 return R;
Chris Lattnerede3fe02003-08-13 04:18:28 +00001828
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001829 // If the operand is an bitwise operator with a constant RHS, and the
1830 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001831 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001832 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1833 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1834 bool isValid = true; // Valid only for And, Or, Xor
1835 bool highBitSet = false; // Transform if high bit of constant set?
1836
1837 switch (Op0BO->getOpcode()) {
1838 default: isValid = false; break; // Do not perform transform!
1839 case Instruction::Or:
1840 case Instruction::Xor:
1841 highBitSet = false;
1842 break;
1843 case Instruction::And:
1844 highBitSet = true;
1845 break;
1846 }
1847
1848 // If this is a signed shift right, and the high bit is modified
1849 // by the logical operation, do not perform the transformation.
1850 // The highBitSet boolean indicates the value of the high bit of
1851 // the constant which would cause it to be modified for this
1852 // operation.
1853 //
1854 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1855 uint64_t Val = Op0C->getRawValue();
1856 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1857 }
1858
1859 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001860 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001861
1862 Instruction *NewShift =
1863 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1864 Op0BO->getName());
1865 Op0BO->setName("");
1866 InsertNewInstBefore(NewShift, I);
1867
1868 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1869 NewRHS);
1870 }
1871 }
1872
Chris Lattner3204d4e2003-07-24 17:52:58 +00001873 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001874 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00001875 if (ConstantUInt *ShiftAmt1C =
1876 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001877 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1878 unsigned ShiftAmt2 = CUI->getValue();
1879
1880 // Check for (A << c1) << c2 and (A >> c1) >> c2
1881 if (I.getOpcode() == Op0SI->getOpcode()) {
1882 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00001883 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
1884 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00001885 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1886 ConstantUInt::get(Type::UByteTy, Amt));
1887 }
1888
Chris Lattnerab780df2003-07-24 18:38:56 +00001889 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1890 // signed types, we can only support the (A >> c1) << c2 configuration,
1891 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001892 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001893 // Calculate bitmask for what gets shifted off the edge...
1894 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001895 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001896 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001897 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001898 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00001899
1900 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001901 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
1902 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00001903 InsertNewInstBefore(Mask, I);
1904
1905 // Figure out what flavor of shift we should use...
1906 if (ShiftAmt1 == ShiftAmt2)
1907 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
1908 else if (ShiftAmt1 < ShiftAmt2) {
1909 return new ShiftInst(I.getOpcode(), Mask,
1910 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1911 } else {
1912 return new ShiftInst(Op0SI->getOpcode(), Mask,
1913 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1914 }
1915 }
1916 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001917 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00001918
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001919 return 0;
1920}
1921
1922
Chris Lattner48a44f72002-05-02 17:06:02 +00001923// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1924// instruction.
1925//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001926static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1927 const Type *DstTy) {
Chris Lattner48a44f72002-05-02 17:06:02 +00001928
Chris Lattner650b6da2002-08-02 20:00:25 +00001929 // It is legal to eliminate the instruction if casting A->B->A if the sizes
1930 // are identical and the bits don't get reinterpreted (for example
Chris Lattner0bb75912002-08-14 23:21:10 +00001931 // int->float->int would not be allowed)
Misha Brukmane5838c42003-05-20 18:45:36 +00001932 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00001933 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00001934
1935 // Allow free casting and conversion of sizes as long as the sign doesn't
1936 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00001937 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00001938 unsigned SrcSize = SrcTy->getPrimitiveSize();
1939 unsigned MidSize = MidTy->getPrimitiveSize();
1940 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner650b6da2002-08-02 20:00:25 +00001941
Chris Lattner3732aca2002-08-15 16:15:25 +00001942 // Cases where we are monotonically decreasing the size of the type are
1943 // always ok, regardless of what sign changes are going on.
1944 //
Chris Lattner0bb75912002-08-14 23:21:10 +00001945 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +00001946 return true;
Chris Lattner3732aca2002-08-15 16:15:25 +00001947
Chris Lattner555518c2002-09-23 23:39:43 +00001948 // Cases where the source and destination type are the same, but the middle
1949 // type is bigger are noops.
1950 //
1951 if (SrcSize == DstSize && MidSize > SrcSize)
1952 return true;
1953
Chris Lattner3732aca2002-08-15 16:15:25 +00001954 // If we are monotonically growing, things are more complex.
1955 //
1956 if (SrcSize <= MidSize && MidSize <= DstSize) {
1957 // We have eight combinations of signedness to worry about. Here's the
1958 // table:
1959 static const int SignTable[8] = {
1960 // CODE, SrcSigned, MidSigned, DstSigned, Comment
1961 1, // U U U Always ok
1962 1, // U U S Always ok
1963 3, // U S U Ok iff SrcSize != MidSize
1964 3, // U S S Ok iff SrcSize != MidSize
1965 0, // S U U Never ok
1966 2, // S U S Ok iff MidSize == DstSize
1967 1, // S S U Always ok
1968 1, // S S S Always ok
1969 };
1970
1971 // Choose an action based on the current entry of the signtable that this
1972 // cast of cast refers to...
1973 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1974 switch (SignTable[Row]) {
1975 case 0: return false; // Never ok
1976 case 1: return true; // Always ok
1977 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1978 case 3: // Ok iff SrcSize != MidSize
1979 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1980 default: assert(0 && "Bad entry in sign table!");
1981 }
Chris Lattner3732aca2002-08-15 16:15:25 +00001982 }
Chris Lattner650b6da2002-08-02 20:00:25 +00001983 }
Chris Lattner48a44f72002-05-02 17:06:02 +00001984
1985 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1986 // like: short -> ushort -> uint, because this can create wrong results if
1987 // the input short is negative!
1988 //
1989 return false;
1990}
1991
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001992static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1993 if (V->getType() == Ty || isa<Constant>(V)) return false;
1994 if (const CastInst *CI = dyn_cast<CastInst>(V))
1995 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1996 return false;
1997 return true;
1998}
1999
2000/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2001/// InsertBefore instruction. This is specialized a bit to avoid inserting
2002/// casts that are known to not do anything...
2003///
2004Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2005 Instruction *InsertBefore) {
2006 if (V->getType() == DestTy) return V;
2007 if (Constant *C = dyn_cast<Constant>(V))
2008 return ConstantExpr::getCast(C, DestTy);
2009
2010 CastInst *CI = new CastInst(V, DestTy, V->getName());
2011 InsertNewInstBefore(CI, *InsertBefore);
2012 return CI;
2013}
Chris Lattner48a44f72002-05-02 17:06:02 +00002014
2015// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002016//
Chris Lattner113f4f42002-06-25 16:13:24 +00002017Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002018 Value *Src = CI.getOperand(0);
2019
Chris Lattner48a44f72002-05-02 17:06:02 +00002020 // If the user is casting a value to the same type, eliminate this cast
2021 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002022 if (CI.getType() == Src->getType())
2023 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002024
Chris Lattner48a44f72002-05-02 17:06:02 +00002025 // If casting the result of another cast instruction, try to eliminate this
2026 // one!
2027 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002028 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002029 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
2030 CSrc->getType(), CI.getType())) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002031 // This instruction now refers directly to the cast's src operand. This
2032 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002033 CI.setOperand(0, CSrc->getOperand(0));
2034 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002035 }
2036
Chris Lattner650b6da2002-08-02 20:00:25 +00002037 // If this is an A->B->A cast, and we are dealing with integral types, try
2038 // to convert this into a logical 'and' instruction.
2039 //
2040 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002041 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002042 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2043 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2044 assert(CSrc->getType() != Type::ULongTy &&
2045 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002046 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002047 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002048 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002049 }
2050 }
2051
Chris Lattner03841652004-05-25 04:29:21 +00002052 // If this is a cast to bool, turn it into the appropriate setne instruction.
2053 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002054 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002055 Constant::getNullValue(CI.getOperand(0)->getType()));
2056
Chris Lattnerd0d51602003-06-21 23:12:02 +00002057 // If casting the result of a getelementptr instruction with no offset, turn
2058 // this into a cast of the original pointer!
2059 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002060 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002061 bool AllZeroOperands = true;
2062 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2063 if (!isa<Constant>(GEP->getOperand(i)) ||
2064 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2065 AllZeroOperands = false;
2066 break;
2067 }
2068 if (AllZeroOperands) {
2069 CI.setOperand(0, GEP->getOperand(0));
2070 return &CI;
2071 }
2072 }
2073
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002074 // If we are casting a malloc or alloca to a pointer to a type of the same
2075 // size, rewrite the allocation instruction to allocate the "right" type.
2076 //
2077 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002078 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002079 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2080 // Get the type really allocated and the type casted to...
2081 const Type *AllocElTy = AI->getAllocatedType();
2082 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2083 const Type *CastElTy = PTy->getElementType();
2084 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002085
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002086 // If the allocation is for an even multiple of the cast type size
Chris Lattneraf789322003-11-03 01:29:41 +00002087 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002088 Value *Amt = ConstantUInt::get(Type::UIntTy,
2089 AllocElTySize/CastElTySize);
2090 std::string Name = AI->getName(); AI->setName("");
2091 AllocationInst *New;
2092 if (isa<MallocInst>(AI))
2093 New = new MallocInst(CastElTy, Amt, Name);
2094 else
2095 New = new AllocaInst(CastElTy, Amt, Name);
Chris Lattner652064e2004-04-30 04:37:52 +00002096 InsertNewInstBefore(New, *AI);
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002097 return ReplaceInstUsesWith(CI, New);
2098 }
2099 }
2100
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002101 // If the source value is an instruction with only this use, we can attempt to
2102 // propagate the cast into the instruction. Also, only handle integral types
2103 // for now.
2104 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002105 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002106 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2107 const Type *DestTy = CI.getType();
2108 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2109 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2110
2111 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2112 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2113
2114 switch (SrcI->getOpcode()) {
2115 case Instruction::Add:
2116 case Instruction::Mul:
2117 case Instruction::And:
2118 case Instruction::Or:
2119 case Instruction::Xor:
2120 // If we are discarding information, or just changing the sign, rewrite.
2121 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2122 // Don't insert two casts if they cannot be eliminated. We allow two
2123 // casts to be inserted if the sizes are the same. This could only be
2124 // converting signedness, which is a noop.
2125 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
2126 !ValueRequiresCast(Op0, DestTy)) {
2127 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2128 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2129 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2130 ->getOpcode(), Op0c, Op1c);
2131 }
2132 }
2133 break;
2134 case Instruction::Shl:
2135 // Allow changing the sign of the source operand. Do not allow changing
2136 // the size of the shift, UNLESS the shift amount is a constant. We
2137 // mush not change variable sized shifts to a smaller size, because it
2138 // is undefined to shift more bits out than exist in the value.
2139 if (DestBitSize == SrcBitSize ||
2140 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2141 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2142 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2143 }
2144 break;
2145 }
2146 }
2147
Chris Lattner260ab202002-04-18 17:39:14 +00002148 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00002149}
2150
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002151/// GetSelectFoldableOperands - We want to turn code that looks like this:
2152/// %C = or %A, %B
2153/// %D = select %cond, %C, %A
2154/// into:
2155/// %C = select %cond, %B, 0
2156/// %D = or %A, %C
2157///
2158/// Assuming that the specified instruction is an operand to the select, return
2159/// a bitmask indicating which operands of this instruction are foldable if they
2160/// equal the other incoming value of the select.
2161///
2162static unsigned GetSelectFoldableOperands(Instruction *I) {
2163 switch (I->getOpcode()) {
2164 case Instruction::Add:
2165 case Instruction::Mul:
2166 case Instruction::And:
2167 case Instruction::Or:
2168 case Instruction::Xor:
2169 return 3; // Can fold through either operand.
2170 case Instruction::Sub: // Can only fold on the amount subtracted.
2171 case Instruction::Shl: // Can only fold on the shift amount.
2172 case Instruction::Shr:
2173 return 1;
2174 default:
2175 return 0; // Cannot fold
2176 }
2177}
2178
2179/// GetSelectFoldableConstant - For the same transformation as the previous
2180/// function, return the identity constant that goes into the select.
2181static Constant *GetSelectFoldableConstant(Instruction *I) {
2182 switch (I->getOpcode()) {
2183 default: assert(0 && "This cannot happen!"); abort();
2184 case Instruction::Add:
2185 case Instruction::Sub:
2186 case Instruction::Or:
2187 case Instruction::Xor:
2188 return Constant::getNullValue(I->getType());
2189 case Instruction::Shl:
2190 case Instruction::Shr:
2191 return Constant::getNullValue(Type::UByteTy);
2192 case Instruction::And:
2193 return ConstantInt::getAllOnesValue(I->getType());
2194 case Instruction::Mul:
2195 return ConstantInt::get(I->getType(), 1);
2196 }
2197}
2198
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002199Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00002200 Value *CondVal = SI.getCondition();
2201 Value *TrueVal = SI.getTrueValue();
2202 Value *FalseVal = SI.getFalseValue();
2203
2204 // select true, X, Y -> X
2205 // select false, X, Y -> Y
2206 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002207 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00002208 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002209 else {
2210 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00002211 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002212 }
Chris Lattner533bc492004-03-30 19:37:13 +00002213
2214 // select C, X, X -> X
2215 if (TrueVal == FalseVal)
2216 return ReplaceInstUsesWith(SI, TrueVal);
2217
Chris Lattner1c631e82004-04-08 04:43:23 +00002218 if (SI.getType() == Type::BoolTy)
2219 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2220 if (C == ConstantBool::True) {
2221 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002222 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002223 } else {
2224 // Change: A = select B, false, C --> A = and !B, C
2225 Value *NotCond =
2226 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2227 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002228 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002229 }
2230 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2231 if (C == ConstantBool::False) {
2232 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002233 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002234 } else {
2235 // Change: A = select B, C, true --> A = or !B, C
2236 Value *NotCond =
2237 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2238 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002239 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002240 }
2241 }
2242
Chris Lattner183b3362004-04-09 19:05:30 +00002243 // Selecting between two integer constants?
2244 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2245 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2246 // select C, 1, 0 -> cast C to int
2247 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2248 return new CastInst(CondVal, SI.getType());
2249 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2250 // select C, 0, 1 -> cast !C to int
2251 Value *NotCond =
2252 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00002253 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00002254 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00002255 }
Chris Lattner35167c32004-06-09 07:59:58 +00002256
2257 // If one of the constants is zero (we know they can't both be) and we
2258 // have a setcc instruction with zero, and we have an 'and' with the
2259 // non-constant value, eliminate this whole mess. This corresponds to
2260 // cases like this: ((X & 27) ? 27 : 0)
2261 if (TrueValC->isNullValue() || FalseValC->isNullValue())
2262 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
2263 if ((IC->getOpcode() == Instruction::SetEQ ||
2264 IC->getOpcode() == Instruction::SetNE) &&
2265 isa<ConstantInt>(IC->getOperand(1)) &&
2266 cast<Constant>(IC->getOperand(1))->isNullValue())
2267 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
2268 if (ICA->getOpcode() == Instruction::And &&
2269 isa<ConstantInt>(ICA->getOperand(1)) &&
2270 (ICA->getOperand(1) == TrueValC ||
2271 ICA->getOperand(1) == FalseValC) &&
2272 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
2273 // Okay, now we know that everything is set up, we just don't
2274 // know whether we have a setne or seteq and whether the true or
2275 // false val is the zero.
2276 bool ShouldNotVal = !TrueValC->isNullValue();
2277 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
2278 Value *V = ICA;
2279 if (ShouldNotVal)
2280 V = InsertNewInstBefore(BinaryOperator::create(
2281 Instruction::Xor, V, ICA->getOperand(1)), SI);
2282 return ReplaceInstUsesWith(SI, V);
2283 }
Chris Lattner533bc492004-03-30 19:37:13 +00002284 }
Chris Lattner623fba12004-04-10 22:21:27 +00002285
2286 // See if we are selecting two values based on a comparison of the two values.
2287 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
2288 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
2289 // Transform (X == Y) ? X : Y -> Y
2290 if (SCI->getOpcode() == Instruction::SetEQ)
2291 return ReplaceInstUsesWith(SI, FalseVal);
2292 // Transform (X != Y) ? X : Y -> X
2293 if (SCI->getOpcode() == Instruction::SetNE)
2294 return ReplaceInstUsesWith(SI, TrueVal);
2295 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2296
2297 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
2298 // Transform (X == Y) ? Y : X -> X
2299 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00002300 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00002301 // Transform (X != Y) ? Y : X -> Y
2302 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00002303 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00002304 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2305 }
2306 }
Chris Lattner1c631e82004-04-08 04:43:23 +00002307
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002308 // See if we can fold the select into one of our operands.
2309 if (SI.getType()->isInteger()) {
2310 // See the comment above GetSelectFoldableOperands for a description of the
2311 // transformation we are doing here.
2312 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
2313 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
2314 !isa<Constant>(FalseVal))
2315 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
2316 unsigned OpToFold = 0;
2317 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
2318 OpToFold = 1;
2319 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
2320 OpToFold = 2;
2321 }
2322
2323 if (OpToFold) {
2324 Constant *C = GetSelectFoldableConstant(TVI);
2325 std::string Name = TVI->getName(); TVI->setName("");
2326 Instruction *NewSel =
2327 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
2328 Name);
2329 InsertNewInstBefore(NewSel, SI);
2330 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
2331 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
2332 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
2333 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
2334 else {
2335 assert(0 && "Unknown instruction!!");
2336 }
2337 }
2338 }
2339
2340 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
2341 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
2342 !isa<Constant>(TrueVal))
2343 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
2344 unsigned OpToFold = 0;
2345 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
2346 OpToFold = 1;
2347 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
2348 OpToFold = 2;
2349 }
2350
2351 if (OpToFold) {
2352 Constant *C = GetSelectFoldableConstant(FVI);
2353 std::string Name = FVI->getName(); FVI->setName("");
2354 Instruction *NewSel =
2355 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
2356 Name);
2357 InsertNewInstBefore(NewSel, SI);
2358 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
2359 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
2360 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
2361 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
2362 else {
2363 assert(0 && "Unknown instruction!!");
2364 }
2365 }
2366 }
2367 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002368 return 0;
2369}
2370
2371
Chris Lattner970c33a2003-06-19 17:00:31 +00002372// CallInst simplification
2373//
2374Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00002375 // Intrinsics cannot occur in an invoke, so handle them here instead of in
2376 // visitCallSite.
2377 if (Function *F = CI.getCalledFunction())
2378 switch (F->getIntrinsicID()) {
2379 case Intrinsic::memmove:
2380 case Intrinsic::memcpy:
2381 case Intrinsic::memset:
2382 // memmove/cpy/set of zero bytes is a noop.
2383 if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
2384 if (NumBytes->isNullValue())
2385 return EraseInstFromFunction(CI);
2386 }
2387 break;
2388 default:
2389 break;
2390 }
2391
Chris Lattneraec3d942003-10-07 22:32:43 +00002392 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00002393}
2394
2395// InvokeInst simplification
2396//
2397Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00002398 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00002399}
2400
Chris Lattneraec3d942003-10-07 22:32:43 +00002401// visitCallSite - Improvements for call and invoke instructions.
2402//
2403Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002404 bool Changed = false;
2405
2406 // If the callee is a constexpr cast of a function, attempt to move the cast
2407 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00002408 if (transformConstExprCastCall(CS)) return 0;
2409
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002410 Value *Callee = CS.getCalledValue();
2411 const PointerType *PTy = cast<PointerType>(Callee->getType());
2412 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2413 if (FTy->isVarArg()) {
2414 // See if we can optimize any arguments passed through the varargs area of
2415 // the call.
2416 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
2417 E = CS.arg_end(); I != E; ++I)
2418 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
2419 // If this cast does not effect the value passed through the varargs
2420 // area, we can eliminate the use of the cast.
2421 Value *Op = CI->getOperand(0);
2422 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
2423 *I = Op;
2424 Changed = true;
2425 }
2426 }
2427 }
Chris Lattneraec3d942003-10-07 22:32:43 +00002428
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002429 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00002430}
2431
Chris Lattner970c33a2003-06-19 17:00:31 +00002432// transformConstExprCastCall - If the callee is a constexpr cast of a function,
2433// attempt to move the cast to the arguments of the call/invoke.
2434//
2435bool InstCombiner::transformConstExprCastCall(CallSite CS) {
2436 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
2437 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
2438 if (CE->getOpcode() != Instruction::Cast ||
2439 !isa<ConstantPointerRef>(CE->getOperand(0)))
2440 return false;
2441 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
2442 if (!isa<Function>(CPR->getValue())) return false;
2443 Function *Callee = cast<Function>(CPR->getValue());
2444 Instruction *Caller = CS.getInstruction();
2445
2446 // Okay, this is a cast from a function to a different type. Unless doing so
2447 // would cause a type conversion of one of our arguments, change this call to
2448 // be a direct call with arguments casted to the appropriate types.
2449 //
2450 const FunctionType *FT = Callee->getFunctionType();
2451 const Type *OldRetTy = Caller->getType();
2452
Chris Lattner1f7942f2004-01-14 06:06:08 +00002453 // Check to see if we are changing the return type...
2454 if (OldRetTy != FT->getReturnType()) {
2455 if (Callee->isExternal() &&
2456 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
2457 !Caller->use_empty())
2458 return false; // Cannot transform this return value...
2459
2460 // If the callsite is an invoke instruction, and the return value is used by
2461 // a PHI node in a successor, we cannot change the return type of the call
2462 // because there is no place to put the cast instruction (without breaking
2463 // the critical edge). Bail out in this case.
2464 if (!Caller->use_empty())
2465 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
2466 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
2467 UI != E; ++UI)
2468 if (PHINode *PN = dyn_cast<PHINode>(*UI))
2469 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00002470 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00002471 return false;
2472 }
Chris Lattner970c33a2003-06-19 17:00:31 +00002473
2474 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
2475 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2476
2477 CallSite::arg_iterator AI = CS.arg_begin();
2478 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
2479 const Type *ParamTy = FT->getParamType(i);
2480 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
2481 if (Callee->isExternal() && !isConvertible) return false;
2482 }
2483
2484 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
2485 Callee->isExternal())
2486 return false; // Do not delete arguments unless we have a function body...
2487
2488 // Okay, we decided that this is a safe thing to do: go ahead and start
2489 // inserting cast instructions as necessary...
2490 std::vector<Value*> Args;
2491 Args.reserve(NumActualArgs);
2492
2493 AI = CS.arg_begin();
2494 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
2495 const Type *ParamTy = FT->getParamType(i);
2496 if ((*AI)->getType() == ParamTy) {
2497 Args.push_back(*AI);
2498 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00002499 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
2500 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00002501 }
2502 }
2503
2504 // If the function takes more arguments than the call was taking, add them
2505 // now...
2506 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2507 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2508
2509 // If we are removing arguments to the function, emit an obnoxious warning...
2510 if (FT->getNumParams() < NumActualArgs)
2511 if (!FT->isVarArg()) {
2512 std::cerr << "WARNING: While resolving call to function '"
2513 << Callee->getName() << "' arguments were dropped!\n";
2514 } else {
2515 // Add all of the arguments in their promoted form to the arg list...
2516 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
2517 const Type *PTy = getPromotedType((*AI)->getType());
2518 if (PTy != (*AI)->getType()) {
2519 // Must promote to pass through va_arg area!
2520 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
2521 InsertNewInstBefore(Cast, *Caller);
2522 Args.push_back(Cast);
2523 } else {
2524 Args.push_back(*AI);
2525 }
2526 }
2527 }
2528
2529 if (FT->getReturnType() == Type::VoidTy)
2530 Caller->setName(""); // Void type should not have a name...
2531
2532 Instruction *NC;
2533 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00002534 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00002535 Args, Caller->getName(), Caller);
2536 } else {
2537 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
2538 }
2539
2540 // Insert a cast of the return type as necessary...
2541 Value *NV = NC;
2542 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
2543 if (NV->getType() != Type::VoidTy) {
2544 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00002545
2546 // If this is an invoke instruction, we should insert it after the first
2547 // non-phi, instruction in the normal successor block.
2548 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
2549 BasicBlock::iterator I = II->getNormalDest()->begin();
2550 while (isa<PHINode>(I)) ++I;
2551 InsertNewInstBefore(NC, *I);
2552 } else {
2553 // Otherwise, it's a call, just insert cast right after the call instr
2554 InsertNewInstBefore(NC, *Caller);
2555 }
Chris Lattner51ea1272004-02-28 05:22:00 +00002556 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00002557 } else {
2558 NV = Constant::getNullValue(Caller->getType());
2559 }
2560 }
2561
2562 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
2563 Caller->replaceAllUsesWith(NV);
2564 Caller->getParent()->getInstList().erase(Caller);
2565 removeFromWorkList(Caller);
2566 return true;
2567}
2568
2569
Chris Lattner48a44f72002-05-02 17:06:02 +00002570
Chris Lattnerbbbdd852002-05-06 18:06:38 +00002571// PHINode simplification
2572//
Chris Lattner113f4f42002-06-25 16:13:24 +00002573Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner91daeb52003-12-19 05:58:40 +00002574 if (Value *V = hasConstantValue(&PN))
2575 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00002576
2577 // If the only user of this instruction is a cast instruction, and all of the
2578 // incoming values are constants, change this PHI to merge together the casted
2579 // constants.
2580 if (PN.hasOneUse())
2581 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
2582 if (CI->getType() != PN.getType()) { // noop casts will be folded
2583 bool AllConstant = true;
2584 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2585 if (!isa<Constant>(PN.getIncomingValue(i))) {
2586 AllConstant = false;
2587 break;
2588 }
2589 if (AllConstant) {
2590 // Make a new PHI with all casted values.
2591 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
2592 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2593 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
2594 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
2595 PN.getIncomingBlock(i));
2596 }
2597
2598 // Update the cast instruction.
2599 CI->setOperand(0, New);
2600 WorkList.push_back(CI); // revisit the cast instruction to fold.
2601 WorkList.push_back(New); // Make sure to revisit the new Phi
2602 return &PN; // PN is now dead!
2603 }
2604 }
Chris Lattner91daeb52003-12-19 05:58:40 +00002605 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00002606}
2607
Chris Lattner69193f92004-04-05 01:30:19 +00002608static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
2609 Instruction *InsertPoint,
2610 InstCombiner *IC) {
2611 unsigned PS = IC->getTargetData().getPointerSize();
2612 const Type *VTy = V->getType();
2613 Instruction *Cast;
2614 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
2615 // We must insert a cast to ensure we sign-extend.
2616 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
2617 V->getName()), *InsertPoint);
2618 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
2619 *InsertPoint);
2620}
2621
Chris Lattner48a44f72002-05-02 17:06:02 +00002622
Chris Lattner113f4f42002-06-25 16:13:24 +00002623Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00002624 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00002625 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00002626 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002627 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00002628 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002629
2630 bool HasZeroPointerIndex = false;
2631 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
2632 HasZeroPointerIndex = C->isNullValue();
2633
2634 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00002635 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00002636
Chris Lattner69193f92004-04-05 01:30:19 +00002637 // Eliminate unneeded casts for indices.
2638 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00002639 gep_type_iterator GTI = gep_type_begin(GEP);
2640 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
2641 if (isa<SequentialType>(*GTI)) {
2642 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
2643 Value *Src = CI->getOperand(0);
2644 const Type *SrcTy = Src->getType();
2645 const Type *DestTy = CI->getType();
2646 if (Src->getType()->isInteger()) {
2647 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
2648 // We can always eliminate a cast from ulong or long to the other.
2649 // We can always eliminate a cast from uint to int or the other on
2650 // 32-bit pointer platforms.
2651 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
2652 MadeChange = true;
2653 GEP.setOperand(i, Src);
2654 }
2655 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2656 SrcTy->getPrimitiveSize() == 4) {
2657 // We can always eliminate a cast from int to [u]long. We can
2658 // eliminate a cast from uint to [u]long iff the target is a 32-bit
2659 // pointer target.
2660 if (SrcTy->isSigned() ||
2661 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
2662 MadeChange = true;
2663 GEP.setOperand(i, Src);
2664 }
Chris Lattner69193f92004-04-05 01:30:19 +00002665 }
2666 }
2667 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00002668 // If we are using a wider index than needed for this platform, shrink it
2669 // to what we need. If the incoming value needs a cast instruction,
2670 // insert it. This explicit cast can make subsequent optimizations more
2671 // obvious.
2672 Value *Op = GEP.getOperand(i);
2673 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00002674 if (Constant *C = dyn_cast<Constant>(Op)) {
2675 GEP.setOperand(i, ConstantExpr::getCast(C, TD->getIntPtrType()));
2676 MadeChange = true;
2677 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00002678 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
2679 Op->getName()), GEP);
2680 GEP.setOperand(i, Op);
2681 MadeChange = true;
2682 }
Chris Lattner69193f92004-04-05 01:30:19 +00002683 }
2684 if (MadeChange) return &GEP;
2685
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002686 // Combine Indices - If the source pointer to this getelementptr instruction
2687 // is a getelementptr instruction, combine the indices of the two
2688 // getelementptr instructions into a single instruction.
2689 //
Chris Lattner57c67b02004-03-25 22:59:29 +00002690 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00002691 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00002692 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00002693 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00002694 if (CE->getOpcode() == Instruction::GetElementPtr)
2695 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
2696 }
2697
2698 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00002699 // Note that if our source is a gep chain itself that we wait for that
2700 // chain to be resolved before we perform this transformation. This
2701 // avoids us creating a TON of code in some cases.
2702 //
2703 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
2704 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
2705 return 0; // Wait until our source is folded to completion.
2706
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002707 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00002708
2709 // Find out whether the last index in the source GEP is a sequential idx.
2710 bool EndsWithSequential = false;
2711 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
2712 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00002713 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00002714
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002715 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00002716 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00002717 // Replace: gep (gep %P, long B), long A, ...
2718 // With: T = long A+B; gep %P, T, ...
2719 //
Chris Lattner5f667a62004-05-07 22:09:22 +00002720 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00002721 if (SO1 == Constant::getNullValue(SO1->getType())) {
2722 Sum = GO1;
2723 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
2724 Sum = SO1;
2725 } else {
2726 // If they aren't the same type, convert both to an integer of the
2727 // target's pointer size.
2728 if (SO1->getType() != GO1->getType()) {
2729 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
2730 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
2731 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
2732 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
2733 } else {
2734 unsigned PS = TD->getPointerSize();
2735 Instruction *Cast;
2736 if (SO1->getType()->getPrimitiveSize() == PS) {
2737 // Convert GO1 to SO1's type.
2738 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
2739
2740 } else if (GO1->getType()->getPrimitiveSize() == PS) {
2741 // Convert SO1 to GO1's type.
2742 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
2743 } else {
2744 const Type *PT = TD->getIntPtrType();
2745 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
2746 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
2747 }
2748 }
2749 }
Chris Lattner5f667a62004-05-07 22:09:22 +00002750 if (isa<Constant>(SO1) && isa<Constant>(GO1))
2751 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
2752 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002753 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
2754 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00002755 }
Chris Lattner69193f92004-04-05 01:30:19 +00002756 }
Chris Lattner5f667a62004-05-07 22:09:22 +00002757
2758 // Recycle the GEP we already have if possible.
2759 if (SrcGEPOperands.size() == 2) {
2760 GEP.setOperand(0, SrcGEPOperands[0]);
2761 GEP.setOperand(1, Sum);
2762 return &GEP;
2763 } else {
2764 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2765 SrcGEPOperands.end()-1);
2766 Indices.push_back(Sum);
2767 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
2768 }
Chris Lattner69193f92004-04-05 01:30:19 +00002769 } else if (isa<Constant>(*GEP.idx_begin()) &&
2770 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00002771 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002772 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00002773 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2774 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002775 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
2776 }
2777
2778 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00002779 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002780
Chris Lattner5f667a62004-05-07 22:09:22 +00002781 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002782 // GEP of global variable. If all of the indices for this GEP are
2783 // constants, we can promote this to a constexpr instead of an instruction.
2784
2785 // Scan for nonconstants...
2786 std::vector<Constant*> Indices;
2787 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
2788 for (; I != E && isa<Constant>(*I); ++I)
2789 Indices.push_back(cast<Constant>(*I));
2790
2791 if (I == E) { // If they are all constants...
Chris Lattner46b3d302003-04-16 22:40:51 +00002792 Constant *CE =
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002793 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
2794
2795 // Replace all uses of the GEP with the new constexpr...
2796 return ReplaceInstUsesWith(GEP, CE);
2797 }
Chris Lattner5f667a62004-05-07 22:09:22 +00002798 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002799 if (CE->getOpcode() == Instruction::Cast) {
2800 if (HasZeroPointerIndex) {
2801 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
2802 // into : GEP [10 x ubyte]* X, long 0, ...
2803 //
2804 // This occurs when the program declares an array extern like "int X[];"
2805 //
2806 Constant *X = CE->getOperand(0);
2807 const PointerType *CPTy = cast<PointerType>(CE->getType());
2808 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
2809 if (const ArrayType *XATy =
2810 dyn_cast<ArrayType>(XTy->getElementType()))
2811 if (const ArrayType *CATy =
2812 dyn_cast<ArrayType>(CPTy->getElementType()))
2813 if (CATy->getElementType() == XATy->getElementType()) {
2814 // At this point, we know that the cast source type is a pointer
2815 // to an array of the same type as the destination pointer
2816 // array. Because the array type is never stepped over (there
2817 // is a leading zero) we can fold the cast into this GEP.
2818 GEP.setOperand(0, X);
2819 return &GEP;
2820 }
2821 }
2822 }
Chris Lattnerca081252001-12-14 16:52:21 +00002823 }
2824
Chris Lattnerca081252001-12-14 16:52:21 +00002825 return 0;
2826}
2827
Chris Lattner1085bdf2002-11-04 16:18:53 +00002828Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
2829 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
2830 if (AI.isArrayAllocation()) // Check C != 1
2831 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
2832 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00002833 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00002834
2835 // Create and insert the replacement instruction...
2836 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00002837 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00002838 else {
2839 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00002840 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00002841 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00002842
2843 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00002844
2845 // Scan to the end of the allocation instructions, to skip over a block of
2846 // allocas if possible...
2847 //
2848 BasicBlock::iterator It = New;
2849 while (isa<AllocationInst>(*It)) ++It;
2850
2851 // Now that I is pointing to the first non-allocation-inst in the block,
2852 // insert our getelementptr instruction...
2853 //
Chris Lattner69193f92004-04-05 01:30:19 +00002854 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00002855 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
2856
2857 // Now make everything use the getelementptr instead of the original
2858 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00002859 return ReplaceInstUsesWith(AI, V);
Chris Lattner1085bdf2002-11-04 16:18:53 +00002860 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00002861
2862 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
2863 // Note that we only do this for alloca's, because malloc should allocate and
2864 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00002865 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
2866 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00002867 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
2868
Chris Lattner1085bdf2002-11-04 16:18:53 +00002869 return 0;
2870}
2871
Chris Lattner8427bff2003-12-07 01:24:23 +00002872Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
2873 Value *Op = FI.getOperand(0);
2874
2875 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
2876 if (CastInst *CI = dyn_cast<CastInst>(Op))
2877 if (isa<PointerType>(CI->getOperand(0)->getType())) {
2878 FI.setOperand(0, CI->getOperand(0));
2879 return &FI;
2880 }
2881
Chris Lattnerf3a36602004-02-28 04:57:37 +00002882 // If we have 'free null' delete the instruction. This can happen in stl code
2883 // when lots of inlining happens.
Chris Lattner51ea1272004-02-28 05:22:00 +00002884 if (isa<ConstantPointerNull>(Op))
2885 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00002886
Chris Lattner8427bff2003-12-07 01:24:23 +00002887 return 0;
2888}
2889
2890
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002891/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
2892/// constantexpr, return the constant value being addressed by the constant
2893/// expression, or null if something is funny.
2894///
2895static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00002896 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002897 return 0; // Do not allow stepping over the value!
2898
2899 // Loop over all of the operands, tracking down which value we are
2900 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00002901 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2902 for (++I; I != E; ++I)
2903 if (const StructType *STy = dyn_cast<StructType>(*I)) {
2904 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
2905 assert(CU->getValue() < STy->getNumElements() &&
2906 "Struct index out of range!");
2907 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
2908 C = cast<Constant>(CS->getValues()[CU->getValue()]);
2909 } else if (isa<ConstantAggregateZero>(C)) {
2910 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
2911 } else {
2912 return 0;
2913 }
2914 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
2915 const ArrayType *ATy = cast<ArrayType>(*I);
2916 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
2917 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
2918 C = cast<Constant>(CA->getValues()[CI->getRawValue()]);
2919 else if (isa<ConstantAggregateZero>(C))
2920 C = Constant::getNullValue(ATy->getElementType());
2921 else
2922 return 0;
2923 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002924 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00002925 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002926 return C;
2927}
2928
2929Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
2930 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00002931 if (LI.isVolatile()) return 0;
2932
Chris Lattner6679e462004-04-14 03:28:36 +00002933 if (Constant *C = dyn_cast<Constant>(Op))
2934 if (C->isNullValue()) // load null -> 0
2935 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
2936 else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C))
2937 Op = CPR->getValue();
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002938
2939 // Instcombine load (constant global) into the value loaded...
2940 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002941 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002942 return ReplaceInstUsesWith(LI, GV->getInitializer());
2943
2944 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
2945 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
2946 if (CE->getOpcode() == Instruction::GetElementPtr)
2947 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
2948 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002949 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002950 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
2951 return ReplaceInstUsesWith(LI, V);
Chris Lattnere228ee52004-04-08 20:39:49 +00002952
2953 // load (cast X) --> cast (load X) iff safe
2954 if (CastInst *CI = dyn_cast<CastInst>(Op)) {
2955 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
2956 if (const PointerType *SrcTy =
2957 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
2958 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerd9e58132004-05-07 15:35:56 +00002959 if (SrcPTy->isSized() && DestPTy->isSized() &&
2960 TD->getTypeSize(SrcPTy) == TD->getTypeSize(DestPTy) &&
Chris Lattnere228ee52004-04-08 20:39:49 +00002961 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
2962 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
2963 // Okay, we are casting from one integer or pointer type to another of
2964 // the same size. Instead of casting the pointer before the load, cast
2965 // the result of the loaded value.
2966 Value *NewLoad = InsertNewInstBefore(new LoadInst(CI->getOperand(0),
2967 CI->getName()), LI);
2968 // Now cast the result of the load.
2969 return new CastInst(NewLoad, LI.getType());
2970 }
2971 }
2972 }
2973
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002974 return 0;
2975}
2976
2977
Chris Lattner9eef8a72003-06-04 04:46:00 +00002978Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2979 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattner4f7acca2004-02-27 06:27:46 +00002980 if (BI.isConditional() && !isa<Constant>(BI.getCondition())) {
Chris Lattnere967b342003-06-04 05:10:11 +00002981 if (Value *V = dyn_castNotVal(BI.getCondition())) {
2982 BasicBlock *TrueDest = BI.getSuccessor(0);
2983 BasicBlock *FalseDest = BI.getSuccessor(1);
2984 // Swap Destinations and condition...
2985 BI.setCondition(V);
2986 BI.setSuccessor(0, FalseDest);
2987 BI.setSuccessor(1, TrueDest);
2988 return &BI;
Chris Lattner4f7acca2004-02-27 06:27:46 +00002989 } else if (SetCondInst *I = dyn_cast<SetCondInst>(BI.getCondition())) {
2990 // Cannonicalize setne -> seteq
2991 if ((I->getOpcode() == Instruction::SetNE ||
2992 I->getOpcode() == Instruction::SetLE ||
2993 I->getOpcode() == Instruction::SetGE) && I->hasOneUse()) {
2994 std::string Name = I->getName(); I->setName("");
2995 Instruction::BinaryOps NewOpcode =
2996 SetCondInst::getInverseCondition(I->getOpcode());
2997 Value *NewSCC = BinaryOperator::create(NewOpcode, I->getOperand(0),
2998 I->getOperand(1), Name, I);
2999 BasicBlock *TrueDest = BI.getSuccessor(0);
3000 BasicBlock *FalseDest = BI.getSuccessor(1);
3001 // Swap Destinations and condition...
3002 BI.setCondition(NewSCC);
3003 BI.setSuccessor(0, FalseDest);
3004 BI.setSuccessor(1, TrueDest);
3005 removeFromWorkList(I);
3006 I->getParent()->getInstList().erase(I);
3007 WorkList.push_back(cast<Instruction>(NewSCC));
3008 return &BI;
3009 }
Chris Lattnere967b342003-06-04 05:10:11 +00003010 }
Chris Lattner4f7acca2004-02-27 06:27:46 +00003011 }
Chris Lattner9eef8a72003-06-04 04:46:00 +00003012 return 0;
3013}
Chris Lattner1085bdf2002-11-04 16:18:53 +00003014
Chris Lattner4c9c20a2004-07-03 00:26:11 +00003015Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3016 Value *Cond = SI.getCondition();
3017 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3018 if (I->getOpcode() == Instruction::Add)
3019 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3020 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3021 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
3022 SI.setOperand(i, ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
3023 AddRHS));
3024 SI.setOperand(0, I->getOperand(0));
3025 WorkList.push_back(I);
3026 return &SI;
3027 }
3028 }
3029 return 0;
3030}
3031
Chris Lattnerca081252001-12-14 16:52:21 +00003032
Chris Lattner99f48c62002-09-02 04:59:56 +00003033void InstCombiner::removeFromWorkList(Instruction *I) {
3034 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3035 WorkList.end());
3036}
3037
Chris Lattner113f4f42002-06-25 16:13:24 +00003038bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00003039 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003040 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00003041
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003042 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3043 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00003044
Chris Lattnerca081252001-12-14 16:52:21 +00003045
3046 while (!WorkList.empty()) {
3047 Instruction *I = WorkList.back(); // Get an instruction from the worklist
3048 WorkList.pop_back();
3049
Misha Brukman632df282002-10-29 23:06:16 +00003050 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00003051 // Check to see if we can DIE the instruction...
3052 if (isInstructionTriviallyDead(I)) {
3053 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003054 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00003055 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00003056 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003057
3058 I->getParent()->getInstList().erase(I);
3059 removeFromWorkList(I);
3060 continue;
3061 }
Chris Lattner99f48c62002-09-02 04:59:56 +00003062
Misha Brukman632df282002-10-29 23:06:16 +00003063 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00003064 if (Constant *C = ConstantFoldInstruction(I)) {
3065 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00003066 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00003067 ReplaceInstUsesWith(*I, C);
3068
Chris Lattner99f48c62002-09-02 04:59:56 +00003069 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003070 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00003071 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003072 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00003073 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003074
Chris Lattner57c67b02004-03-25 22:59:29 +00003075 // Check to see if any of the operands of this instruction are a
3076 // ConstantPointerRef. Since they sneak in all over the place and inhibit
3077 // optimization, we want to strip them out unconditionally!
3078 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3079 if (ConstantPointerRef *CPR =
3080 dyn_cast<ConstantPointerRef>(I->getOperand(i))) {
3081 I->setOperand(i, CPR->getValue());
3082 Changed = true;
3083 }
3084
Chris Lattnerca081252001-12-14 16:52:21 +00003085 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003086 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00003087 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00003088 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00003089 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003090 DEBUG(std::cerr << "IC: Old = " << *I
3091 << " New = " << *Result);
3092
Chris Lattner396dbfe2004-06-09 05:08:07 +00003093 // Everything uses the new instruction now.
3094 I->replaceAllUsesWith(Result);
3095
3096 // Push the new instruction and any users onto the worklist.
3097 WorkList.push_back(Result);
3098 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003099
3100 // Move the name to the new instruction first...
3101 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00003102 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003103
3104 // Insert the new instruction into the basic block...
3105 BasicBlock *InstParent = I->getParent();
3106 InstParent->getInstList().insert(I, Result);
3107
Chris Lattner63d75af2004-05-01 23:27:23 +00003108 // Make sure that we reprocess all operands now that we reduced their
3109 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003110 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3111 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3112 WorkList.push_back(OpI);
3113
Chris Lattner396dbfe2004-06-09 05:08:07 +00003114 // Instructions can end up on the worklist more than once. Make sure
3115 // we do not process an instruction that has been deleted.
3116 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003117
3118 // Erase the old instruction.
3119 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003120 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003121 DEBUG(std::cerr << "IC: MOD = " << *I);
3122
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003123 // If the instruction was modified, it's possible that it is now dead.
3124 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00003125 if (isInstructionTriviallyDead(I)) {
3126 // Make sure we process all operands now that we are reducing their
3127 // use counts.
3128 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3129 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3130 WorkList.push_back(OpI);
3131
3132 // Instructions may end up in the worklist more than once. Erase all
3133 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00003134 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00003135 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00003136 } else {
3137 WorkList.push_back(Result);
3138 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003139 }
Chris Lattner053c0932002-05-14 15:24:07 +00003140 }
Chris Lattner260ab202002-04-18 17:39:14 +00003141 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00003142 }
3143 }
3144
Chris Lattner260ab202002-04-18 17:39:14 +00003145 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00003146}
3147
Chris Lattner8427bff2003-12-07 01:24:23 +00003148Pass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00003149 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00003150}
Brian Gaeke960707c2003-11-11 22:41:34 +00003151