blob: bf5711948640f2ee89d797ce1e753cf16952e837 [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 Lattner260ab202002-04-18 17:39:14 +0000125
126 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000127 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000128
Chris Lattner970c33a2003-06-19 17:00:31 +0000129 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000130 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000131 bool transformConstExprCastCall(CallSite CS);
132
Chris Lattner69193f92004-04-05 01:30:19 +0000133 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000134 // InsertNewInstBefore - insert an instruction New before instruction Old
135 // in the program. Add the new instruction to the worklist.
136 //
Chris Lattnere79e8542004-02-23 06:38:22 +0000137 Value *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000138 assert(New && New->getParent() == 0 &&
139 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000140 BasicBlock *BB = Old.getParent();
141 BB->getInstList().insert(&Old, New); // Insert inst
142 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000143 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000144 }
145
146 // ReplaceInstUsesWith - This method is to be used when an instruction is
147 // found to be dead, replacable with another preexisting expression. Here
148 // we add all uses of I to the worklist, replace all uses of I with the new
149 // value, then return I, so that the inst combiner will know that I was
150 // modified.
151 //
152 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000153 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000154 if (&I != V) {
155 I.replaceAllUsesWith(V);
156 return &I;
157 } else {
158 // If we are replacing the instruction with itself, this must be in a
159 // segment of unreachable code, so just clobber the instruction.
160 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
161 return &I;
162 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000163 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000164
165 // EraseInstFromFunction - When dealing with an instruction that has side
166 // effects or produces a void value, we can't rely on DCE to delete the
167 // instruction. Instead, visit methods should return the value returned by
168 // this function.
169 Instruction *EraseInstFromFunction(Instruction &I) {
170 assert(I.use_empty() && "Cannot erase instruction that is used!");
171 AddUsesToWorkList(I);
172 removeFromWorkList(&I);
173 I.getParent()->getInstList().erase(&I);
174 return 0; // Don't do anything with FI
175 }
176
177
Chris Lattner3ac7c262003-08-13 20:16:26 +0000178 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000179 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
180 /// InsertBefore instruction. This is specialized a bit to avoid inserting
181 /// casts that are known to not do anything...
182 ///
183 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
184 Instruction *InsertBefore);
185
Chris Lattner7fb29e12003-03-11 00:12:48 +0000186 // SimplifyCommutative - This performs a few simplifications for commutative
187 // operators...
188 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000189
190 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
191 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner260ab202002-04-18 17:39:14 +0000192 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000193
Chris Lattnerc8b70922002-07-26 21:12:46 +0000194 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000195}
196
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000197// getComplexity: Assign a complexity or rank value to LLVM Values...
198// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
199static unsigned getComplexity(Value *V) {
200 if (isa<Instruction>(V)) {
201 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
202 return 2;
203 return 3;
204 }
205 if (isa<Argument>(V)) return 2;
206 return isa<Constant>(V) ? 0 : 1;
207}
Chris Lattner260ab202002-04-18 17:39:14 +0000208
Chris Lattner7fb29e12003-03-11 00:12:48 +0000209// isOnlyUse - Return true if this instruction will be deleted if we stop using
210// it.
211static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000212 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000213}
214
Chris Lattnere79e8542004-02-23 06:38:22 +0000215// getPromotedType - Return the specified type promoted as it would be to pass
216// though a va_arg area...
217static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000218 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000219 case Type::SByteTyID:
220 case Type::ShortTyID: return Type::IntTy;
221 case Type::UByteTyID:
222 case Type::UShortTyID: return Type::UIntTy;
223 case Type::FloatTyID: return Type::DoubleTy;
224 default: return Ty;
225 }
226}
227
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000228// SimplifyCommutative - This performs a few simplifications for commutative
229// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000230//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000231// 1. Order operands such that they are listed from right (least complex) to
232// left (most complex). This puts constants before unary operators before
233// binary operators.
234//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000235// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
236// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000237//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000238bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000239 bool Changed = false;
240 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
241 Changed = !I.swapOperands();
242
243 if (!I.isAssociative()) return Changed;
244 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000245 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
246 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
247 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000248 Constant *Folded = ConstantExpr::get(I.getOpcode(),
249 cast<Constant>(I.getOperand(1)),
250 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000251 I.setOperand(0, Op->getOperand(0));
252 I.setOperand(1, Folded);
253 return true;
254 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
255 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
256 isOnlyUse(Op) && isOnlyUse(Op1)) {
257 Constant *C1 = cast<Constant>(Op->getOperand(1));
258 Constant *C2 = cast<Constant>(Op1->getOperand(1));
259
260 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000261 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000262 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
263 Op1->getOperand(0),
264 Op1->getName(), &I);
265 WorkList.push_back(New);
266 I.setOperand(0, New);
267 I.setOperand(1, Folded);
268 return true;
269 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000270 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000271 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000272}
Chris Lattnerca081252001-12-14 16:52:21 +0000273
Chris Lattnerbb74e222003-03-10 23:06:50 +0000274// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
275// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000276//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000277static inline Value *dyn_castNegVal(Value *V) {
278 if (BinaryOperator::isNeg(V))
279 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
280
Chris Lattner9244df62003-04-30 22:19:10 +0000281 // Constants can be considered to be negated values if they can be folded...
282 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000283 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000284 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000285}
286
Chris Lattnerbb74e222003-03-10 23:06:50 +0000287static inline Value *dyn_castNotVal(Value *V) {
288 if (BinaryOperator::isNot(V))
289 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
290
291 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000292 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000293 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000294 return 0;
295}
296
Chris Lattner7fb29e12003-03-11 00:12:48 +0000297// dyn_castFoldableMul - If this value is a multiply that can be folded into
298// other computations (because it has a constant operand), return the
299// non-constant operand of the multiply.
300//
301static inline Value *dyn_castFoldableMul(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000302 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000303 if (Instruction *I = dyn_cast<Instruction>(V))
304 if (I->getOpcode() == Instruction::Mul)
305 if (isa<Constant>(I->getOperand(1)))
306 return I->getOperand(0);
307 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000308}
Chris Lattner31ae8632002-08-14 17:51:49 +0000309
Chris Lattner7fb29e12003-03-11 00:12:48 +0000310// dyn_castMaskingAnd - If this value is an And instruction masking a value with
311// a constant, return the constant being anded with.
312//
Chris Lattner01d56392003-08-12 19:17:27 +0000313template<class ValueType>
314static inline Constant *dyn_castMaskingAnd(ValueType *V) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000315 if (Instruction *I = dyn_cast<Instruction>(V))
316 if (I->getOpcode() == Instruction::And)
317 return dyn_cast<Constant>(I->getOperand(1));
318
319 // If this is a constant, it acts just like we were masking with it.
320 return dyn_cast<Constant>(V);
321}
Chris Lattner3082c5a2003-02-18 19:28:33 +0000322
323// Log2 - Calculate the log base 2 for the specified value if it is exactly a
324// power of 2.
325static unsigned Log2(uint64_t Val) {
326 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
327 unsigned Count = 0;
328 while (Val != 1) {
329 if (Val & 1) return 0; // Multiple bits set?
330 Val >>= 1;
331 ++Count;
332 }
333 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000334}
335
Chris Lattnerb8b97502003-08-13 19:01:45 +0000336
337/// AssociativeOpt - Perform an optimization on an associative operator. This
338/// function is designed to check a chain of associative operators for a
339/// potential to apply a certain optimization. Since the optimization may be
340/// applicable if the expression was reassociated, this checks the chain, then
341/// reassociates the expression as necessary to expose the optimization
342/// opportunity. This makes use of a special Functor, which must define
343/// 'shouldApply' and 'apply' methods.
344///
345template<typename Functor>
346Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
347 unsigned Opcode = Root.getOpcode();
348 Value *LHS = Root.getOperand(0);
349
350 // Quick check, see if the immediate LHS matches...
351 if (F.shouldApply(LHS))
352 return F.apply(Root);
353
354 // Otherwise, if the LHS is not of the same opcode as the root, return.
355 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000356 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000357 // Should we apply this transform to the RHS?
358 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
359
360 // If not to the RHS, check to see if we should apply to the LHS...
361 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
362 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
363 ShouldApply = true;
364 }
365
366 // If the functor wants to apply the optimization to the RHS of LHSI,
367 // reassociate the expression from ((? op A) op B) to (? op (A op B))
368 if (ShouldApply) {
369 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000370
371 // Now all of the instructions are in the current basic block, go ahead
372 // and perform the reassociation.
373 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
374
375 // First move the selected RHS to the LHS of the root...
376 Root.setOperand(0, LHSI->getOperand(1));
377
378 // Make what used to be the LHS of the root be the user of the root...
379 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000380 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000381 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
382 return 0;
383 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000384 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000385 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000386 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
387 BasicBlock::iterator ARI = &Root; ++ARI;
388 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
389 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000390
391 // Now propagate the ExtraOperand down the chain of instructions until we
392 // get to LHSI.
393 while (TmpLHSI != LHSI) {
394 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000395 // Move the instruction to immediately before the chain we are
396 // constructing to avoid breaking dominance properties.
397 NextLHSI->getParent()->getInstList().remove(NextLHSI);
398 BB->getInstList().insert(ARI, NextLHSI);
399 ARI = NextLHSI;
400
Chris Lattnerb8b97502003-08-13 19:01:45 +0000401 Value *NextOp = NextLHSI->getOperand(1);
402 NextLHSI->setOperand(1, ExtraOperand);
403 TmpLHSI = NextLHSI;
404 ExtraOperand = NextOp;
405 }
406
407 // Now that the instructions are reassociated, have the functor perform
408 // the transformation...
409 return F.apply(Root);
410 }
411
412 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
413 }
414 return 0;
415}
416
417
418// AddRHS - Implements: X + X --> X << 1
419struct AddRHS {
420 Value *RHS;
421 AddRHS(Value *rhs) : RHS(rhs) {}
422 bool shouldApply(Value *LHS) const { return LHS == RHS; }
423 Instruction *apply(BinaryOperator &Add) const {
424 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
425 ConstantInt::get(Type::UByteTy, 1));
426 }
427};
428
429// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
430// iff C1&C2 == 0
431struct AddMaskingAnd {
432 Constant *C2;
433 AddMaskingAnd(Constant *c) : C2(c) {}
434 bool shouldApply(Value *LHS) const {
435 if (Constant *C1 = dyn_castMaskingAnd(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000436 return ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000437 return false;
438 }
439 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000440 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000441 }
442};
443
Chris Lattner183b3362004-04-09 19:05:30 +0000444static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
445 InstCombiner *IC) {
446 // Figure out if the constant is the left or the right argument.
447 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
448 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000449
Chris Lattner183b3362004-04-09 19:05:30 +0000450 if (Constant *SOC = dyn_cast<Constant>(SO)) {
451 if (ConstIsRHS)
452 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
453 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
454 }
455
456 Value *Op0 = SO, *Op1 = ConstOperand;
457 if (!ConstIsRHS)
458 std::swap(Op0, Op1);
459 Instruction *New;
460 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
461 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
462 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
463 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattnerf9d96652004-04-10 19:15:56 +0000464 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000465 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000466 abort();
467 }
Chris Lattner183b3362004-04-09 19:05:30 +0000468 return IC->InsertNewInstBefore(New, BI);
469}
470
471// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
472// constant as the other operand, try to fold the binary operator into the
473// select arguments.
474static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
475 InstCombiner *IC) {
476 // Don't modify shared select instructions
477 if (!SI->hasOneUse()) return 0;
478 Value *TV = SI->getOperand(1);
479 Value *FV = SI->getOperand(2);
480
481 if (isa<Constant>(TV) || isa<Constant>(FV)) {
482 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
483 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
484
485 return new SelectInst(SI->getCondition(), SelectTrueVal,
486 SelectFalseVal);
487 }
488 return 0;
489}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000490
Chris Lattner113f4f42002-06-25 16:13:24 +0000491Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000492 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000493 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000494
Chris Lattnercf4a9962004-04-10 22:01:55 +0000495 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
496 // X + 0 --> X
497 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
498 RHSC->isNullValue())
499 return ReplaceInstUsesWith(I, LHS);
500
501 // X + (signbit) --> X ^ signbit
502 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
503 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
504 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
505 if (Val == (1ULL << NumBits-1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000506 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000507 }
508 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000509
Chris Lattnerb8b97502003-08-13 19:01:45 +0000510 // X + X --> X << 1
511 if (I.getType()->isInteger())
512 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattnerede3fe02003-08-13 04:18:28 +0000513
Chris Lattner147e9752002-05-08 22:46:53 +0000514 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000515 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000516 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000517
518 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000519 if (!isa<Constant>(RHS))
520 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000521 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000522
Chris Lattner57c8d992003-02-18 19:57:07 +0000523 // X*C + X --> X * (C+1)
524 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000525 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000526 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000527 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
528 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000529 return BinaryOperator::createMul(RHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000530 }
531
532 // X + X*C --> X * (C+1)
533 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000534 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000535 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000536 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
537 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000538 return BinaryOperator::createMul(LHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000539 }
540
Chris Lattnerb8b97502003-08-13 19:01:45 +0000541 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
542 if (Constant *C2 = dyn_castMaskingAnd(RHS))
543 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000544
Chris Lattnerb9cde762003-10-02 15:11:26 +0000545 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
546 if (Instruction *ILHS = dyn_cast<Instruction>(LHS)) {
547 switch (ILHS->getOpcode()) {
548 case Instruction::Xor:
549 // ~X + C --> (C-1) - X
550 if (ConstantInt *XorRHS = dyn_cast<ConstantInt>(ILHS->getOperand(1)))
551 if (XorRHS->isAllOnesValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000552 return BinaryOperator::createSub(ConstantExpr::getSub(CRHS,
553 ConstantInt::get(I.getType(), 1)),
Chris Lattnerb9cde762003-10-02 15:11:26 +0000554 ILHS->getOperand(0));
555 break;
Chris Lattner183b3362004-04-09 19:05:30 +0000556 case Instruction::Select:
557 // Try to fold constant add into select arguments.
558 if (Instruction *R = FoldBinOpIntoSelect(I,cast<SelectInst>(ILHS),this))
559 return R;
560
Chris Lattnerb9cde762003-10-02 15:11:26 +0000561 default: break;
562 }
563 }
564 }
565
Chris Lattner113f4f42002-06-25 16:13:24 +0000566 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000567}
568
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000569// isSignBit - Return true if the value represented by the constant only has the
570// highest order bit set.
571static bool isSignBit(ConstantInt *CI) {
572 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
573 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
574}
575
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000576static unsigned getTypeSizeInBits(const Type *Ty) {
577 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
578}
579
Chris Lattner022167f2004-03-13 00:11:49 +0000580/// RemoveNoopCast - Strip off nonconverting casts from the value.
581///
582static Value *RemoveNoopCast(Value *V) {
583 if (CastInst *CI = dyn_cast<CastInst>(V)) {
584 const Type *CTy = CI->getType();
585 const Type *OpTy = CI->getOperand(0)->getType();
586 if (CTy->isInteger() && OpTy->isInteger()) {
587 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
588 return RemoveNoopCast(CI->getOperand(0));
589 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
590 return RemoveNoopCast(CI->getOperand(0));
591 }
592 return V;
593}
594
Chris Lattner113f4f42002-06-25 16:13:24 +0000595Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000596 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000597
Chris Lattnere6794492002-08-12 21:17:25 +0000598 if (Op0 == Op1) // sub X, X -> 0
599 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000600
Chris Lattnere6794492002-08-12 21:17:25 +0000601 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000602 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000603 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000604
Chris Lattner8f2f5982003-11-05 01:06:05 +0000605 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
606 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000607 if (C->isAllOnesValue())
608 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000609
Chris Lattner8f2f5982003-11-05 01:06:05 +0000610 // C - ~X == X + (1+C)
611 if (BinaryOperator::isNot(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000612 return BinaryOperator::createAdd(
613 BinaryOperator::getNotArgument(cast<BinaryOperator>(Op1)),
614 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000615 // -((uint)X >> 31) -> ((int)X >> 31)
616 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000617 if (C->isNullValue()) {
618 Value *NoopCastedRHS = RemoveNoopCast(Op1);
619 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000620 if (SI->getOpcode() == Instruction::Shr)
621 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
622 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000623 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000624 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000625 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000626 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000627 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000628 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000629 // Ok, the transformation is safe. Insert a cast of the incoming
630 // value, then the new shift, then the new cast.
631 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
632 SI->getOperand(0)->getName());
633 Value *InV = InsertNewInstBefore(FirstCast, I);
634 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
635 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000636 if (NewShift->getType() == I.getType())
637 return NewShift;
638 else {
639 InV = InsertNewInstBefore(NewShift, I);
640 return new CastInst(NewShift, I.getType());
641 }
Chris Lattner92295c52004-03-12 23:53:13 +0000642 }
643 }
Chris Lattner022167f2004-03-13 00:11:49 +0000644 }
Chris Lattner183b3362004-04-09 19:05:30 +0000645
646 // Try to fold constant sub into select arguments.
647 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
648 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
649 return R;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000650 }
651
Chris Lattner3082c5a2003-02-18 19:28:33 +0000652 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000653 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000654 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
655 // is not used by anyone else...
656 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000657 if (Op1I->getOpcode() == Instruction::Sub &&
658 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000659 // Swap the two operands of the subexpr...
660 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
661 Op1I->setOperand(0, IIOp1);
662 Op1I->setOperand(1, IIOp0);
663
664 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000665 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000666 }
667
668 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
669 //
670 if (Op1I->getOpcode() == Instruction::And &&
671 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
672 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
673
Chris Lattner396dbfe2004-06-09 05:08:07 +0000674 Value *NewNot =
675 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000676 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000677 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000678
679 // X - X*C --> X * (1-C)
680 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000681 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000682 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner34428442003-05-27 16:40:51 +0000683 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000684 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000685 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000686 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000687 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000688
Chris Lattner57c8d992003-02-18 19:57:07 +0000689 // X*C - X --> X * (C-1)
690 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000691 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000692 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner34428442003-05-27 16:40:51 +0000693 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000694 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000695 return BinaryOperator::createMul(Op1, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000696 }
697
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000698 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000699}
700
Chris Lattnere79e8542004-02-23 06:38:22 +0000701/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
702/// really just returns true if the most significant (sign) bit is set.
703static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
704 if (RHS->getType()->isSigned()) {
705 // True if source is LHS < 0 or LHS <= -1
706 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
707 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
708 } else {
709 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
710 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
711 // the size of the integer type.
712 if (Opcode == Instruction::SetGE)
713 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
714 if (Opcode == Instruction::SetGT)
715 return RHSC->getValue() ==
716 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
717 }
718 return false;
719}
720
Chris Lattner113f4f42002-06-25 16:13:24 +0000721Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000722 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000723 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000724
Chris Lattnere6794492002-08-12 21:17:25 +0000725 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000726 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
727 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000728
729 // ((X << C1)*C2) == (X * (C2 << C1))
730 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
731 if (SI->getOpcode() == Instruction::Shl)
732 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000733 return BinaryOperator::createMul(SI->getOperand(0),
734 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000735
Chris Lattnercce81be2003-09-11 22:24:54 +0000736 if (CI->isNullValue())
737 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
738 if (CI->equalsInt(1)) // X * 1 == X
739 return ReplaceInstUsesWith(I, Op0);
740 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000741 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000742
Chris Lattnercce81be2003-09-11 22:24:54 +0000743 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000744 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
745 return new ShiftInst(Instruction::Shl, Op0,
746 ConstantUInt::get(Type::UByteTy, C));
747 } else {
748 ConstantFP *Op1F = cast<ConstantFP>(Op1);
749 if (Op1F->isNullValue())
750 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000751
Chris Lattner3082c5a2003-02-18 19:28:33 +0000752 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
753 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
754 if (Op1F->getValue() == 1.0)
755 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
756 }
Chris Lattner183b3362004-04-09 19:05:30 +0000757
758 // Try to fold constant mul into select arguments.
759 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
760 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
761 return R;
Chris Lattner260ab202002-04-18 17:39:14 +0000762 }
763
Chris Lattner934a64cf2003-03-10 23:23:04 +0000764 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
765 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000766 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000767
Chris Lattner2635b522004-02-23 05:39:21 +0000768 // If one of the operands of the multiply is a cast from a boolean value, then
769 // we know the bool is either zero or one, so this is a 'masking' multiply.
770 // See if we can simplify things based on how the boolean was originally
771 // formed.
772 CastInst *BoolCast = 0;
773 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
774 if (CI->getOperand(0)->getType() == Type::BoolTy)
775 BoolCast = CI;
776 if (!BoolCast)
777 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
778 if (CI->getOperand(0)->getType() == Type::BoolTy)
779 BoolCast = CI;
780 if (BoolCast) {
781 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
782 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
783 const Type *SCOpTy = SCIOp0->getType();
784
Chris Lattnere79e8542004-02-23 06:38:22 +0000785 // If the setcc is true iff the sign bit of X is set, then convert this
786 // multiply into a shift/and combination.
787 if (isa<ConstantInt>(SCIOp1) &&
788 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000789 // Shift the X value right to turn it into "all signbits".
790 Constant *Amt = ConstantUInt::get(Type::UByteTy,
791 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000792 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000793 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000794 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
795 SCIOp0->getName()), I);
796 }
797
798 Value *V =
799 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
800 BoolCast->getOperand(0)->getName()+
801 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000802
803 // If the multiply type is not the same as the source type, sign extend
804 // or truncate to the multiply type.
805 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000806 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000807
808 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000809 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000810 }
811 }
812 }
813
Chris Lattner113f4f42002-06-25 16:13:24 +0000814 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000815}
816
Chris Lattner113f4f42002-06-25 16:13:24 +0000817Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000818 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000819 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000820 if (RHS->equalsInt(1))
821 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000822
Chris Lattnere20c3342004-04-26 14:01:59 +0000823 // div X, -1 == -X
824 if (RHS->isAllOnesValue())
825 return BinaryOperator::createNeg(I.getOperand(0));
826
Chris Lattner3082c5a2003-02-18 19:28:33 +0000827 // Check to see if this is an unsigned division with an exact power of 2,
828 // if so, convert to a right shift.
829 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
830 if (uint64_t Val = C->getValue()) // Don't break X / 0
831 if (uint64_t C = Log2(Val))
832 return new ShiftInst(Instruction::Shr, I.getOperand(0),
833 ConstantUInt::get(Type::UByteTy, C));
834 }
835
836 // 0 / X == 0, we don't need to preserve faults!
837 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
838 if (LHS->equalsInt(0))
839 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
840
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000841 return 0;
842}
843
844
Chris Lattner113f4f42002-06-25 16:13:24 +0000845Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000846 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
847 if (RHS->equalsInt(1)) // X % 1 == 0
848 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner56b50512004-03-26 16:11:24 +0000849 if (RHS->isAllOnesValue()) // X % -1 == 0
850 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000851
852 // Check to see if this is an unsigned remainder with an exact power of 2,
853 // if so, convert to a bitwise and.
854 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
855 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +0000856 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000857 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattner3082c5a2003-02-18 19:28:33 +0000858 ConstantUInt::get(I.getType(), Val-1));
859 }
860
861 // 0 % X == 0, we don't need to preserve faults!
862 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
863 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000864 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
865
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000866 return 0;
867}
868
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000869// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000870static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000871 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
872 // Calculate -1 casted to the right type...
873 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
874 uint64_t Val = ~0ULL; // All ones
875 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
876 return CU->getValue() == Val-1;
877 }
878
879 const ConstantSInt *CS = cast<ConstantSInt>(C);
880
881 // Calculate 0111111111..11111
882 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
883 int64_t Val = INT64_MAX; // All ones
884 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
885 return CS->getValue() == Val-1;
886}
887
888// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000889static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000890 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
891 return CU->getValue() == 1;
892
893 const ConstantSInt *CS = cast<ConstantSInt>(C);
894
895 // Calculate 1111111111000000000000
896 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
897 int64_t Val = -1; // All ones
898 Val <<= TypeBits-1; // Shift over to the right spot
899 return CS->getValue() == Val+1;
900}
901
Chris Lattner35167c32004-06-09 07:59:58 +0000902// isOneBitSet - Return true if there is exactly one bit set in the specified
903// constant.
904static bool isOneBitSet(const ConstantInt *CI) {
905 uint64_t V = CI->getRawValue();
906 return V && (V & (V-1)) == 0;
907}
908
Chris Lattner3ac7c262003-08-13 20:16:26 +0000909/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
910/// are carefully arranged to allow folding of expressions such as:
911///
912/// (A < B) | (A > B) --> (A != B)
913///
914/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
915/// represents that the comparison is true if A == B, and bit value '1' is true
916/// if A < B.
917///
918static unsigned getSetCondCode(const SetCondInst *SCI) {
919 switch (SCI->getOpcode()) {
920 // False -> 0
921 case Instruction::SetGT: return 1;
922 case Instruction::SetEQ: return 2;
923 case Instruction::SetGE: return 3;
924 case Instruction::SetLT: return 4;
925 case Instruction::SetNE: return 5;
926 case Instruction::SetLE: return 6;
927 // True -> 7
928 default:
929 assert(0 && "Invalid SetCC opcode!");
930 return 0;
931 }
932}
933
934/// getSetCCValue - This is the complement of getSetCondCode, which turns an
935/// opcode and two operands into either a constant true or false, or a brand new
936/// SetCC instruction.
937static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
938 switch (Opcode) {
939 case 0: return ConstantBool::False;
940 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
941 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
942 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
943 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
944 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
945 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
946 case 7: return ConstantBool::True;
947 default: assert(0 && "Illegal SetCCCode!"); return 0;
948 }
949}
950
951// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
952struct FoldSetCCLogical {
953 InstCombiner &IC;
954 Value *LHS, *RHS;
955 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
956 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
957 bool shouldApply(Value *V) const {
958 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
959 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
960 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
961 return false;
962 }
963 Instruction *apply(BinaryOperator &Log) const {
964 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
965 if (SCI->getOperand(0) != LHS) {
966 assert(SCI->getOperand(1) == LHS);
967 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
968 }
969
970 unsigned LHSCode = getSetCondCode(SCI);
971 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
972 unsigned Code;
973 switch (Log.getOpcode()) {
974 case Instruction::And: Code = LHSCode & RHSCode; break;
975 case Instruction::Or: Code = LHSCode | RHSCode; break;
976 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +0000977 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +0000978 }
979
980 Value *RV = getSetCCValue(Code, LHS, RHS);
981 if (Instruction *I = dyn_cast<Instruction>(RV))
982 return I;
983 // Otherwise, it's a constant boolean value...
984 return IC.ReplaceInstUsesWith(Log, RV);
985 }
986};
987
988
Chris Lattnerba1cb382003-09-19 17:17:26 +0000989// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
990// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
991// guaranteed to be either a shift instruction or a binary operator.
992Instruction *InstCombiner::OptAndOp(Instruction *Op,
993 ConstantIntegral *OpRHS,
994 ConstantIntegral *AndRHS,
995 BinaryOperator &TheAnd) {
996 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +0000997 Constant *Together = 0;
998 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000999 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001000
Chris Lattnerba1cb382003-09-19 17:17:26 +00001001 switch (Op->getOpcode()) {
1002 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001003 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001004 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001005 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001006 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001007 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1008 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001009 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001010 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001011 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001012 }
1013 break;
1014 case Instruction::Or:
1015 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001016 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001017 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001018 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001019 if (Together == AndRHS) // (X | C) & C --> C
1020 return ReplaceInstUsesWith(TheAnd, AndRHS);
1021
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001022 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001023 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1024 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001025 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001026 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001027 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001028 }
1029 }
1030 break;
1031 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001032 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001033 // Adding a one to a single bit bit-field should be turned into an XOR
1034 // of the bit. First thing to check is to see if this AND is with a
1035 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001036 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001037
1038 // Clear bits that are not part of the constant.
1039 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1040
1041 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001042 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001043 // Ok, at this point, we know that we are masking the result of the
1044 // ADD down to exactly one bit. If the constant we are adding has
1045 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001046 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001047
1048 // Check to see if any bits below the one bit set in AndRHSV are set.
1049 if ((AddRHS & (AndRHSV-1)) == 0) {
1050 // If not, the only thing that can effect the output of the AND is
1051 // the bit specified by AndRHSV. If that bit is set, the effect of
1052 // the XOR is to toggle the bit. If it is clear, then the ADD has
1053 // no effect.
1054 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1055 TheAnd.setOperand(0, X);
1056 return &TheAnd;
1057 } else {
1058 std::string Name = Op->getName(); Op->setName("");
1059 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001060 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001061 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001062 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001063 }
1064 }
1065 }
1066 }
1067 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001068
1069 case Instruction::Shl: {
1070 // We know that the AND will not produce any of the bits shifted in, so if
1071 // the anded constant includes them, clear them now!
1072 //
1073 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001074 Constant *CI = ConstantExpr::getAnd(AndRHS,
1075 ConstantExpr::getShl(AllOne, OpRHS));
Chris Lattner2da29172003-09-19 19:05:02 +00001076 if (CI != AndRHS) {
1077 TheAnd.setOperand(1, CI);
1078 return &TheAnd;
1079 }
1080 break;
1081 }
1082 case Instruction::Shr:
1083 // We know that the AND will not produce any of the bits shifted in, so if
1084 // the anded constant includes them, clear them now! This only applies to
1085 // unsigned shifts, because a signed shr may bring in set bits!
1086 //
1087 if (AndRHS->getType()->isUnsigned()) {
1088 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001089 Constant *CI = ConstantExpr::getAnd(AndRHS,
1090 ConstantExpr::getShr(AllOne, OpRHS));
Chris Lattner2da29172003-09-19 19:05:02 +00001091 if (CI != AndRHS) {
1092 TheAnd.setOperand(1, CI);
1093 return &TheAnd;
1094 }
1095 }
1096 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001097 }
1098 return 0;
1099}
1100
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001101
Chris Lattner113f4f42002-06-25 16:13:24 +00001102Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001103 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001104 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001105
1106 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001107 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1108 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001109
1110 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001111 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001112 if (RHS->isAllOnesValue())
1113 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001114
Chris Lattnerba1cb382003-09-19 17:17:26 +00001115 // Optimize a variety of ((val OP C1) & C2) combinations...
1116 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1117 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001118 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001119 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001120 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1121 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001122 }
Chris Lattner183b3362004-04-09 19:05:30 +00001123
1124 // Try to fold constant and into select arguments.
1125 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1126 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1127 return R;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001128 }
1129
Chris Lattnerbb74e222003-03-10 23:06:50 +00001130 Value *Op0NotVal = dyn_castNotVal(Op0);
1131 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001132
Chris Lattner023a4832004-06-18 06:07:51 +00001133 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1134 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1135
Chris Lattner3082c5a2003-02-18 19:28:33 +00001136 // (~A & ~B) == (~(A | B)) - Demorgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001137 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001138 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1139 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001140 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001141 return BinaryOperator::createNot(Or);
1142 }
1143
Chris Lattner3ac7c262003-08-13 20:16:26 +00001144 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1145 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1146 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1147 return R;
1148
Chris Lattner113f4f42002-06-25 16:13:24 +00001149 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001150}
1151
1152
1153
Chris Lattner113f4f42002-06-25 16:13:24 +00001154Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001155 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001156 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001157
1158 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001159 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1160 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001161
1162 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001163 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001164 if (RHS->isAllOnesValue())
1165 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001166
Chris Lattner8f0d1562003-07-23 18:29:44 +00001167 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1168 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1169 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
1170 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
1171 std::string Op0Name = Op0I->getName(); Op0I->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001172 Instruction *Or = BinaryOperator::createOr(Op0I->getOperand(0), RHS,
1173 Op0Name);
Chris Lattner8f0d1562003-07-23 18:29:44 +00001174 InsertNewInstBefore(Or, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001175 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, Op0CI));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001176 }
1177
1178 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1179 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
1180 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
1181 std::string Op0Name = Op0I->getName(); Op0I->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001182 Instruction *Or = BinaryOperator::createOr(Op0I->getOperand(0), RHS,
1183 Op0Name);
Chris Lattner8f0d1562003-07-23 18:29:44 +00001184 InsertNewInstBefore(Or, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001185 return BinaryOperator::createXor(Or,
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001186 ConstantExpr::getAnd(Op0CI,
1187 ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001188 }
1189 }
Chris Lattner183b3362004-04-09 19:05:30 +00001190
1191 // Try to fold constant and into select arguments.
1192 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1193 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1194 return R;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001195 }
1196
Chris Lattner812aab72003-08-12 19:11:07 +00001197 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattner01d56392003-08-12 19:17:27 +00001198 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
1199 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
1200 if (LHS->getOperand(0) == RHS->getOperand(0))
1201 if (Constant *C0 = dyn_castMaskingAnd(LHS))
1202 if (Constant *C1 = dyn_castMaskingAnd(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001203 return BinaryOperator::createAnd(LHS->getOperand(0),
1204 ConstantExpr::getOr(C0, C1));
Chris Lattner812aab72003-08-12 19:11:07 +00001205
Chris Lattner3e327a42003-03-10 23:13:59 +00001206 Value *Op0NotVal = dyn_castNotVal(Op0);
1207 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001208
Chris Lattner3e327a42003-03-10 23:13:59 +00001209 if (Op1 == Op0NotVal) // ~A | A == -1
1210 return ReplaceInstUsesWith(I,
1211 ConstantIntegral::getAllOnesValue(I.getType()));
1212
1213 if (Op0 == Op1NotVal) // A | ~A == -1
1214 return ReplaceInstUsesWith(I,
1215 ConstantIntegral::getAllOnesValue(I.getType()));
1216
1217 // (~A | ~B) == (~(A & B)) - Demorgan's Law
1218 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner396dbfe2004-06-09 05:08:07 +00001219 Value *And = InsertNewInstBefore(
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001220 BinaryOperator::createAnd(Op0NotVal,
1221 Op1NotVal,I.getName()+".demorgan"),I);
Chris Lattner3e327a42003-03-10 23:13:59 +00001222 return BinaryOperator::createNot(And);
1223 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001224
Chris Lattner3ac7c262003-08-13 20:16:26 +00001225 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
1226 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1227 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1228 return R;
1229
Chris Lattner113f4f42002-06-25 16:13:24 +00001230 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001231}
1232
Chris Lattnerc2076352004-02-16 01:20:27 +00001233// XorSelf - Implements: X ^ X --> 0
1234struct XorSelf {
1235 Value *RHS;
1236 XorSelf(Value *rhs) : RHS(rhs) {}
1237 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1238 Instruction *apply(BinaryOperator &Xor) const {
1239 return &Xor;
1240 }
1241};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001242
1243
Chris Lattner113f4f42002-06-25 16:13:24 +00001244Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001245 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001246 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001247
Chris Lattnerc2076352004-02-16 01:20:27 +00001248 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1249 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1250 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001251 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001252 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001253
Chris Lattner97638592003-07-23 21:37:07 +00001254 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001255 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001256 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001257 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001258
Chris Lattner97638592003-07-23 21:37:07 +00001259 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001260 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001261 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001262 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001263 return new SetCondInst(SCI->getInverseCondition(),
1264 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001265
Chris Lattner8f2f5982003-11-05 01:06:05 +00001266 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001267 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1268 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001269 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1270 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001271 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001272 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001273 }
Chris Lattner023a4832004-06-18 06:07:51 +00001274
1275 // ~(~X & Y) --> (X | ~Y)
1276 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1277 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1278 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1279 Instruction *NotY =
1280 BinaryOperator::createNot(Op0I->getOperand(1),
1281 Op0I->getOperand(1)->getName()+".not");
1282 InsertNewInstBefore(NotY, I);
1283 return BinaryOperator::createOr(Op0NotVal, NotY);
1284 }
1285 }
Chris Lattner97638592003-07-23 21:37:07 +00001286
1287 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001288 switch (Op0I->getOpcode()) {
1289 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001290 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001291 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001292 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1293 return BinaryOperator::createSub(
1294 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001295 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001296 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001297 }
Chris Lattnere5806662003-11-04 23:50:51 +00001298 break;
1299 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001300 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001301 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1302 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001303 break;
1304 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001305 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001306 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001307 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001308 break;
1309 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001310 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001311 }
Chris Lattner183b3362004-04-09 19:05:30 +00001312
1313 // Try to fold constant and into select arguments.
1314 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1315 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1316 return R;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001317 }
1318
Chris Lattnerbb74e222003-03-10 23:06:50 +00001319 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001320 if (X == Op1)
1321 return ReplaceInstUsesWith(I,
1322 ConstantIntegral::getAllOnesValue(I.getType()));
1323
Chris Lattnerbb74e222003-03-10 23:06:50 +00001324 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001325 if (X == Op0)
1326 return ReplaceInstUsesWith(I,
1327 ConstantIntegral::getAllOnesValue(I.getType()));
1328
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001329 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001330 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001331 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1332 cast<BinaryOperator>(Op1I)->swapOperands();
1333 I.swapOperands();
1334 std::swap(Op0, Op1);
1335 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1336 I.swapOperands();
1337 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001338 }
1339 } else if (Op1I->getOpcode() == Instruction::Xor) {
1340 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1341 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1342 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1343 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1344 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001345
1346 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001347 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001348 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1349 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001350 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001351 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1352 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001353 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001354 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001355 } else if (Op0I->getOpcode() == Instruction::Xor) {
1356 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1357 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1358 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1359 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001360 }
1361
Chris Lattner7fb29e12003-03-11 00:12:48 +00001362 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
1363 if (Constant *C1 = dyn_castMaskingAnd(Op0))
1364 if (Constant *C2 = dyn_castMaskingAnd(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001365 if (ConstantExpr::getAnd(C1, C2)->isNullValue())
1366 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001367
Chris Lattner3ac7c262003-08-13 20:16:26 +00001368 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1369 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1370 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1371 return R;
1372
Chris Lattner113f4f42002-06-25 16:13:24 +00001373 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001374}
1375
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001376// AddOne, SubOne - Add or subtract a constant one from an integer constant...
1377static Constant *AddOne(ConstantInt *C) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001378 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001379}
1380static Constant *SubOne(ConstantInt *C) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001381 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001382}
1383
Chris Lattner1fc23f32002-05-09 20:11:54 +00001384// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1385// true when both operands are equal...
1386//
Chris Lattner113f4f42002-06-25 16:13:24 +00001387static bool isTrueWhenEqual(Instruction &I) {
1388 return I.getOpcode() == Instruction::SetEQ ||
1389 I.getOpcode() == Instruction::SetGE ||
1390 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +00001391}
1392
Chris Lattner113f4f42002-06-25 16:13:24 +00001393Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001394 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001395 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1396 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001397
1398 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001399 if (Op0 == Op1)
1400 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001401
Chris Lattnerd07283a2003-08-13 05:38:46 +00001402 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1403 if (isa<ConstantPointerNull>(Op1) &&
1404 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001405 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1406
Chris Lattnerd07283a2003-08-13 05:38:46 +00001407
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001408 // setcc's with boolean values can always be turned into bitwise operations
1409 if (Ty == Type::BoolTy) {
1410 // If this is <, >, or !=, we can change this into a simple xor instruction
1411 if (!isTrueWhenEqual(I))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001412 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001413
1414 // Otherwise we need to make a temporary intermediate instruction and insert
1415 // it into the instruction stream. This is what we are after:
1416 //
1417 // seteq bool %A, %B -> ~(A^B)
1418 // setle bool %A, %B -> ~A | B
1419 // setge bool %A, %B -> A | ~B
1420 //
1421 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001422 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001423 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001424 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001425 }
1426
1427 // Handle the setXe cases...
1428 assert(I.getOpcode() == Instruction::SetGE ||
1429 I.getOpcode() == Instruction::SetLE);
1430
1431 if (I.getOpcode() == Instruction::SetGE)
1432 std::swap(Op0, Op1); // Change setge -> setle
1433
1434 // Now we just have the SetLE case.
Chris Lattner31ae8632002-08-14 17:51:49 +00001435 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001436 InsertNewInstBefore(Not, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001437 return BinaryOperator::createOr(Not, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001438 }
1439
Chris Lattner2dd01742004-06-09 04:24:29 +00001440 // See if we are doing a comparison between a constant and an instruction that
1441 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001442 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere1e10e12004-05-25 06:32:08 +00001443 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner2dd01742004-06-09 04:24:29 +00001444 if (LHSI->hasOneUse())
Chris Lattner35167c32004-06-09 07:59:58 +00001445 switch (LHSI->getOpcode()) {
1446 case Instruction::And:
1447 if (isa<ConstantInt>(LHSI->getOperand(1))) {
1448
Chris Lattnere1e10e12004-05-25 06:32:08 +00001449
Chris Lattner35167c32004-06-09 07:59:58 +00001450 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1451 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1452 // happens a LOT in code produced by the C front-end, for bitfield
1453 // access.
1454 if (LHSI->getOperand(0)->hasOneUse())
1455 if (ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0)))
1456 if (ConstantUInt *ShAmt =
1457 dyn_cast<ConstantUInt>(Shift->getOperand(1))) {
1458 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1459
1460 // We can fold this as long as we can't shift unknown bits
1461 // into the mask. This can only happen with signed shift
1462 // rights, as they sign-extend.
1463 const Type *Ty = Shift->getType();
1464 if (Shift->getOpcode() != Instruction::Shr ||
1465 Shift->getType()->isUnsigned() ||
1466 // To test for the bad case of the signed shr, see if any
1467 // of the bits shifted in could be tested after the mask.
1468 ConstantExpr::getAnd(ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), ConstantUInt::get(Type::UByteTy, Ty->getPrimitiveSize()*8-ShAmt->getValue())), AndCST)->isNullValue()) {
1469 unsigned ShiftOp = Shift->getOpcode() == Instruction::Shl
1470 ? Instruction::Shr : Instruction::Shl;
1471 I.setOperand(1, ConstantExpr::get(ShiftOp, CI, ShAmt));
1472 LHSI->setOperand(1,ConstantExpr::get(ShiftOp,AndCST,ShAmt));
1473 LHSI->setOperand(0, Shift->getOperand(0));
1474 WorkList.push_back(Shift); // Shift is probably dead.
1475 AddUsesToWorkList(I);
1476 return &I;
1477 }
Chris Lattner2dd01742004-06-09 04:24:29 +00001478 }
Chris Lattner35167c32004-06-09 07:59:58 +00001479 }
1480 break;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001481 case Instruction::Div:
1482 if (0 && isa<ConstantInt>(LHSI->getOperand(1))) {
1483 std::cerr << "COULD FOLD: " << *LHSI;
1484 std::cerr << "COULD FOLD: " << I << "\n";
1485 }
1486 break;
Chris Lattner35167c32004-06-09 07:59:58 +00001487 case Instruction::Select:
Chris Lattner2dd01742004-06-09 04:24:29 +00001488 // If either operand of the select is a constant, we can fold the
1489 // comparison into the select arms, which will cause one to be
1490 // constant folded and the select turned into a bitwise or.
1491 Value *Op1 = 0, *Op2 = 0;
Chris Lattner35167c32004-06-09 07:59:58 +00001492 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00001493 // Fold the known value into the constant operand.
1494 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
1495 // Insert a new SetCC of the other select operand.
1496 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00001497 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00001498 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00001499 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00001500 // Fold the known value into the constant operand.
1501 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
1502 // Insert a new SetCC of the other select operand.
1503 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00001504 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00001505 I.getName()), I);
1506 }
1507
1508 if (Op1)
Chris Lattner35167c32004-06-09 07:59:58 +00001509 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
1510 break;
Chris Lattner2dd01742004-06-09 04:24:29 +00001511 }
Chris Lattnere1e10e12004-05-25 06:32:08 +00001512
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001513 // Simplify seteq and setne instructions...
1514 if (I.getOpcode() == Instruction::SetEQ ||
1515 I.getOpcode() == Instruction::SetNE) {
1516 bool isSetNE = I.getOpcode() == Instruction::SetNE;
1517
Chris Lattnercfbce7c2003-07-23 17:26:36 +00001518 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001519 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00001520 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1521 switch (BO->getOpcode()) {
1522 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00001523 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1524 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1525 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1526 ConstantExpr::getSub(CI, BOp1C));
1527 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00001528 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1529 // efficiently invertible, or if the add has just this one use.
1530 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00001531
Chris Lattnerc992add2003-08-13 05:33:12 +00001532 if (Value *NegVal = dyn_castNegVal(BOp1))
1533 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1534 else if (Value *NegVal = dyn_castNegVal(BOp0))
1535 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001536 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00001537 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1538 BO->setName("");
1539 InsertNewInstBefore(Neg, I);
1540 return new SetCondInst(I.getOpcode(), BOp0, Neg);
1541 }
1542 }
1543 break;
1544 case Instruction::Xor:
1545 // For the xor case, we can xor two constants together, eliminating
1546 // the explicit xor.
1547 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1548 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001549 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00001550
1551 // FALLTHROUGH
1552 case Instruction::Sub:
1553 // Replace (([sub|xor] A, B) != 0) with (A != B)
1554 if (CI->isNullValue())
1555 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1556 BO->getOperand(1));
1557 break;
1558
1559 case Instruction::Or:
1560 // If bits are being or'd in that are not present in the constant we
1561 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001562 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001563 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001564 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001565 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001566 }
Chris Lattnerc992add2003-08-13 05:33:12 +00001567 break;
1568
1569 case Instruction::And:
1570 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001571 // If bits are being compared against that are and'd out, then the
1572 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001573 if (!ConstantExpr::getAnd(CI,
1574 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001575 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00001576
Chris Lattner35167c32004-06-09 07:59:58 +00001577 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00001578 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00001579 return new SetCondInst(isSetNE ? Instruction::SetEQ :
1580 Instruction::SetNE, Op0,
1581 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00001582
Chris Lattnerc992add2003-08-13 05:33:12 +00001583 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
1584 // to be a signed value as appropriate.
1585 if (isSignBit(BOC)) {
1586 Value *X = BO->getOperand(0);
1587 // If 'X' is not signed, insert a cast now...
1588 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001589 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerc992add2003-08-13 05:33:12 +00001590 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1591 InsertNewInstBefore(NewCI, I);
1592 X = NewCI;
1593 }
1594 return new SetCondInst(isSetNE ? Instruction::SetLT :
1595 Instruction::SetGE, X,
1596 Constant::getNullValue(X->getType()));
1597 }
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001598 }
Chris Lattnerc992add2003-08-13 05:33:12 +00001599 default: break;
1600 }
1601 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00001602 } else { // Not a SetEQ/SetNE
1603 // If the LHS is a cast from an integral value of the same size,
1604 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
1605 Value *CastOp = Cast->getOperand(0);
1606 const Type *SrcTy = CastOp->getType();
1607 unsigned SrcTySize = SrcTy->getPrimitiveSize();
1608 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
1609 SrcTySize == Cast->getType()->getPrimitiveSize()) {
1610 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
1611 "Source and destination signednesses should differ!");
1612 if (Cast->getType()->isSigned()) {
1613 // If this is a signed comparison, check for comparisons in the
1614 // vicinity of zero.
1615 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
1616 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001617 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00001618 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
1619 else if (I.getOpcode() == Instruction::SetGT &&
1620 cast<ConstantSInt>(CI)->getValue() == -1)
1621 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001622 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00001623 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
1624 } else {
1625 ConstantUInt *CUI = cast<ConstantUInt>(CI);
1626 if (I.getOpcode() == Instruction::SetLT &&
1627 CUI->getValue() == 1ULL << (SrcTySize*8-1))
1628 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001629 return BinaryOperator::createSetGT(CastOp,
1630 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00001631 else if (I.getOpcode() == Instruction::SetGT &&
1632 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
1633 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001634 return BinaryOperator::createSetLT(CastOp,
1635 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00001636 }
1637 }
1638 }
Chris Lattnere967b342003-06-04 05:10:11 +00001639 }
Chris Lattner791ac1a2003-06-01 03:35:25 +00001640
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001641 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +00001642 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001643 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1644 return ReplaceInstUsesWith(I, ConstantBool::False);
1645 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1646 return ReplaceInstUsesWith(I, ConstantBool::True);
1647 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001648 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001649 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001650 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001651
Chris Lattnere6794492002-08-12 21:17:25 +00001652 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001653 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1654 return ReplaceInstUsesWith(I, ConstantBool::False);
1655 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1656 return ReplaceInstUsesWith(I, ConstantBool::True);
1657 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001658 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001659 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001660 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001661
1662 // Comparing against a value really close to min or max?
1663 } else if (isMinValuePlusOne(CI)) {
1664 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001665 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001666 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001667 return BinaryOperator::createSetNE(Op0, SubOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001668
1669 } else if (isMaxValueMinusOne(CI)) {
1670 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001671 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001672 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001673 return BinaryOperator::createSetNE(Op0, AddOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001674 }
Chris Lattner59611142004-02-23 05:47:48 +00001675
1676 // If we still have a setle or setge instruction, turn it into the
1677 // appropriate setlt or setgt instruction. Since the border cases have
1678 // already been handled above, this requires little checking.
1679 //
1680 if (I.getOpcode() == Instruction::SetLE)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001681 return BinaryOperator::createSetLT(Op0, AddOne(CI));
Chris Lattner59611142004-02-23 05:47:48 +00001682 if (I.getOpcode() == Instruction::SetGE)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001683 return BinaryOperator::createSetGT(Op0, SubOne(CI));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001684 }
1685
Chris Lattner16930792003-11-03 04:25:02 +00001686 // Test to see if the operands of the setcc are casted versions of other
1687 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00001688 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1689 Value *CastOp0 = CI->getOperand(0);
1690 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00001691 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00001692 (I.getOpcode() == Instruction::SetEQ ||
1693 I.getOpcode() == Instruction::SetNE)) {
1694 // We keep moving the cast from the left operand over to the right
1695 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00001696 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00001697
1698 // If operand #1 is a cast instruction, see if we can eliminate it as
1699 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00001700 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
1701 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00001702 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00001703 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00001704
1705 // If Op1 is a constant, we can fold the cast into the constant.
1706 if (Op1->getType() != Op0->getType())
1707 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1708 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
1709 } else {
1710 // Otherwise, cast the RHS right before the setcc
1711 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
1712 InsertNewInstBefore(cast<Instruction>(Op1), I);
1713 }
1714 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
1715 }
1716
Chris Lattner6444c372003-11-03 05:17:03 +00001717 // Handle the special case of: setcc (cast bool to X), <cst>
1718 // This comes up when you have code like
1719 // int X = A < B;
1720 // if (X) ...
1721 // For generality, we handle any zero-extension of any operand comparison
1722 // with a constant.
1723 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
1724 const Type *SrcTy = CastOp0->getType();
1725 const Type *DestTy = Op0->getType();
1726 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
1727 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
1728 // Ok, we have an expansion of operand 0 into a new type. Get the
1729 // constant value, masink off bits which are not set in the RHS. These
1730 // could be set if the destination value is signed.
1731 uint64_t ConstVal = ConstantRHS->getRawValue();
1732 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
1733
1734 // If the constant we are comparing it with has high bits set, which
1735 // don't exist in the original value, the values could never be equal,
1736 // because the source would be zero extended.
1737 unsigned SrcBits =
1738 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00001739 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
1740 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00001741 switch (I.getOpcode()) {
1742 default: assert(0 && "Unknown comparison type!");
1743 case Instruction::SetEQ:
1744 return ReplaceInstUsesWith(I, ConstantBool::False);
1745 case Instruction::SetNE:
1746 return ReplaceInstUsesWith(I, ConstantBool::True);
1747 case Instruction::SetLT:
1748 case Instruction::SetLE:
1749 if (DestTy->isSigned() && HasSignBit)
1750 return ReplaceInstUsesWith(I, ConstantBool::False);
1751 return ReplaceInstUsesWith(I, ConstantBool::True);
1752 case Instruction::SetGT:
1753 case Instruction::SetGE:
1754 if (DestTy->isSigned() && HasSignBit)
1755 return ReplaceInstUsesWith(I, ConstantBool::True);
1756 return ReplaceInstUsesWith(I, ConstantBool::False);
1757 }
1758 }
1759
1760 // Otherwise, we can replace the setcc with a setcc of the smaller
1761 // operand value.
1762 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
1763 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
1764 }
1765 }
1766 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001767 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001768}
1769
1770
1771
Chris Lattnere8d6c602003-03-10 19:16:08 +00001772Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001773 assert(I.getOperand(1)->getType() == Type::UByteTy);
1774 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001775 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001776
1777 // shl X, 0 == X and shr X, 0 == X
1778 // shl 0, X == 0 and shr 0, X == 0
1779 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00001780 Op0 == Constant::getNullValue(Op0->getType()))
1781 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001782
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001783 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
1784 if (!isLeftShift)
1785 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1786 if (CSI->isAllOnesValue())
1787 return ReplaceInstUsesWith(I, CSI);
1788
Chris Lattner183b3362004-04-09 19:05:30 +00001789 // Try to fold constant and into select arguments.
1790 if (isa<Constant>(Op0))
1791 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1792 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1793 return R;
1794
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001795 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001796 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1797 // of a signed value.
1798 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00001799 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00001800 if (CUI->getValue() >= TypeBits) {
1801 if (!Op0->getType()->isSigned() || isLeftShift)
1802 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
1803 else {
1804 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
1805 return &I;
1806 }
1807 }
Chris Lattner55f3d942002-09-10 23:04:09 +00001808
Chris Lattnerede3fe02003-08-13 04:18:28 +00001809 // ((X*C1) << C2) == (X * (C1 << C2))
1810 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1811 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1812 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001813 return BinaryOperator::createMul(BO->getOperand(0),
1814 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00001815
Chris Lattner183b3362004-04-09 19:05:30 +00001816 // Try to fold constant and into select arguments.
1817 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1818 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1819 return R;
Chris Lattnerede3fe02003-08-13 04:18:28 +00001820
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001821 // If the operand is an bitwise operator with a constant RHS, and the
1822 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001823 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001824 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1825 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1826 bool isValid = true; // Valid only for And, Or, Xor
1827 bool highBitSet = false; // Transform if high bit of constant set?
1828
1829 switch (Op0BO->getOpcode()) {
1830 default: isValid = false; break; // Do not perform transform!
1831 case Instruction::Or:
1832 case Instruction::Xor:
1833 highBitSet = false;
1834 break;
1835 case Instruction::And:
1836 highBitSet = true;
1837 break;
1838 }
1839
1840 // If this is a signed shift right, and the high bit is modified
1841 // by the logical operation, do not perform the transformation.
1842 // The highBitSet boolean indicates the value of the high bit of
1843 // the constant which would cause it to be modified for this
1844 // operation.
1845 //
1846 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1847 uint64_t Val = Op0C->getRawValue();
1848 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1849 }
1850
1851 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001852 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001853
1854 Instruction *NewShift =
1855 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1856 Op0BO->getName());
1857 Op0BO->setName("");
1858 InsertNewInstBefore(NewShift, I);
1859
1860 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1861 NewRHS);
1862 }
1863 }
1864
Chris Lattner3204d4e2003-07-24 17:52:58 +00001865 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001866 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00001867 if (ConstantUInt *ShiftAmt1C =
1868 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001869 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1870 unsigned ShiftAmt2 = CUI->getValue();
1871
1872 // Check for (A << c1) << c2 and (A >> c1) >> c2
1873 if (I.getOpcode() == Op0SI->getOpcode()) {
1874 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00001875 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
1876 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00001877 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1878 ConstantUInt::get(Type::UByteTy, Amt));
1879 }
1880
Chris Lattnerab780df2003-07-24 18:38:56 +00001881 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1882 // signed types, we can only support the (A >> c1) << c2 configuration,
1883 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001884 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001885 // Calculate bitmask for what gets shifted off the edge...
1886 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001887 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001888 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001889 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001890 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00001891
1892 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001893 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
1894 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00001895 InsertNewInstBefore(Mask, I);
1896
1897 // Figure out what flavor of shift we should use...
1898 if (ShiftAmt1 == ShiftAmt2)
1899 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
1900 else if (ShiftAmt1 < ShiftAmt2) {
1901 return new ShiftInst(I.getOpcode(), Mask,
1902 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1903 } else {
1904 return new ShiftInst(Op0SI->getOpcode(), Mask,
1905 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1906 }
1907 }
1908 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001909 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00001910
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001911 return 0;
1912}
1913
1914
Chris Lattner48a44f72002-05-02 17:06:02 +00001915// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1916// instruction.
1917//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001918static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1919 const Type *DstTy) {
Chris Lattner48a44f72002-05-02 17:06:02 +00001920
Chris Lattner650b6da2002-08-02 20:00:25 +00001921 // It is legal to eliminate the instruction if casting A->B->A if the sizes
1922 // are identical and the bits don't get reinterpreted (for example
Chris Lattner0bb75912002-08-14 23:21:10 +00001923 // int->float->int would not be allowed)
Misha Brukmane5838c42003-05-20 18:45:36 +00001924 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00001925 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00001926
1927 // Allow free casting and conversion of sizes as long as the sign doesn't
1928 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00001929 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00001930 unsigned SrcSize = SrcTy->getPrimitiveSize();
1931 unsigned MidSize = MidTy->getPrimitiveSize();
1932 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner650b6da2002-08-02 20:00:25 +00001933
Chris Lattner3732aca2002-08-15 16:15:25 +00001934 // Cases where we are monotonically decreasing the size of the type are
1935 // always ok, regardless of what sign changes are going on.
1936 //
Chris Lattner0bb75912002-08-14 23:21:10 +00001937 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +00001938 return true;
Chris Lattner3732aca2002-08-15 16:15:25 +00001939
Chris Lattner555518c2002-09-23 23:39:43 +00001940 // Cases where the source and destination type are the same, but the middle
1941 // type is bigger are noops.
1942 //
1943 if (SrcSize == DstSize && MidSize > SrcSize)
1944 return true;
1945
Chris Lattner3732aca2002-08-15 16:15:25 +00001946 // If we are monotonically growing, things are more complex.
1947 //
1948 if (SrcSize <= MidSize && MidSize <= DstSize) {
1949 // We have eight combinations of signedness to worry about. Here's the
1950 // table:
1951 static const int SignTable[8] = {
1952 // CODE, SrcSigned, MidSigned, DstSigned, Comment
1953 1, // U U U Always ok
1954 1, // U U S Always ok
1955 3, // U S U Ok iff SrcSize != MidSize
1956 3, // U S S Ok iff SrcSize != MidSize
1957 0, // S U U Never ok
1958 2, // S U S Ok iff MidSize == DstSize
1959 1, // S S U Always ok
1960 1, // S S S Always ok
1961 };
1962
1963 // Choose an action based on the current entry of the signtable that this
1964 // cast of cast refers to...
1965 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1966 switch (SignTable[Row]) {
1967 case 0: return false; // Never ok
1968 case 1: return true; // Always ok
1969 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1970 case 3: // Ok iff SrcSize != MidSize
1971 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1972 default: assert(0 && "Bad entry in sign table!");
1973 }
Chris Lattner3732aca2002-08-15 16:15:25 +00001974 }
Chris Lattner650b6da2002-08-02 20:00:25 +00001975 }
Chris Lattner48a44f72002-05-02 17:06:02 +00001976
1977 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1978 // like: short -> ushort -> uint, because this can create wrong results if
1979 // the input short is negative!
1980 //
1981 return false;
1982}
1983
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001984static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1985 if (V->getType() == Ty || isa<Constant>(V)) return false;
1986 if (const CastInst *CI = dyn_cast<CastInst>(V))
1987 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1988 return false;
1989 return true;
1990}
1991
1992/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1993/// InsertBefore instruction. This is specialized a bit to avoid inserting
1994/// casts that are known to not do anything...
1995///
1996Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1997 Instruction *InsertBefore) {
1998 if (V->getType() == DestTy) return V;
1999 if (Constant *C = dyn_cast<Constant>(V))
2000 return ConstantExpr::getCast(C, DestTy);
2001
2002 CastInst *CI = new CastInst(V, DestTy, V->getName());
2003 InsertNewInstBefore(CI, *InsertBefore);
2004 return CI;
2005}
Chris Lattner48a44f72002-05-02 17:06:02 +00002006
2007// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002008//
Chris Lattner113f4f42002-06-25 16:13:24 +00002009Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002010 Value *Src = CI.getOperand(0);
2011
Chris Lattner48a44f72002-05-02 17:06:02 +00002012 // If the user is casting a value to the same type, eliminate this cast
2013 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002014 if (CI.getType() == Src->getType())
2015 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002016
Chris Lattner48a44f72002-05-02 17:06:02 +00002017 // If casting the result of another cast instruction, try to eliminate this
2018 // one!
2019 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002020 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002021 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
2022 CSrc->getType(), CI.getType())) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002023 // This instruction now refers directly to the cast's src operand. This
2024 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002025 CI.setOperand(0, CSrc->getOperand(0));
2026 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002027 }
2028
Chris Lattner650b6da2002-08-02 20:00:25 +00002029 // If this is an A->B->A cast, and we are dealing with integral types, try
2030 // to convert this into a logical 'and' instruction.
2031 //
2032 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002033 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002034 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2035 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2036 assert(CSrc->getType() != Type::ULongTy &&
2037 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002038 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002039 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002040 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002041 }
2042 }
2043
Chris Lattner03841652004-05-25 04:29:21 +00002044 // If this is a cast to bool, turn it into the appropriate setne instruction.
2045 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002046 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002047 Constant::getNullValue(CI.getOperand(0)->getType()));
2048
Chris Lattnerd0d51602003-06-21 23:12:02 +00002049 // If casting the result of a getelementptr instruction with no offset, turn
2050 // this into a cast of the original pointer!
2051 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002052 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002053 bool AllZeroOperands = true;
2054 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2055 if (!isa<Constant>(GEP->getOperand(i)) ||
2056 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2057 AllZeroOperands = false;
2058 break;
2059 }
2060 if (AllZeroOperands) {
2061 CI.setOperand(0, GEP->getOperand(0));
2062 return &CI;
2063 }
2064 }
2065
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002066 // If we are casting a malloc or alloca to a pointer to a type of the same
2067 // size, rewrite the allocation instruction to allocate the "right" type.
2068 //
2069 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002070 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002071 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2072 // Get the type really allocated and the type casted to...
2073 const Type *AllocElTy = AI->getAllocatedType();
2074 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2075 const Type *CastElTy = PTy->getElementType();
2076 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002077
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002078 // If the allocation is for an even multiple of the cast type size
Chris Lattneraf789322003-11-03 01:29:41 +00002079 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002080 Value *Amt = ConstantUInt::get(Type::UIntTy,
2081 AllocElTySize/CastElTySize);
2082 std::string Name = AI->getName(); AI->setName("");
2083 AllocationInst *New;
2084 if (isa<MallocInst>(AI))
2085 New = new MallocInst(CastElTy, Amt, Name);
2086 else
2087 New = new AllocaInst(CastElTy, Amt, Name);
Chris Lattner652064e2004-04-30 04:37:52 +00002088 InsertNewInstBefore(New, *AI);
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002089 return ReplaceInstUsesWith(CI, New);
2090 }
2091 }
2092
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002093 // If the source value is an instruction with only this use, we can attempt to
2094 // propagate the cast into the instruction. Also, only handle integral types
2095 // for now.
2096 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002097 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002098 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2099 const Type *DestTy = CI.getType();
2100 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2101 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2102
2103 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2104 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2105
2106 switch (SrcI->getOpcode()) {
2107 case Instruction::Add:
2108 case Instruction::Mul:
2109 case Instruction::And:
2110 case Instruction::Or:
2111 case Instruction::Xor:
2112 // If we are discarding information, or just changing the sign, rewrite.
2113 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2114 // Don't insert two casts if they cannot be eliminated. We allow two
2115 // casts to be inserted if the sizes are the same. This could only be
2116 // converting signedness, which is a noop.
2117 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
2118 !ValueRequiresCast(Op0, DestTy)) {
2119 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2120 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2121 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2122 ->getOpcode(), Op0c, Op1c);
2123 }
2124 }
2125 break;
2126 case Instruction::Shl:
2127 // Allow changing the sign of the source operand. Do not allow changing
2128 // the size of the shift, UNLESS the shift amount is a constant. We
2129 // mush not change variable sized shifts to a smaller size, because it
2130 // is undefined to shift more bits out than exist in the value.
2131 if (DestBitSize == SrcBitSize ||
2132 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2133 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2134 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2135 }
2136 break;
2137 }
2138 }
2139
Chris Lattner260ab202002-04-18 17:39:14 +00002140 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00002141}
2142
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002143/// GetSelectFoldableOperands - We want to turn code that looks like this:
2144/// %C = or %A, %B
2145/// %D = select %cond, %C, %A
2146/// into:
2147/// %C = select %cond, %B, 0
2148/// %D = or %A, %C
2149///
2150/// Assuming that the specified instruction is an operand to the select, return
2151/// a bitmask indicating which operands of this instruction are foldable if they
2152/// equal the other incoming value of the select.
2153///
2154static unsigned GetSelectFoldableOperands(Instruction *I) {
2155 switch (I->getOpcode()) {
2156 case Instruction::Add:
2157 case Instruction::Mul:
2158 case Instruction::And:
2159 case Instruction::Or:
2160 case Instruction::Xor:
2161 return 3; // Can fold through either operand.
2162 case Instruction::Sub: // Can only fold on the amount subtracted.
2163 case Instruction::Shl: // Can only fold on the shift amount.
2164 case Instruction::Shr:
2165 return 1;
2166 default:
2167 return 0; // Cannot fold
2168 }
2169}
2170
2171/// GetSelectFoldableConstant - For the same transformation as the previous
2172/// function, return the identity constant that goes into the select.
2173static Constant *GetSelectFoldableConstant(Instruction *I) {
2174 switch (I->getOpcode()) {
2175 default: assert(0 && "This cannot happen!"); abort();
2176 case Instruction::Add:
2177 case Instruction::Sub:
2178 case Instruction::Or:
2179 case Instruction::Xor:
2180 return Constant::getNullValue(I->getType());
2181 case Instruction::Shl:
2182 case Instruction::Shr:
2183 return Constant::getNullValue(Type::UByteTy);
2184 case Instruction::And:
2185 return ConstantInt::getAllOnesValue(I->getType());
2186 case Instruction::Mul:
2187 return ConstantInt::get(I->getType(), 1);
2188 }
2189}
2190
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002191Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00002192 Value *CondVal = SI.getCondition();
2193 Value *TrueVal = SI.getTrueValue();
2194 Value *FalseVal = SI.getFalseValue();
2195
2196 // select true, X, Y -> X
2197 // select false, X, Y -> Y
2198 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002199 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00002200 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002201 else {
2202 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00002203 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002204 }
Chris Lattner533bc492004-03-30 19:37:13 +00002205
2206 // select C, X, X -> X
2207 if (TrueVal == FalseVal)
2208 return ReplaceInstUsesWith(SI, TrueVal);
2209
Chris Lattner1c631e82004-04-08 04:43:23 +00002210 if (SI.getType() == Type::BoolTy)
2211 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2212 if (C == ConstantBool::True) {
2213 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002214 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002215 } else {
2216 // Change: A = select B, false, C --> A = and !B, C
2217 Value *NotCond =
2218 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2219 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002220 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002221 }
2222 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2223 if (C == ConstantBool::False) {
2224 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002225 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002226 } else {
2227 // Change: A = select B, C, true --> A = or !B, C
2228 Value *NotCond =
2229 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2230 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002231 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002232 }
2233 }
2234
Chris Lattner183b3362004-04-09 19:05:30 +00002235 // Selecting between two integer constants?
2236 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2237 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2238 // select C, 1, 0 -> cast C to int
2239 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2240 return new CastInst(CondVal, SI.getType());
2241 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2242 // select C, 0, 1 -> cast !C to int
2243 Value *NotCond =
2244 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00002245 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00002246 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00002247 }
Chris Lattner35167c32004-06-09 07:59:58 +00002248
2249 // If one of the constants is zero (we know they can't both be) and we
2250 // have a setcc instruction with zero, and we have an 'and' with the
2251 // non-constant value, eliminate this whole mess. This corresponds to
2252 // cases like this: ((X & 27) ? 27 : 0)
2253 if (TrueValC->isNullValue() || FalseValC->isNullValue())
2254 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
2255 if ((IC->getOpcode() == Instruction::SetEQ ||
2256 IC->getOpcode() == Instruction::SetNE) &&
2257 isa<ConstantInt>(IC->getOperand(1)) &&
2258 cast<Constant>(IC->getOperand(1))->isNullValue())
2259 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
2260 if (ICA->getOpcode() == Instruction::And &&
2261 isa<ConstantInt>(ICA->getOperand(1)) &&
2262 (ICA->getOperand(1) == TrueValC ||
2263 ICA->getOperand(1) == FalseValC) &&
2264 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
2265 // Okay, now we know that everything is set up, we just don't
2266 // know whether we have a setne or seteq and whether the true or
2267 // false val is the zero.
2268 bool ShouldNotVal = !TrueValC->isNullValue();
2269 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
2270 Value *V = ICA;
2271 if (ShouldNotVal)
2272 V = InsertNewInstBefore(BinaryOperator::create(
2273 Instruction::Xor, V, ICA->getOperand(1)), SI);
2274 return ReplaceInstUsesWith(SI, V);
2275 }
Chris Lattner533bc492004-03-30 19:37:13 +00002276 }
Chris Lattner623fba12004-04-10 22:21:27 +00002277
2278 // See if we are selecting two values based on a comparison of the two values.
2279 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
2280 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
2281 // Transform (X == Y) ? X : Y -> Y
2282 if (SCI->getOpcode() == Instruction::SetEQ)
2283 return ReplaceInstUsesWith(SI, FalseVal);
2284 // Transform (X != Y) ? X : Y -> X
2285 if (SCI->getOpcode() == Instruction::SetNE)
2286 return ReplaceInstUsesWith(SI, TrueVal);
2287 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2288
2289 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
2290 // Transform (X == Y) ? Y : X -> X
2291 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00002292 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00002293 // Transform (X != Y) ? Y : X -> Y
2294 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00002295 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00002296 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2297 }
2298 }
Chris Lattner1c631e82004-04-08 04:43:23 +00002299
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002300 // See if we can fold the select into one of our operands.
2301 if (SI.getType()->isInteger()) {
2302 // See the comment above GetSelectFoldableOperands for a description of the
2303 // transformation we are doing here.
2304 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
2305 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
2306 !isa<Constant>(FalseVal))
2307 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
2308 unsigned OpToFold = 0;
2309 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
2310 OpToFold = 1;
2311 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
2312 OpToFold = 2;
2313 }
2314
2315 if (OpToFold) {
2316 Constant *C = GetSelectFoldableConstant(TVI);
2317 std::string Name = TVI->getName(); TVI->setName("");
2318 Instruction *NewSel =
2319 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
2320 Name);
2321 InsertNewInstBefore(NewSel, SI);
2322 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
2323 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
2324 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
2325 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
2326 else {
2327 assert(0 && "Unknown instruction!!");
2328 }
2329 }
2330 }
2331
2332 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
2333 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
2334 !isa<Constant>(TrueVal))
2335 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
2336 unsigned OpToFold = 0;
2337 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
2338 OpToFold = 1;
2339 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
2340 OpToFold = 2;
2341 }
2342
2343 if (OpToFold) {
2344 Constant *C = GetSelectFoldableConstant(FVI);
2345 std::string Name = FVI->getName(); FVI->setName("");
2346 Instruction *NewSel =
2347 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
2348 Name);
2349 InsertNewInstBefore(NewSel, SI);
2350 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
2351 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
2352 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
2353 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
2354 else {
2355 assert(0 && "Unknown instruction!!");
2356 }
2357 }
2358 }
2359 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002360 return 0;
2361}
2362
2363
Chris Lattner970c33a2003-06-19 17:00:31 +00002364// CallInst simplification
2365//
2366Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00002367 // Intrinsics cannot occur in an invoke, so handle them here instead of in
2368 // visitCallSite.
2369 if (Function *F = CI.getCalledFunction())
2370 switch (F->getIntrinsicID()) {
2371 case Intrinsic::memmove:
2372 case Intrinsic::memcpy:
2373 case Intrinsic::memset:
2374 // memmove/cpy/set of zero bytes is a noop.
2375 if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
2376 if (NumBytes->isNullValue())
2377 return EraseInstFromFunction(CI);
2378 }
2379 break;
2380 default:
2381 break;
2382 }
2383
Chris Lattneraec3d942003-10-07 22:32:43 +00002384 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00002385}
2386
2387// InvokeInst simplification
2388//
2389Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00002390 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00002391}
2392
Chris Lattneraec3d942003-10-07 22:32:43 +00002393// visitCallSite - Improvements for call and invoke instructions.
2394//
2395Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002396 bool Changed = false;
2397
2398 // If the callee is a constexpr cast of a function, attempt to move the cast
2399 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00002400 if (transformConstExprCastCall(CS)) return 0;
2401
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002402 Value *Callee = CS.getCalledValue();
2403 const PointerType *PTy = cast<PointerType>(Callee->getType());
2404 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2405 if (FTy->isVarArg()) {
2406 // See if we can optimize any arguments passed through the varargs area of
2407 // the call.
2408 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
2409 E = CS.arg_end(); I != E; ++I)
2410 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
2411 // If this cast does not effect the value passed through the varargs
2412 // area, we can eliminate the use of the cast.
2413 Value *Op = CI->getOperand(0);
2414 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
2415 *I = Op;
2416 Changed = true;
2417 }
2418 }
2419 }
Chris Lattneraec3d942003-10-07 22:32:43 +00002420
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002421 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00002422}
2423
Chris Lattner970c33a2003-06-19 17:00:31 +00002424// transformConstExprCastCall - If the callee is a constexpr cast of a function,
2425// attempt to move the cast to the arguments of the call/invoke.
2426//
2427bool InstCombiner::transformConstExprCastCall(CallSite CS) {
2428 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
2429 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
2430 if (CE->getOpcode() != Instruction::Cast ||
2431 !isa<ConstantPointerRef>(CE->getOperand(0)))
2432 return false;
2433 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
2434 if (!isa<Function>(CPR->getValue())) return false;
2435 Function *Callee = cast<Function>(CPR->getValue());
2436 Instruction *Caller = CS.getInstruction();
2437
2438 // Okay, this is a cast from a function to a different type. Unless doing so
2439 // would cause a type conversion of one of our arguments, change this call to
2440 // be a direct call with arguments casted to the appropriate types.
2441 //
2442 const FunctionType *FT = Callee->getFunctionType();
2443 const Type *OldRetTy = Caller->getType();
2444
Chris Lattner1f7942f2004-01-14 06:06:08 +00002445 // Check to see if we are changing the return type...
2446 if (OldRetTy != FT->getReturnType()) {
2447 if (Callee->isExternal() &&
2448 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
2449 !Caller->use_empty())
2450 return false; // Cannot transform this return value...
2451
2452 // If the callsite is an invoke instruction, and the return value is used by
2453 // a PHI node in a successor, we cannot change the return type of the call
2454 // because there is no place to put the cast instruction (without breaking
2455 // the critical edge). Bail out in this case.
2456 if (!Caller->use_empty())
2457 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
2458 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
2459 UI != E; ++UI)
2460 if (PHINode *PN = dyn_cast<PHINode>(*UI))
2461 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00002462 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00002463 return false;
2464 }
Chris Lattner970c33a2003-06-19 17:00:31 +00002465
2466 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
2467 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2468
2469 CallSite::arg_iterator AI = CS.arg_begin();
2470 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
2471 const Type *ParamTy = FT->getParamType(i);
2472 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
2473 if (Callee->isExternal() && !isConvertible) return false;
2474 }
2475
2476 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
2477 Callee->isExternal())
2478 return false; // Do not delete arguments unless we have a function body...
2479
2480 // Okay, we decided that this is a safe thing to do: go ahead and start
2481 // inserting cast instructions as necessary...
2482 std::vector<Value*> Args;
2483 Args.reserve(NumActualArgs);
2484
2485 AI = CS.arg_begin();
2486 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
2487 const Type *ParamTy = FT->getParamType(i);
2488 if ((*AI)->getType() == ParamTy) {
2489 Args.push_back(*AI);
2490 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00002491 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
2492 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00002493 }
2494 }
2495
2496 // If the function takes more arguments than the call was taking, add them
2497 // now...
2498 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2499 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2500
2501 // If we are removing arguments to the function, emit an obnoxious warning...
2502 if (FT->getNumParams() < NumActualArgs)
2503 if (!FT->isVarArg()) {
2504 std::cerr << "WARNING: While resolving call to function '"
2505 << Callee->getName() << "' arguments were dropped!\n";
2506 } else {
2507 // Add all of the arguments in their promoted form to the arg list...
2508 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
2509 const Type *PTy = getPromotedType((*AI)->getType());
2510 if (PTy != (*AI)->getType()) {
2511 // Must promote to pass through va_arg area!
2512 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
2513 InsertNewInstBefore(Cast, *Caller);
2514 Args.push_back(Cast);
2515 } else {
2516 Args.push_back(*AI);
2517 }
2518 }
2519 }
2520
2521 if (FT->getReturnType() == Type::VoidTy)
2522 Caller->setName(""); // Void type should not have a name...
2523
2524 Instruction *NC;
2525 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00002526 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00002527 Args, Caller->getName(), Caller);
2528 } else {
2529 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
2530 }
2531
2532 // Insert a cast of the return type as necessary...
2533 Value *NV = NC;
2534 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
2535 if (NV->getType() != Type::VoidTy) {
2536 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00002537
2538 // If this is an invoke instruction, we should insert it after the first
2539 // non-phi, instruction in the normal successor block.
2540 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
2541 BasicBlock::iterator I = II->getNormalDest()->begin();
2542 while (isa<PHINode>(I)) ++I;
2543 InsertNewInstBefore(NC, *I);
2544 } else {
2545 // Otherwise, it's a call, just insert cast right after the call instr
2546 InsertNewInstBefore(NC, *Caller);
2547 }
Chris Lattner51ea1272004-02-28 05:22:00 +00002548 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00002549 } else {
2550 NV = Constant::getNullValue(Caller->getType());
2551 }
2552 }
2553
2554 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
2555 Caller->replaceAllUsesWith(NV);
2556 Caller->getParent()->getInstList().erase(Caller);
2557 removeFromWorkList(Caller);
2558 return true;
2559}
2560
2561
Chris Lattner48a44f72002-05-02 17:06:02 +00002562
Chris Lattnerbbbdd852002-05-06 18:06:38 +00002563// PHINode simplification
2564//
Chris Lattner113f4f42002-06-25 16:13:24 +00002565Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner91daeb52003-12-19 05:58:40 +00002566 if (Value *V = hasConstantValue(&PN))
2567 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00002568
2569 // If the only user of this instruction is a cast instruction, and all of the
2570 // incoming values are constants, change this PHI to merge together the casted
2571 // constants.
2572 if (PN.hasOneUse())
2573 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
2574 if (CI->getType() != PN.getType()) { // noop casts will be folded
2575 bool AllConstant = true;
2576 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2577 if (!isa<Constant>(PN.getIncomingValue(i))) {
2578 AllConstant = false;
2579 break;
2580 }
2581 if (AllConstant) {
2582 // Make a new PHI with all casted values.
2583 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
2584 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2585 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
2586 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
2587 PN.getIncomingBlock(i));
2588 }
2589
2590 // Update the cast instruction.
2591 CI->setOperand(0, New);
2592 WorkList.push_back(CI); // revisit the cast instruction to fold.
2593 WorkList.push_back(New); // Make sure to revisit the new Phi
2594 return &PN; // PN is now dead!
2595 }
2596 }
Chris Lattner91daeb52003-12-19 05:58:40 +00002597 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00002598}
2599
Chris Lattner69193f92004-04-05 01:30:19 +00002600static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
2601 Instruction *InsertPoint,
2602 InstCombiner *IC) {
2603 unsigned PS = IC->getTargetData().getPointerSize();
2604 const Type *VTy = V->getType();
2605 Instruction *Cast;
2606 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
2607 // We must insert a cast to ensure we sign-extend.
2608 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
2609 V->getName()), *InsertPoint);
2610 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
2611 *InsertPoint);
2612}
2613
Chris Lattner48a44f72002-05-02 17:06:02 +00002614
Chris Lattner113f4f42002-06-25 16:13:24 +00002615Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00002616 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00002617 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00002618 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002619 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00002620 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002621
2622 bool HasZeroPointerIndex = false;
2623 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
2624 HasZeroPointerIndex = C->isNullValue();
2625
2626 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00002627 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00002628
Chris Lattner69193f92004-04-05 01:30:19 +00002629 // Eliminate unneeded casts for indices.
2630 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00002631 gep_type_iterator GTI = gep_type_begin(GEP);
2632 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
2633 if (isa<SequentialType>(*GTI)) {
2634 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
2635 Value *Src = CI->getOperand(0);
2636 const Type *SrcTy = Src->getType();
2637 const Type *DestTy = CI->getType();
2638 if (Src->getType()->isInteger()) {
2639 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
2640 // We can always eliminate a cast from ulong or long to the other.
2641 // We can always eliminate a cast from uint to int or the other on
2642 // 32-bit pointer platforms.
2643 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
2644 MadeChange = true;
2645 GEP.setOperand(i, Src);
2646 }
2647 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2648 SrcTy->getPrimitiveSize() == 4) {
2649 // We can always eliminate a cast from int to [u]long. We can
2650 // eliminate a cast from uint to [u]long iff the target is a 32-bit
2651 // pointer target.
2652 if (SrcTy->isSigned() ||
2653 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
2654 MadeChange = true;
2655 GEP.setOperand(i, Src);
2656 }
Chris Lattner69193f92004-04-05 01:30:19 +00002657 }
2658 }
2659 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00002660 // If we are using a wider index than needed for this platform, shrink it
2661 // to what we need. If the incoming value needs a cast instruction,
2662 // insert it. This explicit cast can make subsequent optimizations more
2663 // obvious.
2664 Value *Op = GEP.getOperand(i);
2665 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00002666 if (Constant *C = dyn_cast<Constant>(Op)) {
2667 GEP.setOperand(i, ConstantExpr::getCast(C, TD->getIntPtrType()));
2668 MadeChange = true;
2669 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00002670 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
2671 Op->getName()), GEP);
2672 GEP.setOperand(i, Op);
2673 MadeChange = true;
2674 }
Chris Lattner69193f92004-04-05 01:30:19 +00002675 }
2676 if (MadeChange) return &GEP;
2677
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002678 // Combine Indices - If the source pointer to this getelementptr instruction
2679 // is a getelementptr instruction, combine the indices of the two
2680 // getelementptr instructions into a single instruction.
2681 //
Chris Lattner57c67b02004-03-25 22:59:29 +00002682 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00002683 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00002684 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00002685 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00002686 if (CE->getOpcode() == Instruction::GetElementPtr)
2687 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
2688 }
2689
2690 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00002691 // Note that if our source is a gep chain itself that we wait for that
2692 // chain to be resolved before we perform this transformation. This
2693 // avoids us creating a TON of code in some cases.
2694 //
2695 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
2696 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
2697 return 0; // Wait until our source is folded to completion.
2698
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002699 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00002700
2701 // Find out whether the last index in the source GEP is a sequential idx.
2702 bool EndsWithSequential = false;
2703 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
2704 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00002705 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00002706
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002707 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00002708 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00002709 // Replace: gep (gep %P, long B), long A, ...
2710 // With: T = long A+B; gep %P, T, ...
2711 //
Chris Lattner5f667a62004-05-07 22:09:22 +00002712 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00002713 if (SO1 == Constant::getNullValue(SO1->getType())) {
2714 Sum = GO1;
2715 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
2716 Sum = SO1;
2717 } else {
2718 // If they aren't the same type, convert both to an integer of the
2719 // target's pointer size.
2720 if (SO1->getType() != GO1->getType()) {
2721 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
2722 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
2723 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
2724 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
2725 } else {
2726 unsigned PS = TD->getPointerSize();
2727 Instruction *Cast;
2728 if (SO1->getType()->getPrimitiveSize() == PS) {
2729 // Convert GO1 to SO1's type.
2730 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
2731
2732 } else if (GO1->getType()->getPrimitiveSize() == PS) {
2733 // Convert SO1 to GO1's type.
2734 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
2735 } else {
2736 const Type *PT = TD->getIntPtrType();
2737 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
2738 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
2739 }
2740 }
2741 }
Chris Lattner5f667a62004-05-07 22:09:22 +00002742 if (isa<Constant>(SO1) && isa<Constant>(GO1))
2743 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
2744 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002745 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
2746 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00002747 }
Chris Lattner69193f92004-04-05 01:30:19 +00002748 }
Chris Lattner5f667a62004-05-07 22:09:22 +00002749
2750 // Recycle the GEP we already have if possible.
2751 if (SrcGEPOperands.size() == 2) {
2752 GEP.setOperand(0, SrcGEPOperands[0]);
2753 GEP.setOperand(1, Sum);
2754 return &GEP;
2755 } else {
2756 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2757 SrcGEPOperands.end()-1);
2758 Indices.push_back(Sum);
2759 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
2760 }
Chris Lattner69193f92004-04-05 01:30:19 +00002761 } else if (isa<Constant>(*GEP.idx_begin()) &&
2762 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00002763 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002764 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00002765 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2766 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002767 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
2768 }
2769
2770 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00002771 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002772
Chris Lattner5f667a62004-05-07 22:09:22 +00002773 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002774 // GEP of global variable. If all of the indices for this GEP are
2775 // constants, we can promote this to a constexpr instead of an instruction.
2776
2777 // Scan for nonconstants...
2778 std::vector<Constant*> Indices;
2779 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
2780 for (; I != E && isa<Constant>(*I); ++I)
2781 Indices.push_back(cast<Constant>(*I));
2782
2783 if (I == E) { // If they are all constants...
Chris Lattner46b3d302003-04-16 22:40:51 +00002784 Constant *CE =
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002785 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
2786
2787 // Replace all uses of the GEP with the new constexpr...
2788 return ReplaceInstUsesWith(GEP, CE);
2789 }
Chris Lattner5f667a62004-05-07 22:09:22 +00002790 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002791 if (CE->getOpcode() == Instruction::Cast) {
2792 if (HasZeroPointerIndex) {
2793 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
2794 // into : GEP [10 x ubyte]* X, long 0, ...
2795 //
2796 // This occurs when the program declares an array extern like "int X[];"
2797 //
2798 Constant *X = CE->getOperand(0);
2799 const PointerType *CPTy = cast<PointerType>(CE->getType());
2800 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
2801 if (const ArrayType *XATy =
2802 dyn_cast<ArrayType>(XTy->getElementType()))
2803 if (const ArrayType *CATy =
2804 dyn_cast<ArrayType>(CPTy->getElementType()))
2805 if (CATy->getElementType() == XATy->getElementType()) {
2806 // At this point, we know that the cast source type is a pointer
2807 // to an array of the same type as the destination pointer
2808 // array. Because the array type is never stepped over (there
2809 // is a leading zero) we can fold the cast into this GEP.
2810 GEP.setOperand(0, X);
2811 return &GEP;
2812 }
2813 }
2814 }
Chris Lattnerca081252001-12-14 16:52:21 +00002815 }
2816
Chris Lattnerca081252001-12-14 16:52:21 +00002817 return 0;
2818}
2819
Chris Lattner1085bdf2002-11-04 16:18:53 +00002820Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
2821 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
2822 if (AI.isArrayAllocation()) // Check C != 1
2823 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
2824 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00002825 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00002826
2827 // Create and insert the replacement instruction...
2828 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00002829 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00002830 else {
2831 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00002832 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00002833 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00002834
2835 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00002836
2837 // Scan to the end of the allocation instructions, to skip over a block of
2838 // allocas if possible...
2839 //
2840 BasicBlock::iterator It = New;
2841 while (isa<AllocationInst>(*It)) ++It;
2842
2843 // Now that I is pointing to the first non-allocation-inst in the block,
2844 // insert our getelementptr instruction...
2845 //
Chris Lattner69193f92004-04-05 01:30:19 +00002846 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00002847 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
2848
2849 // Now make everything use the getelementptr instead of the original
2850 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00002851 return ReplaceInstUsesWith(AI, V);
Chris Lattner1085bdf2002-11-04 16:18:53 +00002852 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00002853
2854 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
2855 // Note that we only do this for alloca's, because malloc should allocate and
2856 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00002857 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
2858 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00002859 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
2860
Chris Lattner1085bdf2002-11-04 16:18:53 +00002861 return 0;
2862}
2863
Chris Lattner8427bff2003-12-07 01:24:23 +00002864Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
2865 Value *Op = FI.getOperand(0);
2866
2867 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
2868 if (CastInst *CI = dyn_cast<CastInst>(Op))
2869 if (isa<PointerType>(CI->getOperand(0)->getType())) {
2870 FI.setOperand(0, CI->getOperand(0));
2871 return &FI;
2872 }
2873
Chris Lattnerf3a36602004-02-28 04:57:37 +00002874 // If we have 'free null' delete the instruction. This can happen in stl code
2875 // when lots of inlining happens.
Chris Lattner51ea1272004-02-28 05:22:00 +00002876 if (isa<ConstantPointerNull>(Op))
2877 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00002878
Chris Lattner8427bff2003-12-07 01:24:23 +00002879 return 0;
2880}
2881
2882
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002883/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
2884/// constantexpr, return the constant value being addressed by the constant
2885/// expression, or null if something is funny.
2886///
2887static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00002888 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002889 return 0; // Do not allow stepping over the value!
2890
2891 // Loop over all of the operands, tracking down which value we are
2892 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00002893 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2894 for (++I; I != E; ++I)
2895 if (const StructType *STy = dyn_cast<StructType>(*I)) {
2896 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
2897 assert(CU->getValue() < STy->getNumElements() &&
2898 "Struct index out of range!");
2899 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
2900 C = cast<Constant>(CS->getValues()[CU->getValue()]);
2901 } else if (isa<ConstantAggregateZero>(C)) {
2902 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
2903 } else {
2904 return 0;
2905 }
2906 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
2907 const ArrayType *ATy = cast<ArrayType>(*I);
2908 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
2909 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
2910 C = cast<Constant>(CA->getValues()[CI->getRawValue()]);
2911 else if (isa<ConstantAggregateZero>(C))
2912 C = Constant::getNullValue(ATy->getElementType());
2913 else
2914 return 0;
2915 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002916 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00002917 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002918 return C;
2919}
2920
2921Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
2922 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00002923 if (LI.isVolatile()) return 0;
2924
Chris Lattner6679e462004-04-14 03:28:36 +00002925 if (Constant *C = dyn_cast<Constant>(Op))
2926 if (C->isNullValue()) // load null -> 0
2927 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
2928 else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C))
2929 Op = CPR->getValue();
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002930
2931 // Instcombine load (constant global) into the value loaded...
2932 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002933 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002934 return ReplaceInstUsesWith(LI, GV->getInitializer());
2935
2936 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
2937 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
2938 if (CE->getOpcode() == Instruction::GetElementPtr)
2939 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
2940 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002941 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002942 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
2943 return ReplaceInstUsesWith(LI, V);
Chris Lattnere228ee52004-04-08 20:39:49 +00002944
2945 // load (cast X) --> cast (load X) iff safe
2946 if (CastInst *CI = dyn_cast<CastInst>(Op)) {
2947 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
2948 if (const PointerType *SrcTy =
2949 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
2950 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerd9e58132004-05-07 15:35:56 +00002951 if (SrcPTy->isSized() && DestPTy->isSized() &&
2952 TD->getTypeSize(SrcPTy) == TD->getTypeSize(DestPTy) &&
Chris Lattnere228ee52004-04-08 20:39:49 +00002953 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
2954 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
2955 // Okay, we are casting from one integer or pointer type to another of
2956 // the same size. Instead of casting the pointer before the load, cast
2957 // the result of the loaded value.
2958 Value *NewLoad = InsertNewInstBefore(new LoadInst(CI->getOperand(0),
2959 CI->getName()), LI);
2960 // Now cast the result of the load.
2961 return new CastInst(NewLoad, LI.getType());
2962 }
2963 }
2964 }
2965
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002966 return 0;
2967}
2968
2969
Chris Lattner9eef8a72003-06-04 04:46:00 +00002970Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2971 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattner4f7acca2004-02-27 06:27:46 +00002972 if (BI.isConditional() && !isa<Constant>(BI.getCondition())) {
Chris Lattnere967b342003-06-04 05:10:11 +00002973 if (Value *V = dyn_castNotVal(BI.getCondition())) {
2974 BasicBlock *TrueDest = BI.getSuccessor(0);
2975 BasicBlock *FalseDest = BI.getSuccessor(1);
2976 // Swap Destinations and condition...
2977 BI.setCondition(V);
2978 BI.setSuccessor(0, FalseDest);
2979 BI.setSuccessor(1, TrueDest);
2980 return &BI;
Chris Lattner4f7acca2004-02-27 06:27:46 +00002981 } else if (SetCondInst *I = dyn_cast<SetCondInst>(BI.getCondition())) {
2982 // Cannonicalize setne -> seteq
2983 if ((I->getOpcode() == Instruction::SetNE ||
2984 I->getOpcode() == Instruction::SetLE ||
2985 I->getOpcode() == Instruction::SetGE) && I->hasOneUse()) {
2986 std::string Name = I->getName(); I->setName("");
2987 Instruction::BinaryOps NewOpcode =
2988 SetCondInst::getInverseCondition(I->getOpcode());
2989 Value *NewSCC = BinaryOperator::create(NewOpcode, I->getOperand(0),
2990 I->getOperand(1), Name, I);
2991 BasicBlock *TrueDest = BI.getSuccessor(0);
2992 BasicBlock *FalseDest = BI.getSuccessor(1);
2993 // Swap Destinations and condition...
2994 BI.setCondition(NewSCC);
2995 BI.setSuccessor(0, FalseDest);
2996 BI.setSuccessor(1, TrueDest);
2997 removeFromWorkList(I);
2998 I->getParent()->getInstList().erase(I);
2999 WorkList.push_back(cast<Instruction>(NewSCC));
3000 return &BI;
3001 }
Chris Lattnere967b342003-06-04 05:10:11 +00003002 }
Chris Lattner4f7acca2004-02-27 06:27:46 +00003003 }
Chris Lattner9eef8a72003-06-04 04:46:00 +00003004 return 0;
3005}
Chris Lattner1085bdf2002-11-04 16:18:53 +00003006
Chris Lattnerca081252001-12-14 16:52:21 +00003007
Chris Lattner99f48c62002-09-02 04:59:56 +00003008void InstCombiner::removeFromWorkList(Instruction *I) {
3009 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3010 WorkList.end());
3011}
3012
Chris Lattner113f4f42002-06-25 16:13:24 +00003013bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00003014 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003015 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00003016
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003017 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3018 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00003019
Chris Lattnerca081252001-12-14 16:52:21 +00003020
3021 while (!WorkList.empty()) {
3022 Instruction *I = WorkList.back(); // Get an instruction from the worklist
3023 WorkList.pop_back();
3024
Misha Brukman632df282002-10-29 23:06:16 +00003025 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00003026 // Check to see if we can DIE the instruction...
3027 if (isInstructionTriviallyDead(I)) {
3028 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003029 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00003030 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00003031 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003032
3033 I->getParent()->getInstList().erase(I);
3034 removeFromWorkList(I);
3035 continue;
3036 }
Chris Lattner99f48c62002-09-02 04:59:56 +00003037
Misha Brukman632df282002-10-29 23:06:16 +00003038 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00003039 if (Constant *C = ConstantFoldInstruction(I)) {
3040 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00003041 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00003042 ReplaceInstUsesWith(*I, C);
3043
Chris Lattner99f48c62002-09-02 04:59:56 +00003044 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003045 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00003046 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003047 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00003048 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003049
Chris Lattner57c67b02004-03-25 22:59:29 +00003050 // Check to see if any of the operands of this instruction are a
3051 // ConstantPointerRef. Since they sneak in all over the place and inhibit
3052 // optimization, we want to strip them out unconditionally!
3053 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3054 if (ConstantPointerRef *CPR =
3055 dyn_cast<ConstantPointerRef>(I->getOperand(i))) {
3056 I->setOperand(i, CPR->getValue());
3057 Changed = true;
3058 }
3059
Chris Lattnerca081252001-12-14 16:52:21 +00003060 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003061 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00003062 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00003063 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00003064 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003065 DEBUG(std::cerr << "IC: Old = " << *I
3066 << " New = " << *Result);
3067
Chris Lattner396dbfe2004-06-09 05:08:07 +00003068 // Everything uses the new instruction now.
3069 I->replaceAllUsesWith(Result);
3070
3071 // Push the new instruction and any users onto the worklist.
3072 WorkList.push_back(Result);
3073 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003074
3075 // Move the name to the new instruction first...
3076 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00003077 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003078
3079 // Insert the new instruction into the basic block...
3080 BasicBlock *InstParent = I->getParent();
3081 InstParent->getInstList().insert(I, Result);
3082
Chris Lattner63d75af2004-05-01 23:27:23 +00003083 // Make sure that we reprocess all operands now that we reduced their
3084 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003085 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3086 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3087 WorkList.push_back(OpI);
3088
Chris Lattner396dbfe2004-06-09 05:08:07 +00003089 // Instructions can end up on the worklist more than once. Make sure
3090 // we do not process an instruction that has been deleted.
3091 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003092
3093 // Erase the old instruction.
3094 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003095 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003096 DEBUG(std::cerr << "IC: MOD = " << *I);
3097
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003098 // If the instruction was modified, it's possible that it is now dead.
3099 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00003100 if (isInstructionTriviallyDead(I)) {
3101 // Make sure we process all operands now that we are reducing their
3102 // use counts.
3103 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3104 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3105 WorkList.push_back(OpI);
3106
3107 // Instructions may end up in the worklist more than once. Erase all
3108 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00003109 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00003110 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00003111 } else {
3112 WorkList.push_back(Result);
3113 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003114 }
Chris Lattner053c0932002-05-14 15:24:07 +00003115 }
Chris Lattner260ab202002-04-18 17:39:14 +00003116 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00003117 }
3118 }
3119
Chris Lattner260ab202002-04-18 17:39:14 +00003120 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00003121}
3122
Chris Lattner8427bff2003-12-07 01:24:23 +00003123Pass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00003124 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00003125}
Brian Gaeke960707c2003-11-11 22:41:34 +00003126