blob: 724243369b500f19d7ac19e14bdc5eb5da6d7046 [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:
15// %Y = add int 1, %X
16// %Z = add int 1, %Y
17// into:
18// %Z = add int 2, %X
19//
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 Lattnerb4cfa7f2002-05-07 20:03:00 +000036#include "llvm/Transforms/Scalar.h"
Chris Lattner471bd762003-05-22 19:07:21 +000037#include "llvm/Instructions.h"
Chris Lattner51ea1272004-02-28 05:22:00 +000038#include "llvm/Intrinsics.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner34428442003-05-27 16:40:51 +000040#include "llvm/Constants.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner60a65912002-02-12 21:07:25 +000046#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000047#include "llvm/Support/InstVisitor.h"
Chris Lattner970c33a2003-06-19 17:00:31 +000048#include "llvm/Support/CallSite.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000049#include "Support/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000050#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000051using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000052
Chris Lattner260ab202002-04-18 17:39:14 +000053namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000054 Statistic<> NumCombined ("instcombine", "Number of insts combined");
55 Statistic<> NumConstProp("instcombine", "Number of constant folds");
56 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
57
Chris Lattnerc8e66542002-04-27 06:56:12 +000058 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000059 public InstVisitor<InstCombiner, Instruction*> {
60 // Worklist of all of the instructions that need to be simplified.
61 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000062 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000063
Chris Lattner51ea1272004-02-28 05:22:00 +000064 /// AddUsersToWorkList - When an instruction is simplified, add all users of
65 /// the instruction to the work lists because they might get more simplified
66 /// now.
67 ///
68 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000069 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000070 UI != UE; ++UI)
71 WorkList.push_back(cast<Instruction>(*UI));
72 }
73
Chris Lattner51ea1272004-02-28 05:22:00 +000074 /// AddUsesToWorkList - When an instruction is simplified, add operands to
75 /// the work lists because they might get more simplified now.
76 ///
77 void AddUsesToWorkList(Instruction &I) {
78 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
79 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
80 WorkList.push_back(Op);
81 }
82
Chris Lattner99f48c62002-09-02 04:59:56 +000083 // removeFromWorkList - remove all instances of I from the worklist.
84 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000085 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000086 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000087
Chris Lattnerf12cc842002-04-28 21:27:06 +000088 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000089 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000090 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000091 }
92
Chris Lattner260ab202002-04-18 17:39:14 +000093 // Visitation implementation - Implement instruction combining for different
94 // instruction types. The semantics are as follows:
95 // Return Value:
96 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +000097 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +000098 // otherwise - Change was made, replace I with returned instruction
99 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000100 Instruction *visitAdd(BinaryOperator &I);
101 Instruction *visitSub(BinaryOperator &I);
102 Instruction *visitMul(BinaryOperator &I);
103 Instruction *visitDiv(BinaryOperator &I);
104 Instruction *visitRem(BinaryOperator &I);
105 Instruction *visitAnd(BinaryOperator &I);
106 Instruction *visitOr (BinaryOperator &I);
107 Instruction *visitXor(BinaryOperator &I);
108 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000109 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000110 Instruction *visitCastInst(CastInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000111 Instruction *visitCallInst(CallInst &CI);
112 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000113 Instruction *visitPHINode(PHINode &PN);
114 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000115 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000116 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000117 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000118 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner260ab202002-04-18 17:39:14 +0000119
120 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000121 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000122
Chris Lattner970c33a2003-06-19 17:00:31 +0000123 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000124 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000125 bool transformConstExprCastCall(CallSite CS);
126
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000127 // InsertNewInstBefore - insert an instruction New before instruction Old
128 // in the program. Add the new instruction to the worklist.
129 //
Chris Lattnere79e8542004-02-23 06:38:22 +0000130 Value *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000131 assert(New && New->getParent() == 0 &&
132 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000133 BasicBlock *BB = Old.getParent();
134 BB->getInstList().insert(&Old, New); // Insert inst
135 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000136 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000137 }
138
Chris Lattner3ac7c262003-08-13 20:16:26 +0000139 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000140 // ReplaceInstUsesWith - This method is to be used when an instruction is
141 // found to be dead, replacable with another preexisting expression. Here
142 // we add all uses of I to the worklist, replace all uses of I with the new
143 // value, then return I, so that the inst combiner will know that I was
144 // modified.
145 //
146 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000147 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000148 I.replaceAllUsesWith(V);
149 return &I;
150 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000151
152 // EraseInstFromFunction - When dealing with an instruction that has side
153 // effects or produces a void value, we can't rely on DCE to delete the
154 // instruction. Instead, visit methods should return the value returned by
155 // this function.
156 Instruction *EraseInstFromFunction(Instruction &I) {
157 assert(I.use_empty() && "Cannot erase instruction that is used!");
158 AddUsesToWorkList(I);
159 removeFromWorkList(&I);
160 I.getParent()->getInstList().erase(&I);
161 return 0; // Don't do anything with FI
162 }
163
164
Chris Lattner3ac7c262003-08-13 20:16:26 +0000165 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000166 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
167 /// InsertBefore instruction. This is specialized a bit to avoid inserting
168 /// casts that are known to not do anything...
169 ///
170 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
171 Instruction *InsertBefore);
172
Chris Lattner7fb29e12003-03-11 00:12:48 +0000173 // SimplifyCommutative - This performs a few simplifications for commutative
174 // operators...
175 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000176
177 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
178 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner260ab202002-04-18 17:39:14 +0000179 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000180
Chris Lattnerc8b70922002-07-26 21:12:46 +0000181 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000182}
183
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000184// getComplexity: Assign a complexity or rank value to LLVM Values...
185// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
186static unsigned getComplexity(Value *V) {
187 if (isa<Instruction>(V)) {
188 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
189 return 2;
190 return 3;
191 }
192 if (isa<Argument>(V)) return 2;
193 return isa<Constant>(V) ? 0 : 1;
194}
Chris Lattner260ab202002-04-18 17:39:14 +0000195
Chris Lattner7fb29e12003-03-11 00:12:48 +0000196// isOnlyUse - Return true if this instruction will be deleted if we stop using
197// it.
198static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000199 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000200}
201
Chris Lattnere79e8542004-02-23 06:38:22 +0000202// getSignedIntegralType - Given an unsigned integral type, return the signed
203// version of it that has the same size.
204static const Type *getSignedIntegralType(const Type *Ty) {
205 switch (Ty->getPrimitiveID()) {
206 default: assert(0 && "Invalid unsigned integer type!"); abort();
207 case Type::UByteTyID: return Type::SByteTy;
208 case Type::UShortTyID: return Type::ShortTy;
209 case Type::UIntTyID: return Type::IntTy;
210 case Type::ULongTyID: return Type::LongTy;
211 }
212}
213
214// getPromotedType - Return the specified type promoted as it would be to pass
215// though a va_arg area...
216static const Type *getPromotedType(const Type *Ty) {
217 switch (Ty->getPrimitiveID()) {
218 case Type::SByteTyID:
219 case Type::ShortTyID: return Type::IntTy;
220 case Type::UByteTyID:
221 case Type::UShortTyID: return Type::UIntTy;
222 case Type::FloatTyID: return Type::DoubleTy;
223 default: return Ty;
224 }
225}
226
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000227// SimplifyCommutative - This performs a few simplifications for commutative
228// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000229//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000230// 1. Order operands such that they are listed from right (least complex) to
231// left (most complex). This puts constants before unary operators before
232// binary operators.
233//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000234// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
235// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000236//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000237bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000238 bool Changed = false;
239 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
240 Changed = !I.swapOperands();
241
242 if (!I.isAssociative()) return Changed;
243 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000244 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
245 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
246 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000247 Constant *Folded = ConstantExpr::get(I.getOpcode(),
248 cast<Constant>(I.getOperand(1)),
249 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000250 I.setOperand(0, Op->getOperand(0));
251 I.setOperand(1, Folded);
252 return true;
253 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
254 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
255 isOnlyUse(Op) && isOnlyUse(Op1)) {
256 Constant *C1 = cast<Constant>(Op->getOperand(1));
257 Constant *C2 = cast<Constant>(Op1->getOperand(1));
258
259 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000260 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000261 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
262 Op1->getOperand(0),
263 Op1->getName(), &I);
264 WorkList.push_back(New);
265 I.setOperand(0, New);
266 I.setOperand(1, Folded);
267 return true;
268 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000269 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000270 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000271}
Chris Lattnerca081252001-12-14 16:52:21 +0000272
Chris Lattnerbb74e222003-03-10 23:06:50 +0000273// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
274// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000275//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000276static inline Value *dyn_castNegVal(Value *V) {
277 if (BinaryOperator::isNeg(V))
278 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
279
Chris Lattner9244df62003-04-30 22:19:10 +0000280 // Constants can be considered to be negated values if they can be folded...
281 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner34428442003-05-27 16:40:51 +0000282 return ConstantExpr::get(Instruction::Sub,
283 Constant::getNullValue(V->getType()), C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000284 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000285}
286
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000287static Constant *NotConstant(Constant *C) {
288 return ConstantExpr::get(Instruction::Xor, C,
289 ConstantIntegral::getAllOnesValue(C->getType()));
290}
291
Chris Lattnerbb74e222003-03-10 23:06:50 +0000292static inline Value *dyn_castNotVal(Value *V) {
293 if (BinaryOperator::isNot(V))
294 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
295
296 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000297 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000298 return NotConstant(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000299 return 0;
300}
301
Chris Lattner7fb29e12003-03-11 00:12:48 +0000302// dyn_castFoldableMul - If this value is a multiply that can be folded into
303// other computations (because it has a constant operand), return the
304// non-constant operand of the multiply.
305//
306static inline Value *dyn_castFoldableMul(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000307 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000308 if (Instruction *I = dyn_cast<Instruction>(V))
309 if (I->getOpcode() == Instruction::Mul)
310 if (isa<Constant>(I->getOperand(1)))
311 return I->getOperand(0);
312 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000313}
Chris Lattner31ae8632002-08-14 17:51:49 +0000314
Chris Lattner7fb29e12003-03-11 00:12:48 +0000315// dyn_castMaskingAnd - If this value is an And instruction masking a value with
316// a constant, return the constant being anded with.
317//
Chris Lattner01d56392003-08-12 19:17:27 +0000318template<class ValueType>
319static inline Constant *dyn_castMaskingAnd(ValueType *V) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000320 if (Instruction *I = dyn_cast<Instruction>(V))
321 if (I->getOpcode() == Instruction::And)
322 return dyn_cast<Constant>(I->getOperand(1));
323
324 // If this is a constant, it acts just like we were masking with it.
325 return dyn_cast<Constant>(V);
326}
Chris Lattner3082c5a2003-02-18 19:28:33 +0000327
328// Log2 - Calculate the log base 2 for the specified value if it is exactly a
329// power of 2.
330static unsigned Log2(uint64_t Val) {
331 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
332 unsigned Count = 0;
333 while (Val != 1) {
334 if (Val & 1) return 0; // Multiple bits set?
335 Val >>= 1;
336 ++Count;
337 }
338 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000339}
340
Chris Lattnerb8b97502003-08-13 19:01:45 +0000341
342/// AssociativeOpt - Perform an optimization on an associative operator. This
343/// function is designed to check a chain of associative operators for a
344/// potential to apply a certain optimization. Since the optimization may be
345/// applicable if the expression was reassociated, this checks the chain, then
346/// reassociates the expression as necessary to expose the optimization
347/// opportunity. This makes use of a special Functor, which must define
348/// 'shouldApply' and 'apply' methods.
349///
350template<typename Functor>
351Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
352 unsigned Opcode = Root.getOpcode();
353 Value *LHS = Root.getOperand(0);
354
355 // Quick check, see if the immediate LHS matches...
356 if (F.shouldApply(LHS))
357 return F.apply(Root);
358
359 // Otherwise, if the LHS is not of the same opcode as the root, return.
360 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000361 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000362 // Should we apply this transform to the RHS?
363 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
364
365 // If not to the RHS, check to see if we should apply to the LHS...
366 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
367 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
368 ShouldApply = true;
369 }
370
371 // If the functor wants to apply the optimization to the RHS of LHSI,
372 // reassociate the expression from ((? op A) op B) to (? op (A op B))
373 if (ShouldApply) {
374 BasicBlock *BB = Root.getParent();
375 // All of the instructions have a single use and have no side-effects,
376 // because of this, we can pull them all into the current basic block.
377 if (LHSI->getParent() != BB) {
378 // Move all of the instructions from root to LHSI into the current
379 // block.
380 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
381 Instruction *LastUse = &Root;
382 while (TmpLHSI->getParent() == BB) {
383 LastUse = TmpLHSI;
384 TmpLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
385 }
386
387 // Loop over all of the instructions in other blocks, moving them into
388 // the current one.
389 Value *TmpLHS = TmpLHSI;
390 do {
391 TmpLHSI = cast<Instruction>(TmpLHS);
392 // Remove from current block...
393 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
394 // Insert before the last instruction...
395 BB->getInstList().insert(LastUse, TmpLHSI);
396 TmpLHS = TmpLHSI->getOperand(0);
397 } while (TmpLHSI != LHSI);
398 }
399
400 // Now all of the instructions are in the current basic block, go ahead
401 // and perform the reassociation.
402 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
403
404 // First move the selected RHS to the LHS of the root...
405 Root.setOperand(0, LHSI->getOperand(1));
406
407 // Make what used to be the LHS of the root be the user of the root...
408 Value *ExtraOperand = TmpLHSI->getOperand(1);
409 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
410 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
411 BB->getInstList().remove(&Root); // Remove root from the BB
412 BB->getInstList().insert(TmpLHSI, &Root); // Insert root before TmpLHSI
413
414 // Now propagate the ExtraOperand down the chain of instructions until we
415 // get to LHSI.
416 while (TmpLHSI != LHSI) {
417 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
418 Value *NextOp = NextLHSI->getOperand(1);
419 NextLHSI->setOperand(1, ExtraOperand);
420 TmpLHSI = NextLHSI;
421 ExtraOperand = NextOp;
422 }
423
424 // Now that the instructions are reassociated, have the functor perform
425 // the transformation...
426 return F.apply(Root);
427 }
428
429 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
430 }
431 return 0;
432}
433
434
435// AddRHS - Implements: X + X --> X << 1
436struct AddRHS {
437 Value *RHS;
438 AddRHS(Value *rhs) : RHS(rhs) {}
439 bool shouldApply(Value *LHS) const { return LHS == RHS; }
440 Instruction *apply(BinaryOperator &Add) const {
441 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
442 ConstantInt::get(Type::UByteTy, 1));
443 }
444};
445
446// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
447// iff C1&C2 == 0
448struct AddMaskingAnd {
449 Constant *C2;
450 AddMaskingAnd(Constant *c) : C2(c) {}
451 bool shouldApply(Value *LHS) const {
452 if (Constant *C1 = dyn_castMaskingAnd(LHS))
453 return ConstantExpr::get(Instruction::And, C1, C2)->isNullValue();
454 return false;
455 }
456 Instruction *apply(BinaryOperator &Add) const {
457 return BinaryOperator::create(Instruction::Or, Add.getOperand(0),
458 Add.getOperand(1));
459 }
460};
461
462
463
Chris Lattner113f4f42002-06-25 16:13:24 +0000464Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000465 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000466 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000467
Chris Lattnerb8b97502003-08-13 19:01:45 +0000468 // X + 0 --> X
Chris Lattner8ee05932004-02-24 18:10:14 +0000469 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
470 RHS == Constant::getNullValue(I.getType()))
Chris Lattnere6794492002-08-12 21:17:25 +0000471 return ReplaceInstUsesWith(I, LHS);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000472
Chris Lattnerb8b97502003-08-13 19:01:45 +0000473 // X + X --> X << 1
474 if (I.getType()->isInteger())
475 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattnerede3fe02003-08-13 04:18:28 +0000476
Chris Lattner147e9752002-05-08 22:46:53 +0000477 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000478 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner147e9752002-05-08 22:46:53 +0000479 return BinaryOperator::create(Instruction::Sub, RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000480
481 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000482 if (!isa<Constant>(RHS))
483 if (Value *V = dyn_castNegVal(RHS))
484 return BinaryOperator::create(Instruction::Sub, LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000485
Chris Lattner57c8d992003-02-18 19:57:07 +0000486 // X*C + X --> X * (C+1)
487 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000488 Constant *CP1 =
489 ConstantExpr::get(Instruction::Add,
490 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
491 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000492 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
493 }
494
495 // X + X*C --> X * (C+1)
496 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000497 Constant *CP1 =
498 ConstantExpr::get(Instruction::Add,
499 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
500 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000501 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
502 }
503
Chris Lattnerb8b97502003-08-13 19:01:45 +0000504 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
505 if (Constant *C2 = dyn_castMaskingAnd(RHS))
506 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000507
Chris Lattnerb9cde762003-10-02 15:11:26 +0000508 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
509 if (Instruction *ILHS = dyn_cast<Instruction>(LHS)) {
510 switch (ILHS->getOpcode()) {
511 case Instruction::Xor:
512 // ~X + C --> (C-1) - X
513 if (ConstantInt *XorRHS = dyn_cast<ConstantInt>(ILHS->getOperand(1)))
514 if (XorRHS->isAllOnesValue())
515 return BinaryOperator::create(Instruction::Sub,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000516 ConstantExpr::get(Instruction::Sub,
517 CRHS, ConstantInt::get(I.getType(), 1)),
Chris Lattnerb9cde762003-10-02 15:11:26 +0000518 ILHS->getOperand(0));
519 break;
520 default: break;
521 }
522 }
523 }
524
Chris Lattner113f4f42002-06-25 16:13:24 +0000525 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000526}
527
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000528// isSignBit - Return true if the value represented by the constant only has the
529// highest order bit set.
530static bool isSignBit(ConstantInt *CI) {
531 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
532 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
533}
534
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000535static unsigned getTypeSizeInBits(const Type *Ty) {
536 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
537}
538
Chris Lattner113f4f42002-06-25 16:13:24 +0000539Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000540 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000541
Chris Lattnere6794492002-08-12 21:17:25 +0000542 if (Op0 == Op1) // sub X, X -> 0
543 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000544
Chris Lattnere6794492002-08-12 21:17:25 +0000545 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000546 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner147e9752002-05-08 22:46:53 +0000547 return BinaryOperator::create(Instruction::Add, Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000548
Chris Lattner8f2f5982003-11-05 01:06:05 +0000549 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
550 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000551 if (C->isAllOnesValue())
552 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000553
Chris Lattner8f2f5982003-11-05 01:06:05 +0000554 // C - ~X == X + (1+C)
555 if (BinaryOperator::isNot(Op1))
556 return BinaryOperator::create(Instruction::Add,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000557 BinaryOperator::getNotArgument(cast<BinaryOperator>(Op1)),
558 ConstantExpr::get(Instruction::Add, C,
559 ConstantInt::get(I.getType(), 1)));
Chris Lattner8f2f5982003-11-05 01:06:05 +0000560 }
561
Chris Lattner3082c5a2003-02-18 19:28:33 +0000562 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000563 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000564 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
565 // is not used by anyone else...
566 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000567 if (Op1I->getOpcode() == Instruction::Sub &&
568 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000569 // Swap the two operands of the subexpr...
570 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
571 Op1I->setOperand(0, IIOp1);
572 Op1I->setOperand(1, IIOp0);
573
574 // Create the new top level add instruction...
575 return BinaryOperator::create(Instruction::Add, Op0, Op1);
576 }
577
578 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
579 //
580 if (Op1I->getOpcode() == Instruction::And &&
581 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
582 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
583
584 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
585 return BinaryOperator::create(Instruction::And, Op0, NewNot);
586 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000587
588 // X - X*C --> X * (1-C)
589 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000590 Constant *CP1 =
591 ConstantExpr::get(Instruction::Sub,
592 ConstantInt::get(I.getType(), 1),
593 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000594 assert(CP1 && "Couldn't constant fold 1-C?");
595 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
596 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000597 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000598
Chris Lattner57c8d992003-02-18 19:57:07 +0000599 // X*C - X --> X * (C-1)
600 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000601 Constant *CP1 =
602 ConstantExpr::get(Instruction::Sub,
603 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
604 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000605 assert(CP1 && "Couldn't constant fold C - 1?");
606 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
607 }
608
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000609 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000610}
611
Chris Lattnere79e8542004-02-23 06:38:22 +0000612/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
613/// really just returns true if the most significant (sign) bit is set.
614static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
615 if (RHS->getType()->isSigned()) {
616 // True if source is LHS < 0 or LHS <= -1
617 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
618 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
619 } else {
620 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
621 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
622 // the size of the integer type.
623 if (Opcode == Instruction::SetGE)
624 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
625 if (Opcode == Instruction::SetGT)
626 return RHSC->getValue() ==
627 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
628 }
629 return false;
630}
631
Chris Lattner113f4f42002-06-25 16:13:24 +0000632Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000633 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000634 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000635
Chris Lattnere6794492002-08-12 21:17:25 +0000636 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000637 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
638 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000639
640 // ((X << C1)*C2) == (X * (C2 << C1))
641 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
642 if (SI->getOpcode() == Instruction::Shl)
643 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
644 return BinaryOperator::create(Instruction::Mul, SI->getOperand(0),
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000645 ConstantExpr::get(Instruction::Shl, CI, ShOp));
646
Chris Lattnercce81be2003-09-11 22:24:54 +0000647 if (CI->isNullValue())
648 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
649 if (CI->equalsInt(1)) // X * 1 == X
650 return ReplaceInstUsesWith(I, Op0);
651 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000652 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000653
Chris Lattnercce81be2003-09-11 22:24:54 +0000654 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000655 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
656 return new ShiftInst(Instruction::Shl, Op0,
657 ConstantUInt::get(Type::UByteTy, C));
658 } else {
659 ConstantFP *Op1F = cast<ConstantFP>(Op1);
660 if (Op1F->isNullValue())
661 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000662
Chris Lattner3082c5a2003-02-18 19:28:33 +0000663 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
664 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
665 if (Op1F->getValue() == 1.0)
666 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
667 }
Chris Lattner260ab202002-04-18 17:39:14 +0000668 }
669
Chris Lattner934a64cf2003-03-10 23:23:04 +0000670 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
671 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
672 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
673
Chris Lattner2635b522004-02-23 05:39:21 +0000674 // If one of the operands of the multiply is a cast from a boolean value, then
675 // we know the bool is either zero or one, so this is a 'masking' multiply.
676 // See if we can simplify things based on how the boolean was originally
677 // formed.
678 CastInst *BoolCast = 0;
679 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
680 if (CI->getOperand(0)->getType() == Type::BoolTy)
681 BoolCast = CI;
682 if (!BoolCast)
683 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
684 if (CI->getOperand(0)->getType() == Type::BoolTy)
685 BoolCast = CI;
686 if (BoolCast) {
687 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
688 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
689 const Type *SCOpTy = SCIOp0->getType();
690
Chris Lattnere79e8542004-02-23 06:38:22 +0000691 // If the setcc is true iff the sign bit of X is set, then convert this
692 // multiply into a shift/and combination.
693 if (isa<ConstantInt>(SCIOp1) &&
694 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000695 // Shift the X value right to turn it into "all signbits".
696 Constant *Amt = ConstantUInt::get(Type::UByteTy,
697 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000698 if (SCIOp0->getType()->isUnsigned()) {
699 const Type *NewTy = getSignedIntegralType(SCIOp0->getType());
700 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
701 SCIOp0->getName()), I);
702 }
703
704 Value *V =
705 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
706 BoolCast->getOperand(0)->getName()+
707 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000708
709 // If the multiply type is not the same as the source type, sign extend
710 // or truncate to the multiply type.
711 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000712 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000713
714 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
715 return BinaryOperator::create(Instruction::And, V, OtherOp);
716 }
717 }
718 }
719
Chris Lattner113f4f42002-06-25 16:13:24 +0000720 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000721}
722
Chris Lattner113f4f42002-06-25 16:13:24 +0000723Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000724 // div X, 1 == X
Chris Lattner3082c5a2003-02-18 19:28:33 +0000725 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere6794492002-08-12 21:17:25 +0000726 if (RHS->equalsInt(1))
727 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000728
729 // Check to see if this is an unsigned division with an exact power of 2,
730 // if so, convert to a right shift.
731 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
732 if (uint64_t Val = C->getValue()) // Don't break X / 0
733 if (uint64_t C = Log2(Val))
734 return new ShiftInst(Instruction::Shr, I.getOperand(0),
735 ConstantUInt::get(Type::UByteTy, C));
736 }
737
738 // 0 / X == 0, we don't need to preserve faults!
739 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
740 if (LHS->equalsInt(0))
741 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
742
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000743 return 0;
744}
745
746
Chris Lattner113f4f42002-06-25 16:13:24 +0000747Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000748 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
749 if (RHS->equalsInt(1)) // X % 1 == 0
750 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
751
752 // Check to see if this is an unsigned remainder with an exact power of 2,
753 // if so, convert to a bitwise and.
754 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
755 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
756 if (Log2(Val))
757 return BinaryOperator::create(Instruction::And, I.getOperand(0),
758 ConstantUInt::get(I.getType(), Val-1));
759 }
760
761 // 0 % X == 0, we don't need to preserve faults!
762 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
763 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000764 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
765
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000766 return 0;
767}
768
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000769// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000770static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000771 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
772 // Calculate -1 casted to the right type...
773 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
774 uint64_t Val = ~0ULL; // All ones
775 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
776 return CU->getValue() == Val-1;
777 }
778
779 const ConstantSInt *CS = cast<ConstantSInt>(C);
780
781 // Calculate 0111111111..11111
782 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
783 int64_t Val = INT64_MAX; // All ones
784 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
785 return CS->getValue() == Val-1;
786}
787
788// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000789static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000790 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
791 return CU->getValue() == 1;
792
793 const ConstantSInt *CS = cast<ConstantSInt>(C);
794
795 // Calculate 1111111111000000000000
796 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
797 int64_t Val = -1; // All ones
798 Val <<= TypeBits-1; // Shift over to the right spot
799 return CS->getValue() == Val+1;
800}
801
Chris Lattner3ac7c262003-08-13 20:16:26 +0000802/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
803/// are carefully arranged to allow folding of expressions such as:
804///
805/// (A < B) | (A > B) --> (A != B)
806///
807/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
808/// represents that the comparison is true if A == B, and bit value '1' is true
809/// if A < B.
810///
811static unsigned getSetCondCode(const SetCondInst *SCI) {
812 switch (SCI->getOpcode()) {
813 // False -> 0
814 case Instruction::SetGT: return 1;
815 case Instruction::SetEQ: return 2;
816 case Instruction::SetGE: return 3;
817 case Instruction::SetLT: return 4;
818 case Instruction::SetNE: return 5;
819 case Instruction::SetLE: return 6;
820 // True -> 7
821 default:
822 assert(0 && "Invalid SetCC opcode!");
823 return 0;
824 }
825}
826
827/// getSetCCValue - This is the complement of getSetCondCode, which turns an
828/// opcode and two operands into either a constant true or false, or a brand new
829/// SetCC instruction.
830static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
831 switch (Opcode) {
832 case 0: return ConstantBool::False;
833 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
834 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
835 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
836 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
837 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
838 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
839 case 7: return ConstantBool::True;
840 default: assert(0 && "Illegal SetCCCode!"); return 0;
841 }
842}
843
844// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
845struct FoldSetCCLogical {
846 InstCombiner &IC;
847 Value *LHS, *RHS;
848 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
849 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
850 bool shouldApply(Value *V) const {
851 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
852 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
853 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
854 return false;
855 }
856 Instruction *apply(BinaryOperator &Log) const {
857 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
858 if (SCI->getOperand(0) != LHS) {
859 assert(SCI->getOperand(1) == LHS);
860 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
861 }
862
863 unsigned LHSCode = getSetCondCode(SCI);
864 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
865 unsigned Code;
866 switch (Log.getOpcode()) {
867 case Instruction::And: Code = LHSCode & RHSCode; break;
868 case Instruction::Or: Code = LHSCode | RHSCode; break;
869 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +0000870 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +0000871 }
872
873 Value *RV = getSetCCValue(Code, LHS, RHS);
874 if (Instruction *I = dyn_cast<Instruction>(RV))
875 return I;
876 // Otherwise, it's a constant boolean value...
877 return IC.ReplaceInstUsesWith(Log, RV);
878 }
879};
880
881
Chris Lattnerba1cb382003-09-19 17:17:26 +0000882// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
883// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
884// guaranteed to be either a shift instruction or a binary operator.
885Instruction *InstCombiner::OptAndOp(Instruction *Op,
886 ConstantIntegral *OpRHS,
887 ConstantIntegral *AndRHS,
888 BinaryOperator &TheAnd) {
889 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +0000890 Constant *Together = 0;
891 if (!isa<ShiftInst>(Op))
892 Together = ConstantExpr::get(Instruction::And, AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000893
Chris Lattnerba1cb382003-09-19 17:17:26 +0000894 switch (Op->getOpcode()) {
895 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000896 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +0000897 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
898 return BinaryOperator::create(Instruction::And, X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000899 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +0000900 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
901 std::string OpName = Op->getName(); Op->setName("");
902 Instruction *And = BinaryOperator::create(Instruction::And,
903 X, AndRHS, OpName);
904 InsertNewInstBefore(And, TheAnd);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000905 return BinaryOperator::create(Instruction::Xor, And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000906 }
907 break;
908 case Instruction::Or:
909 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000910 if (Together->isNullValue())
Chris Lattnerba1cb382003-09-19 17:17:26 +0000911 return BinaryOperator::create(Instruction::And, X, AndRHS);
912 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +0000913 if (Together == AndRHS) // (X | C) & C --> C
914 return ReplaceInstUsesWith(TheAnd, AndRHS);
915
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000916 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +0000917 // (X | C1) & C2 --> (X | (C1&C2)) & C2
918 std::string Op0Name = Op->getName(); Op->setName("");
919 Instruction *Or = BinaryOperator::create(Instruction::Or, X,
920 Together, Op0Name);
921 InsertNewInstBefore(Or, TheAnd);
922 return BinaryOperator::create(Instruction::And, Or, AndRHS);
923 }
924 }
925 break;
926 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000927 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +0000928 // Adding a one to a single bit bit-field should be turned into an XOR
929 // of the bit. First thing to check is to see if this AND is with a
930 // single bit constant.
931 unsigned long long AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
932
933 // Clear bits that are not part of the constant.
934 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
935
936 // If there is only one bit set...
937 if ((AndRHSV & (AndRHSV-1)) == 0) {
938 // Ok, at this point, we know that we are masking the result of the
939 // ADD down to exactly one bit. If the constant we are adding has
940 // no bits set below this bit, then we can eliminate the ADD.
941 unsigned long long AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
942
943 // Check to see if any bits below the one bit set in AndRHSV are set.
944 if ((AddRHS & (AndRHSV-1)) == 0) {
945 // If not, the only thing that can effect the output of the AND is
946 // the bit specified by AndRHSV. If that bit is set, the effect of
947 // the XOR is to toggle the bit. If it is clear, then the ADD has
948 // no effect.
949 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
950 TheAnd.setOperand(0, X);
951 return &TheAnd;
952 } else {
953 std::string Name = Op->getName(); Op->setName("");
954 // Pull the XOR out of the AND.
955 Instruction *NewAnd =
956 BinaryOperator::create(Instruction::And, X, AndRHS, Name);
957 InsertNewInstBefore(NewAnd, TheAnd);
958 return BinaryOperator::create(Instruction::Xor, NewAnd, AndRHS);
959 }
960 }
961 }
962 }
963 break;
Chris Lattner2da29172003-09-19 19:05:02 +0000964
965 case Instruction::Shl: {
966 // We know that the AND will not produce any of the bits shifted in, so if
967 // the anded constant includes them, clear them now!
968 //
969 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000970 Constant *CI = ConstantExpr::get(Instruction::And, AndRHS,
971 ConstantExpr::get(Instruction::Shl, AllOne, OpRHS));
Chris Lattner2da29172003-09-19 19:05:02 +0000972 if (CI != AndRHS) {
973 TheAnd.setOperand(1, CI);
974 return &TheAnd;
975 }
976 break;
977 }
978 case Instruction::Shr:
979 // We know that the AND will not produce any of the bits shifted in, so if
980 // the anded constant includes them, clear them now! This only applies to
981 // unsigned shifts, because a signed shr may bring in set bits!
982 //
983 if (AndRHS->getType()->isUnsigned()) {
984 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000985 Constant *CI = ConstantExpr::get(Instruction::And, AndRHS,
986 ConstantExpr::get(Instruction::Shr, AllOne, OpRHS));
Chris Lattner2da29172003-09-19 19:05:02 +0000987 if (CI != AndRHS) {
988 TheAnd.setOperand(1, CI);
989 return &TheAnd;
990 }
991 }
992 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +0000993 }
994 return 0;
995}
996
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000997
Chris Lattner113f4f42002-06-25 16:13:24 +0000998Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000999 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001000 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001001
1002 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001003 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1004 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001005
1006 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001007 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001008 if (RHS->isAllOnesValue())
1009 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001010
Chris Lattnerba1cb382003-09-19 17:17:26 +00001011 // Optimize a variety of ((val OP C1) & C2) combinations...
1012 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1013 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001014 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001015 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001016 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1017 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001018 }
Chris Lattner49b47ae2003-07-23 17:57:01 +00001019 }
1020
Chris Lattnerbb74e222003-03-10 23:06:50 +00001021 Value *Op0NotVal = dyn_castNotVal(Op0);
1022 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001023
1024 // (~A & ~B) == (~(A | B)) - Demorgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001025 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001026 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
Chris Lattner49b47ae2003-07-23 17:57:01 +00001027 Op1NotVal,I.getName()+".demorgan");
1028 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001029 return BinaryOperator::createNot(Or);
1030 }
1031
1032 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1033 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner65217ff2002-08-23 18:32:43 +00001034
Chris Lattner3ac7c262003-08-13 20:16:26 +00001035 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1036 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1037 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1038 return R;
1039
Chris Lattner113f4f42002-06-25 16:13:24 +00001040 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001041}
1042
1043
1044
Chris Lattner113f4f42002-06-25 16:13:24 +00001045Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001046 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001047 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001048
1049 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001050 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1051 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001052
1053 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001054 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001055 if (RHS->isAllOnesValue())
1056 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001057
Chris Lattner8f0d1562003-07-23 18:29:44 +00001058 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1059 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1060 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
1061 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
1062 std::string Op0Name = Op0I->getName(); Op0I->setName("");
1063 Instruction *Or = BinaryOperator::create(Instruction::Or,
1064 Op0I->getOperand(0), RHS,
1065 Op0Name);
1066 InsertNewInstBefore(Or, I);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001067 return BinaryOperator::create(Instruction::And, Or,
1068 ConstantExpr::get(Instruction::Or, RHS, Op0CI));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001069 }
1070
1071 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1072 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
1073 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
1074 std::string Op0Name = Op0I->getName(); Op0I->setName("");
1075 Instruction *Or = BinaryOperator::create(Instruction::Or,
1076 Op0I->getOperand(0), RHS,
1077 Op0Name);
1078 InsertNewInstBefore(Or, I);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001079 return BinaryOperator::create(Instruction::Xor, Or,
1080 ConstantExpr::get(Instruction::And, Op0CI,
1081 NotConstant(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001082 }
1083 }
1084 }
1085
Chris Lattner812aab72003-08-12 19:11:07 +00001086 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattner01d56392003-08-12 19:17:27 +00001087 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
1088 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
1089 if (LHS->getOperand(0) == RHS->getOperand(0))
1090 if (Constant *C0 = dyn_castMaskingAnd(LHS))
1091 if (Constant *C1 = dyn_castMaskingAnd(RHS))
1092 return BinaryOperator::create(Instruction::And, LHS->getOperand(0),
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001093 ConstantExpr::get(Instruction::Or, C0, C1));
Chris Lattner812aab72003-08-12 19:11:07 +00001094
Chris Lattner3e327a42003-03-10 23:13:59 +00001095 Value *Op0NotVal = dyn_castNotVal(Op0);
1096 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001097
Chris Lattner3e327a42003-03-10 23:13:59 +00001098 if (Op1 == Op0NotVal) // ~A | A == -1
1099 return ReplaceInstUsesWith(I,
1100 ConstantIntegral::getAllOnesValue(I.getType()));
1101
1102 if (Op0 == Op1NotVal) // A | ~A == -1
1103 return ReplaceInstUsesWith(I,
1104 ConstantIntegral::getAllOnesValue(I.getType()));
1105
1106 // (~A | ~B) == (~(A & B)) - Demorgan's Law
1107 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1108 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
1109 Op1NotVal,I.getName()+".demorgan",
1110 &I);
1111 WorkList.push_back(And);
1112 return BinaryOperator::createNot(And);
1113 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001114
Chris Lattner3ac7c262003-08-13 20:16:26 +00001115 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
1116 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1117 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1118 return R;
1119
Chris Lattner113f4f42002-06-25 16:13:24 +00001120 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001121}
1122
Chris Lattnerc2076352004-02-16 01:20:27 +00001123// XorSelf - Implements: X ^ X --> 0
1124struct XorSelf {
1125 Value *RHS;
1126 XorSelf(Value *rhs) : RHS(rhs) {}
1127 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1128 Instruction *apply(BinaryOperator &Xor) const {
1129 return &Xor;
1130 }
1131};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001132
1133
Chris Lattner113f4f42002-06-25 16:13:24 +00001134Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001135 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001136 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001137
Chris Lattnerc2076352004-02-16 01:20:27 +00001138 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1139 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1140 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001141 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001142 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001143
Chris Lattner97638592003-07-23 21:37:07 +00001144 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001145 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001146 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001147 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001148
Chris Lattner97638592003-07-23 21:37:07 +00001149 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001150 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001151 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001152 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001153 return new SetCondInst(SCI->getInverseCondition(),
1154 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001155
Chris Lattner8f2f5982003-11-05 01:06:05 +00001156 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001157 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1158 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
1159 Constant *NegOp0I0C = ConstantExpr::get(Instruction::Sub,
1160 Constant::getNullValue(Op0I0C->getType()), Op0I0C);
1161 Constant *ConstantRHS = ConstantExpr::get(Instruction::Sub, NegOp0I0C,
1162 ConstantInt::get(I.getType(), 1));
1163 return BinaryOperator::create(Instruction::Add, Op0I->getOperand(1),
1164 ConstantRHS);
1165 }
Chris Lattner97638592003-07-23 21:37:07 +00001166
1167 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001168 switch (Op0I->getOpcode()) {
1169 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001170 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001171 if (RHS->isAllOnesValue()) {
1172 Constant *NegOp0CI = ConstantExpr::get(Instruction::Sub,
1173 Constant::getNullValue(Op0CI->getType()), Op0CI);
Chris Lattner0f68fa62003-11-04 23:37:10 +00001174 return BinaryOperator::create(Instruction::Sub,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001175 ConstantExpr::get(Instruction::Sub, NegOp0CI,
1176 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001177 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001178 }
Chris Lattnere5806662003-11-04 23:50:51 +00001179 break;
1180 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001181 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001182 if (ConstantExpr::get(Instruction::And, RHS, Op0CI)->isNullValue())
Chris Lattner97638592003-07-23 21:37:07 +00001183 return BinaryOperator::create(Instruction::Or, Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001184 break;
1185 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001186 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001187 if (ConstantExpr::get(Instruction::And, RHS, Op0CI) == RHS)
1188 return BinaryOperator::create(Instruction::And, Op0,
1189 NotConstant(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001190 break;
1191 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001192 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001193 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001194 }
1195
Chris Lattnerbb74e222003-03-10 23:06:50 +00001196 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001197 if (X == Op1)
1198 return ReplaceInstUsesWith(I,
1199 ConstantIntegral::getAllOnesValue(I.getType()));
1200
Chris Lattnerbb74e222003-03-10 23:06:50 +00001201 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001202 if (X == Op0)
1203 return ReplaceInstUsesWith(I,
1204 ConstantIntegral::getAllOnesValue(I.getType()));
1205
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001206 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001207 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001208 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1209 cast<BinaryOperator>(Op1I)->swapOperands();
1210 I.swapOperands();
1211 std::swap(Op0, Op1);
1212 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1213 I.swapOperands();
1214 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001215 }
1216 } else if (Op1I->getOpcode() == Instruction::Xor) {
1217 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1218 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1219 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1220 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1221 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001222
1223 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001224 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001225 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1226 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001227 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001228 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
1229 WorkList.push_back(cast<Instruction>(NotB));
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001230 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
1231 NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001232 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001233 } else if (Op0I->getOpcode() == Instruction::Xor) {
1234 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1235 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1236 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1237 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001238 }
1239
Chris Lattner7fb29e12003-03-11 00:12:48 +00001240 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
1241 if (Constant *C1 = dyn_castMaskingAnd(Op0))
1242 if (Constant *C2 = dyn_castMaskingAnd(Op1))
Chris Lattner34428442003-05-27 16:40:51 +00001243 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +00001244 return BinaryOperator::create(Instruction::Or, Op0, Op1);
1245
Chris Lattner3ac7c262003-08-13 20:16:26 +00001246 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1247 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1248 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1249 return R;
1250
Chris Lattner113f4f42002-06-25 16:13:24 +00001251 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001252}
1253
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001254// AddOne, SubOne - Add or subtract a constant one from an integer constant...
1255static Constant *AddOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +00001256 Constant *Result = ConstantExpr::get(Instruction::Add, C,
1257 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001258 assert(Result && "Constant folding integer addition failed!");
1259 return Result;
1260}
1261static Constant *SubOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +00001262 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
1263 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001264 assert(Result && "Constant folding integer addition failed!");
1265 return Result;
1266}
1267
Chris Lattner1fc23f32002-05-09 20:11:54 +00001268// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1269// true when both operands are equal...
1270//
Chris Lattner113f4f42002-06-25 16:13:24 +00001271static bool isTrueWhenEqual(Instruction &I) {
1272 return I.getOpcode() == Instruction::SetEQ ||
1273 I.getOpcode() == Instruction::SetGE ||
1274 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +00001275}
1276
Chris Lattner113f4f42002-06-25 16:13:24 +00001277Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001278 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001279 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1280 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001281
1282 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001283 if (Op0 == Op1)
1284 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001285
Chris Lattnerd07283a2003-08-13 05:38:46 +00001286 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1287 if (isa<ConstantPointerNull>(Op1) &&
1288 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001289 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1290
Chris Lattnerd07283a2003-08-13 05:38:46 +00001291
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001292 // setcc's with boolean values can always be turned into bitwise operations
1293 if (Ty == Type::BoolTy) {
1294 // If this is <, >, or !=, we can change this into a simple xor instruction
1295 if (!isTrueWhenEqual(I))
Chris Lattner16930792003-11-03 04:25:02 +00001296 return BinaryOperator::create(Instruction::Xor, Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001297
1298 // Otherwise we need to make a temporary intermediate instruction and insert
1299 // it into the instruction stream. This is what we are after:
1300 //
1301 // seteq bool %A, %B -> ~(A^B)
1302 // setle bool %A, %B -> ~A | B
1303 // setge bool %A, %B -> A | ~B
1304 //
1305 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
1306 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
1307 I.getName()+"tmp");
1308 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001309 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001310 }
1311
1312 // Handle the setXe cases...
1313 assert(I.getOpcode() == Instruction::SetGE ||
1314 I.getOpcode() == Instruction::SetLE);
1315
1316 if (I.getOpcode() == Instruction::SetGE)
1317 std::swap(Op0, Op1); // Change setge -> setle
1318
1319 // Now we just have the SetLE case.
Chris Lattner31ae8632002-08-14 17:51:49 +00001320 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001321 InsertNewInstBefore(Not, I);
Chris Lattner16930792003-11-03 04:25:02 +00001322 return BinaryOperator::create(Instruction::Or, Not, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001323 }
1324
1325 // Check to see if we are doing one of many comparisons against constant
1326 // integers at the end of their ranges...
1327 //
1328 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001329 // Simplify seteq and setne instructions...
1330 if (I.getOpcode() == Instruction::SetEQ ||
1331 I.getOpcode() == Instruction::SetNE) {
1332 bool isSetNE = I.getOpcode() == Instruction::SetNE;
1333
Chris Lattnercfbce7c2003-07-23 17:26:36 +00001334 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001335 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00001336 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1337 switch (BO->getOpcode()) {
1338 case Instruction::Add:
1339 if (CI->isNullValue()) {
1340 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1341 // efficiently invertible, or if the add has just this one use.
1342 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1343 if (Value *NegVal = dyn_castNegVal(BOp1))
1344 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1345 else if (Value *NegVal = dyn_castNegVal(BOp0))
1346 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001347 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00001348 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1349 BO->setName("");
1350 InsertNewInstBefore(Neg, I);
1351 return new SetCondInst(I.getOpcode(), BOp0, Neg);
1352 }
1353 }
1354 break;
1355 case Instruction::Xor:
1356 // For the xor case, we can xor two constants together, eliminating
1357 // the explicit xor.
1358 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1359 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001360 ConstantExpr::get(Instruction::Xor, CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00001361
1362 // FALLTHROUGH
1363 case Instruction::Sub:
1364 // Replace (([sub|xor] A, B) != 0) with (A != B)
1365 if (CI->isNullValue())
1366 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1367 BO->getOperand(1));
1368 break;
1369
1370 case Instruction::Or:
1371 // If bits are being or'd in that are not present in the constant we
1372 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001373 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1374 Constant *NotCI = NotConstant(CI);
1375 if (!ConstantExpr::get(Instruction::And, BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001376 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001377 }
Chris Lattnerc992add2003-08-13 05:33:12 +00001378 break;
1379
1380 case Instruction::And:
1381 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001382 // If bits are being compared against that are and'd out, then the
1383 // comparison can never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001384 if (!ConstantExpr::get(Instruction::And, CI,
1385 NotConstant(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001386 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00001387
1388 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
1389 // to be a signed value as appropriate.
1390 if (isSignBit(BOC)) {
1391 Value *X = BO->getOperand(0);
1392 // If 'X' is not signed, insert a cast now...
1393 if (!BOC->getType()->isSigned()) {
Chris Lattnere79e8542004-02-23 06:38:22 +00001394 const Type *DestTy = getSignedIntegralType(BOC->getType());
Chris Lattnerc992add2003-08-13 05:33:12 +00001395 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1396 InsertNewInstBefore(NewCI, I);
1397 X = NewCI;
1398 }
1399 return new SetCondInst(isSetNE ? Instruction::SetLT :
1400 Instruction::SetGE, X,
1401 Constant::getNullValue(X->getType()));
1402 }
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001403 }
Chris Lattnerc992add2003-08-13 05:33:12 +00001404 default: break;
1405 }
1406 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00001407 } else { // Not a SetEQ/SetNE
1408 // If the LHS is a cast from an integral value of the same size,
1409 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
1410 Value *CastOp = Cast->getOperand(0);
1411 const Type *SrcTy = CastOp->getType();
1412 unsigned SrcTySize = SrcTy->getPrimitiveSize();
1413 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
1414 SrcTySize == Cast->getType()->getPrimitiveSize()) {
1415 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
1416 "Source and destination signednesses should differ!");
1417 if (Cast->getType()->isSigned()) {
1418 // If this is a signed comparison, check for comparisons in the
1419 // vicinity of zero.
1420 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
1421 // X < 0 => x > 127
1422 return BinaryOperator::create(Instruction::SetGT, CastOp,
1423 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
1424 else if (I.getOpcode() == Instruction::SetGT &&
1425 cast<ConstantSInt>(CI)->getValue() == -1)
1426 // X > -1 => x < 128
Chris Lattnerc40b9d72004-02-23 21:46:42 +00001427 return BinaryOperator::create(Instruction::SetLT, CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00001428 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
1429 } else {
1430 ConstantUInt *CUI = cast<ConstantUInt>(CI);
1431 if (I.getOpcode() == Instruction::SetLT &&
1432 CUI->getValue() == 1ULL << (SrcTySize*8-1))
1433 // X < 128 => X > -1
1434 return BinaryOperator::create(Instruction::SetGT, CastOp,
1435 ConstantSInt::get(SrcTy, -1));
1436 else if (I.getOpcode() == Instruction::SetGT &&
1437 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
1438 // X > 127 => X < 0
1439 return BinaryOperator::create(Instruction::SetLT, CastOp,
1440 Constant::getNullValue(SrcTy));
1441 }
1442 }
1443 }
Chris Lattnere967b342003-06-04 05:10:11 +00001444 }
Chris Lattner791ac1a2003-06-01 03:35:25 +00001445
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001446 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +00001447 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001448 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1449 return ReplaceInstUsesWith(I, ConstantBool::False);
1450 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1451 return ReplaceInstUsesWith(I, ConstantBool::True);
1452 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
Chris Lattner16930792003-11-03 04:25:02 +00001453 return BinaryOperator::create(Instruction::SetEQ, Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001454 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
Chris Lattner16930792003-11-03 04:25:02 +00001455 return BinaryOperator::create(Instruction::SetNE, Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001456
Chris Lattnere6794492002-08-12 21:17:25 +00001457 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001458 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1459 return ReplaceInstUsesWith(I, ConstantBool::False);
1460 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1461 return ReplaceInstUsesWith(I, ConstantBool::True);
1462 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
Chris Lattner16930792003-11-03 04:25:02 +00001463 return BinaryOperator::create(Instruction::SetEQ, Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001464 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
Chris Lattner16930792003-11-03 04:25:02 +00001465 return BinaryOperator::create(Instruction::SetNE, Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001466
1467 // Comparing against a value really close to min or max?
1468 } else if (isMinValuePlusOne(CI)) {
1469 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
Chris Lattner16930792003-11-03 04:25:02 +00001470 return BinaryOperator::create(Instruction::SetEQ, Op0, SubOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001471 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
Chris Lattner16930792003-11-03 04:25:02 +00001472 return BinaryOperator::create(Instruction::SetNE, Op0, SubOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001473
1474 } else if (isMaxValueMinusOne(CI)) {
1475 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
Chris Lattner16930792003-11-03 04:25:02 +00001476 return BinaryOperator::create(Instruction::SetEQ, Op0, AddOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001477 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
Chris Lattner16930792003-11-03 04:25:02 +00001478 return BinaryOperator::create(Instruction::SetNE, Op0, AddOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001479 }
Chris Lattner59611142004-02-23 05:47:48 +00001480
1481 // If we still have a setle or setge instruction, turn it into the
1482 // appropriate setlt or setgt instruction. Since the border cases have
1483 // already been handled above, this requires little checking.
1484 //
1485 if (I.getOpcode() == Instruction::SetLE)
1486 return BinaryOperator::create(Instruction::SetLT, Op0, AddOne(CI));
1487 if (I.getOpcode() == Instruction::SetGE)
1488 return BinaryOperator::create(Instruction::SetGT, Op0, SubOne(CI));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001489 }
1490
Chris Lattner16930792003-11-03 04:25:02 +00001491 // Test to see if the operands of the setcc are casted versions of other
1492 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00001493 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1494 Value *CastOp0 = CI->getOperand(0);
1495 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner16930792003-11-03 04:25:02 +00001496 !isa<Argument>(Op1) &&
1497 (I.getOpcode() == Instruction::SetEQ ||
1498 I.getOpcode() == Instruction::SetNE)) {
1499 // We keep moving the cast from the left operand over to the right
1500 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00001501 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00001502
1503 // If operand #1 is a cast instruction, see if we can eliminate it as
1504 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00001505 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
1506 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00001507 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00001508 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00001509
1510 // If Op1 is a constant, we can fold the cast into the constant.
1511 if (Op1->getType() != Op0->getType())
1512 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1513 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
1514 } else {
1515 // Otherwise, cast the RHS right before the setcc
1516 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
1517 InsertNewInstBefore(cast<Instruction>(Op1), I);
1518 }
1519 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
1520 }
1521
Chris Lattner6444c372003-11-03 05:17:03 +00001522 // Handle the special case of: setcc (cast bool to X), <cst>
1523 // This comes up when you have code like
1524 // int X = A < B;
1525 // if (X) ...
1526 // For generality, we handle any zero-extension of any operand comparison
1527 // with a constant.
1528 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
1529 const Type *SrcTy = CastOp0->getType();
1530 const Type *DestTy = Op0->getType();
1531 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
1532 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
1533 // Ok, we have an expansion of operand 0 into a new type. Get the
1534 // constant value, masink off bits which are not set in the RHS. These
1535 // could be set if the destination value is signed.
1536 uint64_t ConstVal = ConstantRHS->getRawValue();
1537 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
1538
1539 // If the constant we are comparing it with has high bits set, which
1540 // don't exist in the original value, the values could never be equal,
1541 // because the source would be zero extended.
1542 unsigned SrcBits =
1543 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00001544 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
1545 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00001546 switch (I.getOpcode()) {
1547 default: assert(0 && "Unknown comparison type!");
1548 case Instruction::SetEQ:
1549 return ReplaceInstUsesWith(I, ConstantBool::False);
1550 case Instruction::SetNE:
1551 return ReplaceInstUsesWith(I, ConstantBool::True);
1552 case Instruction::SetLT:
1553 case Instruction::SetLE:
1554 if (DestTy->isSigned() && HasSignBit)
1555 return ReplaceInstUsesWith(I, ConstantBool::False);
1556 return ReplaceInstUsesWith(I, ConstantBool::True);
1557 case Instruction::SetGT:
1558 case Instruction::SetGE:
1559 if (DestTy->isSigned() && HasSignBit)
1560 return ReplaceInstUsesWith(I, ConstantBool::True);
1561 return ReplaceInstUsesWith(I, ConstantBool::False);
1562 }
1563 }
1564
1565 // Otherwise, we can replace the setcc with a setcc of the smaller
1566 // operand value.
1567 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
1568 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
1569 }
1570 }
1571 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001572 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001573}
1574
1575
1576
Chris Lattnere8d6c602003-03-10 19:16:08 +00001577Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001578 assert(I.getOperand(1)->getType() == Type::UByteTy);
1579 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001580 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001581
1582 // shl X, 0 == X and shr X, 0 == X
1583 // shl 0, X == 0 and shr 0, X == 0
1584 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00001585 Op0 == Constant::getNullValue(Op0->getType()))
1586 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001587
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001588 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
1589 if (!isLeftShift)
1590 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1591 if (CSI->isAllOnesValue())
1592 return ReplaceInstUsesWith(I, CSI);
1593
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001594 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001595 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1596 // of a signed value.
1597 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00001598 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00001599 if (CUI->getValue() >= TypeBits) {
1600 if (!Op0->getType()->isSigned() || isLeftShift)
1601 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
1602 else {
1603 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
1604 return &I;
1605 }
1606 }
Chris Lattner55f3d942002-09-10 23:04:09 +00001607
Chris Lattnerede3fe02003-08-13 04:18:28 +00001608 // ((X*C1) << C2) == (X * (C1 << C2))
1609 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1610 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1611 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
1612 return BinaryOperator::create(Instruction::Mul, BO->getOperand(0),
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001613 ConstantExpr::get(Instruction::Shl, BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00001614
1615
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001616 // If the operand is an bitwise operator with a constant RHS, and the
1617 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001618 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001619 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1620 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1621 bool isValid = true; // Valid only for And, Or, Xor
1622 bool highBitSet = false; // Transform if high bit of constant set?
1623
1624 switch (Op0BO->getOpcode()) {
1625 default: isValid = false; break; // Do not perform transform!
1626 case Instruction::Or:
1627 case Instruction::Xor:
1628 highBitSet = false;
1629 break;
1630 case Instruction::And:
1631 highBitSet = true;
1632 break;
1633 }
1634
1635 // If this is a signed shift right, and the high bit is modified
1636 // by the logical operation, do not perform the transformation.
1637 // The highBitSet boolean indicates the value of the high bit of
1638 // the constant which would cause it to be modified for this
1639 // operation.
1640 //
1641 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1642 uint64_t Val = Op0C->getRawValue();
1643 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1644 }
1645
1646 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001647 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001648
1649 Instruction *NewShift =
1650 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1651 Op0BO->getName());
1652 Op0BO->setName("");
1653 InsertNewInstBefore(NewShift, I);
1654
1655 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1656 NewRHS);
1657 }
1658 }
1659
Chris Lattner3204d4e2003-07-24 17:52:58 +00001660 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001661 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00001662 if (ConstantUInt *ShiftAmt1C =
1663 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001664 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1665 unsigned ShiftAmt2 = CUI->getValue();
1666
1667 // Check for (A << c1) << c2 and (A >> c1) >> c2
1668 if (I.getOpcode() == Op0SI->getOpcode()) {
1669 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00001670 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
1671 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00001672 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1673 ConstantUInt::get(Type::UByteTy, Amt));
1674 }
1675
Chris Lattnerab780df2003-07-24 18:38:56 +00001676 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1677 // signed types, we can only support the (A >> c1) << c2 configuration,
1678 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001679 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001680 // Calculate bitmask for what gets shifted off the edge...
1681 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001682 if (isLeftShift)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001683 C = ConstantExpr::get(Instruction::Shl, C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001684 else
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001685 C = ConstantExpr::get(Instruction::Shr, C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00001686
1687 Instruction *Mask =
1688 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
1689 C, Op0SI->getOperand(0)->getName()+".mask");
1690 InsertNewInstBefore(Mask, I);
1691
1692 // Figure out what flavor of shift we should use...
1693 if (ShiftAmt1 == ShiftAmt2)
1694 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
1695 else if (ShiftAmt1 < ShiftAmt2) {
1696 return new ShiftInst(I.getOpcode(), Mask,
1697 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1698 } else {
1699 return new ShiftInst(Op0SI->getOpcode(), Mask,
1700 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1701 }
1702 }
1703 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001704 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00001705
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001706 return 0;
1707}
1708
1709
Chris Lattner48a44f72002-05-02 17:06:02 +00001710// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1711// instruction.
1712//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001713static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1714 const Type *DstTy) {
Chris Lattner48a44f72002-05-02 17:06:02 +00001715
Chris Lattner650b6da2002-08-02 20:00:25 +00001716 // It is legal to eliminate the instruction if casting A->B->A if the sizes
1717 // are identical and the bits don't get reinterpreted (for example
Chris Lattner0bb75912002-08-14 23:21:10 +00001718 // int->float->int would not be allowed)
Misha Brukmane5838c42003-05-20 18:45:36 +00001719 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00001720 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00001721
1722 // Allow free casting and conversion of sizes as long as the sign doesn't
1723 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00001724 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00001725 unsigned SrcSize = SrcTy->getPrimitiveSize();
1726 unsigned MidSize = MidTy->getPrimitiveSize();
1727 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner650b6da2002-08-02 20:00:25 +00001728
Chris Lattner3732aca2002-08-15 16:15:25 +00001729 // Cases where we are monotonically decreasing the size of the type are
1730 // always ok, regardless of what sign changes are going on.
1731 //
Chris Lattner0bb75912002-08-14 23:21:10 +00001732 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +00001733 return true;
Chris Lattner3732aca2002-08-15 16:15:25 +00001734
Chris Lattner555518c2002-09-23 23:39:43 +00001735 // Cases where the source and destination type are the same, but the middle
1736 // type is bigger are noops.
1737 //
1738 if (SrcSize == DstSize && MidSize > SrcSize)
1739 return true;
1740
Chris Lattner3732aca2002-08-15 16:15:25 +00001741 // If we are monotonically growing, things are more complex.
1742 //
1743 if (SrcSize <= MidSize && MidSize <= DstSize) {
1744 // We have eight combinations of signedness to worry about. Here's the
1745 // table:
1746 static const int SignTable[8] = {
1747 // CODE, SrcSigned, MidSigned, DstSigned, Comment
1748 1, // U U U Always ok
1749 1, // U U S Always ok
1750 3, // U S U Ok iff SrcSize != MidSize
1751 3, // U S S Ok iff SrcSize != MidSize
1752 0, // S U U Never ok
1753 2, // S U S Ok iff MidSize == DstSize
1754 1, // S S U Always ok
1755 1, // S S S Always ok
1756 };
1757
1758 // Choose an action based on the current entry of the signtable that this
1759 // cast of cast refers to...
1760 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1761 switch (SignTable[Row]) {
1762 case 0: return false; // Never ok
1763 case 1: return true; // Always ok
1764 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1765 case 3: // Ok iff SrcSize != MidSize
1766 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1767 default: assert(0 && "Bad entry in sign table!");
1768 }
Chris Lattner3732aca2002-08-15 16:15:25 +00001769 }
Chris Lattner650b6da2002-08-02 20:00:25 +00001770 }
Chris Lattner48a44f72002-05-02 17:06:02 +00001771
1772 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1773 // like: short -> ushort -> uint, because this can create wrong results if
1774 // the input short is negative!
1775 //
1776 return false;
1777}
1778
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001779static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1780 if (V->getType() == Ty || isa<Constant>(V)) return false;
1781 if (const CastInst *CI = dyn_cast<CastInst>(V))
1782 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1783 return false;
1784 return true;
1785}
1786
1787/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1788/// InsertBefore instruction. This is specialized a bit to avoid inserting
1789/// casts that are known to not do anything...
1790///
1791Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1792 Instruction *InsertBefore) {
1793 if (V->getType() == DestTy) return V;
1794 if (Constant *C = dyn_cast<Constant>(V))
1795 return ConstantExpr::getCast(C, DestTy);
1796
1797 CastInst *CI = new CastInst(V, DestTy, V->getName());
1798 InsertNewInstBefore(CI, *InsertBefore);
1799 return CI;
1800}
Chris Lattner48a44f72002-05-02 17:06:02 +00001801
1802// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00001803//
Chris Lattner113f4f42002-06-25 16:13:24 +00001804Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00001805 Value *Src = CI.getOperand(0);
1806
Chris Lattner48a44f72002-05-02 17:06:02 +00001807 // If the user is casting a value to the same type, eliminate this cast
1808 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00001809 if (CI.getType() == Src->getType())
1810 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00001811
Chris Lattner48a44f72002-05-02 17:06:02 +00001812 // If casting the result of another cast instruction, try to eliminate this
1813 // one!
1814 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00001815 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001816 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
1817 CSrc->getType(), CI.getType())) {
Chris Lattner48a44f72002-05-02 17:06:02 +00001818 // This instruction now refers directly to the cast's src operand. This
1819 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00001820 CI.setOperand(0, CSrc->getOperand(0));
1821 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00001822 }
1823
Chris Lattner650b6da2002-08-02 20:00:25 +00001824 // If this is an A->B->A cast, and we are dealing with integral types, try
1825 // to convert this into a logical 'and' instruction.
1826 //
1827 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00001828 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00001829 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1830 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1831 assert(CSrc->getType() != Type::ULongTy &&
1832 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00001833 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00001834 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1835 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1836 AndOp);
1837 }
1838 }
1839
Chris Lattnerd0d51602003-06-21 23:12:02 +00001840 // If casting the result of a getelementptr instruction with no offset, turn
1841 // this into a cast of the original pointer!
1842 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00001843 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00001844 bool AllZeroOperands = true;
1845 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1846 if (!isa<Constant>(GEP->getOperand(i)) ||
1847 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
1848 AllZeroOperands = false;
1849 break;
1850 }
1851 if (AllZeroOperands) {
1852 CI.setOperand(0, GEP->getOperand(0));
1853 return &CI;
1854 }
1855 }
1856
Chris Lattnerf4ad1652003-11-02 05:57:39 +00001857 // If we are casting a malloc or alloca to a pointer to a type of the same
1858 // size, rewrite the allocation instruction to allocate the "right" type.
1859 //
1860 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00001861 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00001862 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
1863 // Get the type really allocated and the type casted to...
1864 const Type *AllocElTy = AI->getAllocatedType();
1865 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
1866 const Type *CastElTy = PTy->getElementType();
1867 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00001868
Chris Lattnerf4ad1652003-11-02 05:57:39 +00001869 // If the allocation is for an even multiple of the cast type size
Chris Lattneraf789322003-11-03 01:29:41 +00001870 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
Chris Lattnerf4ad1652003-11-02 05:57:39 +00001871 Value *Amt = ConstantUInt::get(Type::UIntTy,
1872 AllocElTySize/CastElTySize);
1873 std::string Name = AI->getName(); AI->setName("");
1874 AllocationInst *New;
1875 if (isa<MallocInst>(AI))
1876 New = new MallocInst(CastElTy, Amt, Name);
1877 else
1878 New = new AllocaInst(CastElTy, Amt, Name);
1879 InsertNewInstBefore(New, CI);
1880 return ReplaceInstUsesWith(CI, New);
1881 }
1882 }
1883
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001884 // If the source value is an instruction with only this use, we can attempt to
1885 // propagate the cast into the instruction. Also, only handle integral types
1886 // for now.
1887 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001888 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001889 CI.getType()->isInteger()) { // Don't mess with casts to bool here
1890 const Type *DestTy = CI.getType();
1891 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
1892 unsigned DestBitSize = getTypeSizeInBits(DestTy);
1893
1894 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
1895 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
1896
1897 switch (SrcI->getOpcode()) {
1898 case Instruction::Add:
1899 case Instruction::Mul:
1900 case Instruction::And:
1901 case Instruction::Or:
1902 case Instruction::Xor:
1903 // If we are discarding information, or just changing the sign, rewrite.
1904 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
1905 // Don't insert two casts if they cannot be eliminated. We allow two
1906 // casts to be inserted if the sizes are the same. This could only be
1907 // converting signedness, which is a noop.
1908 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
1909 !ValueRequiresCast(Op0, DestTy)) {
1910 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1911 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
1912 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
1913 ->getOpcode(), Op0c, Op1c);
1914 }
1915 }
1916 break;
1917 case Instruction::Shl:
1918 // Allow changing the sign of the source operand. Do not allow changing
1919 // the size of the shift, UNLESS the shift amount is a constant. We
1920 // mush not change variable sized shifts to a smaller size, because it
1921 // is undefined to shift more bits out than exist in the value.
1922 if (DestBitSize == SrcBitSize ||
1923 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
1924 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1925 return new ShiftInst(Instruction::Shl, Op0c, Op1);
1926 }
1927 break;
1928 }
1929 }
1930
Chris Lattner260ab202002-04-18 17:39:14 +00001931 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00001932}
1933
Chris Lattner970c33a2003-06-19 17:00:31 +00001934// CallInst simplification
1935//
1936Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00001937 // Intrinsics cannot occur in an invoke, so handle them here instead of in
1938 // visitCallSite.
1939 if (Function *F = CI.getCalledFunction())
1940 switch (F->getIntrinsicID()) {
1941 case Intrinsic::memmove:
1942 case Intrinsic::memcpy:
1943 case Intrinsic::memset:
1944 // memmove/cpy/set of zero bytes is a noop.
1945 if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
1946 if (NumBytes->isNullValue())
1947 return EraseInstFromFunction(CI);
1948 }
1949 break;
1950 default:
1951 break;
1952 }
1953
Chris Lattneraec3d942003-10-07 22:32:43 +00001954 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00001955}
1956
1957// InvokeInst simplification
1958//
1959Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00001960 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00001961}
1962
Chris Lattneraec3d942003-10-07 22:32:43 +00001963// visitCallSite - Improvements for call and invoke instructions.
1964//
1965Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00001966 bool Changed = false;
1967
1968 // If the callee is a constexpr cast of a function, attempt to move the cast
1969 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00001970 if (transformConstExprCastCall(CS)) return 0;
1971
Chris Lattner75b4d1d2003-10-07 22:54:13 +00001972 Value *Callee = CS.getCalledValue();
1973 const PointerType *PTy = cast<PointerType>(Callee->getType());
1974 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1975 if (FTy->isVarArg()) {
1976 // See if we can optimize any arguments passed through the varargs area of
1977 // the call.
1978 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
1979 E = CS.arg_end(); I != E; ++I)
1980 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
1981 // If this cast does not effect the value passed through the varargs
1982 // area, we can eliminate the use of the cast.
1983 Value *Op = CI->getOperand(0);
1984 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
1985 *I = Op;
1986 Changed = true;
1987 }
1988 }
1989 }
Chris Lattneraec3d942003-10-07 22:32:43 +00001990
Chris Lattner75b4d1d2003-10-07 22:54:13 +00001991 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00001992}
1993
Chris Lattner970c33a2003-06-19 17:00:31 +00001994// transformConstExprCastCall - If the callee is a constexpr cast of a function,
1995// attempt to move the cast to the arguments of the call/invoke.
1996//
1997bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1998 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1999 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
2000 if (CE->getOpcode() != Instruction::Cast ||
2001 !isa<ConstantPointerRef>(CE->getOperand(0)))
2002 return false;
2003 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
2004 if (!isa<Function>(CPR->getValue())) return false;
2005 Function *Callee = cast<Function>(CPR->getValue());
2006 Instruction *Caller = CS.getInstruction();
2007
2008 // Okay, this is a cast from a function to a different type. Unless doing so
2009 // would cause a type conversion of one of our arguments, change this call to
2010 // be a direct call with arguments casted to the appropriate types.
2011 //
2012 const FunctionType *FT = Callee->getFunctionType();
2013 const Type *OldRetTy = Caller->getType();
2014
Chris Lattner1f7942f2004-01-14 06:06:08 +00002015 // Check to see if we are changing the return type...
2016 if (OldRetTy != FT->getReturnType()) {
2017 if (Callee->isExternal() &&
2018 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
2019 !Caller->use_empty())
2020 return false; // Cannot transform this return value...
2021
2022 // If the callsite is an invoke instruction, and the return value is used by
2023 // a PHI node in a successor, we cannot change the return type of the call
2024 // because there is no place to put the cast instruction (without breaking
2025 // the critical edge). Bail out in this case.
2026 if (!Caller->use_empty())
2027 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
2028 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
2029 UI != E; ++UI)
2030 if (PHINode *PN = dyn_cast<PHINode>(*UI))
2031 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00002032 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00002033 return false;
2034 }
Chris Lattner970c33a2003-06-19 17:00:31 +00002035
2036 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
2037 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2038
2039 CallSite::arg_iterator AI = CS.arg_begin();
2040 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
2041 const Type *ParamTy = FT->getParamType(i);
2042 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
2043 if (Callee->isExternal() && !isConvertible) return false;
2044 }
2045
2046 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
2047 Callee->isExternal())
2048 return false; // Do not delete arguments unless we have a function body...
2049
2050 // Okay, we decided that this is a safe thing to do: go ahead and start
2051 // inserting cast instructions as necessary...
2052 std::vector<Value*> Args;
2053 Args.reserve(NumActualArgs);
2054
2055 AI = CS.arg_begin();
2056 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
2057 const Type *ParamTy = FT->getParamType(i);
2058 if ((*AI)->getType() == ParamTy) {
2059 Args.push_back(*AI);
2060 } else {
2061 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
2062 InsertNewInstBefore(Cast, *Caller);
2063 Args.push_back(Cast);
2064 }
2065 }
2066
2067 // If the function takes more arguments than the call was taking, add them
2068 // now...
2069 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2070 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2071
2072 // If we are removing arguments to the function, emit an obnoxious warning...
2073 if (FT->getNumParams() < NumActualArgs)
2074 if (!FT->isVarArg()) {
2075 std::cerr << "WARNING: While resolving call to function '"
2076 << Callee->getName() << "' arguments were dropped!\n";
2077 } else {
2078 // Add all of the arguments in their promoted form to the arg list...
2079 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
2080 const Type *PTy = getPromotedType((*AI)->getType());
2081 if (PTy != (*AI)->getType()) {
2082 // Must promote to pass through va_arg area!
2083 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
2084 InsertNewInstBefore(Cast, *Caller);
2085 Args.push_back(Cast);
2086 } else {
2087 Args.push_back(*AI);
2088 }
2089 }
2090 }
2091
2092 if (FT->getReturnType() == Type::VoidTy)
2093 Caller->setName(""); // Void type should not have a name...
2094
2095 Instruction *NC;
2096 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00002097 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00002098 Args, Caller->getName(), Caller);
2099 } else {
2100 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
2101 }
2102
2103 // Insert a cast of the return type as necessary...
2104 Value *NV = NC;
2105 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
2106 if (NV->getType() != Type::VoidTy) {
2107 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00002108
2109 // If this is an invoke instruction, we should insert it after the first
2110 // non-phi, instruction in the normal successor block.
2111 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
2112 BasicBlock::iterator I = II->getNormalDest()->begin();
2113 while (isa<PHINode>(I)) ++I;
2114 InsertNewInstBefore(NC, *I);
2115 } else {
2116 // Otherwise, it's a call, just insert cast right after the call instr
2117 InsertNewInstBefore(NC, *Caller);
2118 }
Chris Lattner51ea1272004-02-28 05:22:00 +00002119 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00002120 } else {
2121 NV = Constant::getNullValue(Caller->getType());
2122 }
2123 }
2124
2125 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
2126 Caller->replaceAllUsesWith(NV);
2127 Caller->getParent()->getInstList().erase(Caller);
2128 removeFromWorkList(Caller);
2129 return true;
2130}
2131
2132
Chris Lattner48a44f72002-05-02 17:06:02 +00002133
Chris Lattnerbbbdd852002-05-06 18:06:38 +00002134// PHINode simplification
2135//
Chris Lattner113f4f42002-06-25 16:13:24 +00002136Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner91daeb52003-12-19 05:58:40 +00002137 if (Value *V = hasConstantValue(&PN))
2138 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00002139
2140 // If the only user of this instruction is a cast instruction, and all of the
2141 // incoming values are constants, change this PHI to merge together the casted
2142 // constants.
2143 if (PN.hasOneUse())
2144 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
2145 if (CI->getType() != PN.getType()) { // noop casts will be folded
2146 bool AllConstant = true;
2147 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2148 if (!isa<Constant>(PN.getIncomingValue(i))) {
2149 AllConstant = false;
2150 break;
2151 }
2152 if (AllConstant) {
2153 // Make a new PHI with all casted values.
2154 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
2155 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2156 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
2157 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
2158 PN.getIncomingBlock(i));
2159 }
2160
2161 // Update the cast instruction.
2162 CI->setOperand(0, New);
2163 WorkList.push_back(CI); // revisit the cast instruction to fold.
2164 WorkList.push_back(New); // Make sure to revisit the new Phi
2165 return &PN; // PN is now dead!
2166 }
2167 }
Chris Lattner91daeb52003-12-19 05:58:40 +00002168 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00002169}
2170
Chris Lattner48a44f72002-05-02 17:06:02 +00002171
Chris Lattner113f4f42002-06-25 16:13:24 +00002172Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner471bd762003-05-22 19:07:21 +00002173 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00002174 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002175 if (GEP.getNumOperands() == 1)
2176 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
2177
2178 bool HasZeroPointerIndex = false;
2179 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
2180 HasZeroPointerIndex = C->isNullValue();
2181
2182 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattnere6794492002-08-12 21:17:25 +00002183 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +00002184
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002185 // Combine Indices - If the source pointer to this getelementptr instruction
2186 // is a getelementptr instruction, combine the indices of the two
2187 // getelementptr instructions into a single instruction.
2188 //
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002189 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002190 std::vector<Value *> Indices;
Chris Lattnerca081252001-12-14 16:52:21 +00002191
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002192 // Can we combine the two pointer arithmetics offsets?
Chris Lattner471bd762003-05-22 19:07:21 +00002193 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
2194 isa<Constant>(GEP.getOperand(1))) {
Chris Lattner235af562003-03-05 22:33:14 +00002195 // Replace: gep (gep %P, long C1), long C2, ...
2196 // With: gep %P, long (C1+C2), ...
Chris Lattner34428442003-05-27 16:40:51 +00002197 Value *Sum = ConstantExpr::get(Instruction::Add,
2198 cast<Constant>(Src->getOperand(1)),
2199 cast<Constant>(GEP.getOperand(1)));
Chris Lattner235af562003-03-05 22:33:14 +00002200 assert(Sum && "Constant folding of longs failed!?");
2201 GEP.setOperand(0, Src->getOperand(0));
2202 GEP.setOperand(1, Sum);
Chris Lattner51ea1272004-02-28 05:22:00 +00002203 AddUsersToWorkList(*Src); // Reduce use count of Src
Chris Lattner235af562003-03-05 22:33:14 +00002204 return &GEP;
Chris Lattner471bd762003-05-22 19:07:21 +00002205 } else if (Src->getNumOperands() == 2) {
Chris Lattner235af562003-03-05 22:33:14 +00002206 // Replace: gep (gep %P, long B), long A, ...
2207 // With: T = long A+B; gep %P, T, ...
2208 //
Chris Lattnerae739ae2004-02-23 21:46:58 +00002209 // Note that if our source is a gep chain itself that we wait for that
2210 // chain to be resolved before we perform this transformation. This
2211 // avoids us creating a TON of code in some cases.
2212 //
2213 if (isa<GetElementPtrInst>(Src->getOperand(0)) &&
2214 cast<Instruction>(Src->getOperand(0))->getNumOperands() == 2)
2215 return 0; // Wait until our source is folded to completion.
2216
Chris Lattner235af562003-03-05 22:33:14 +00002217 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
2218 GEP.getOperand(1),
2219 Src->getName()+".sum", &GEP);
2220 GEP.setOperand(0, Src->getOperand(0));
2221 GEP.setOperand(1, Sum);
2222 WorkList.push_back(cast<Instruction>(Sum));
2223 return &GEP;
Chris Lattner5d606a02002-11-04 16:43:32 +00002224 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
Chris Lattnera8339e32002-09-17 21:05:42 +00002225 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002226 // Otherwise we can do the fold if the first index of the GEP is a zero
2227 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
2228 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner5d606a02002-11-04 16:43:32 +00002229 } else if (Src->getOperand(Src->getNumOperands()-1) ==
2230 Constant::getNullValue(Type::LongTy)) {
2231 // If the src gep ends with a constant array index, merge this get into
2232 // it, even if we have a non-zero array index.
2233 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
2234 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002235 }
2236
2237 if (!Indices.empty())
2238 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002239
2240 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
2241 // GEP of global variable. If all of the indices for this GEP are
2242 // constants, we can promote this to a constexpr instead of an instruction.
2243
2244 // Scan for nonconstants...
2245 std::vector<Constant*> Indices;
2246 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
2247 for (; I != E && isa<Constant>(*I); ++I)
2248 Indices.push_back(cast<Constant>(*I));
2249
2250 if (I == E) { // If they are all constants...
Chris Lattner46b3d302003-04-16 22:40:51 +00002251 Constant *CE =
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002252 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
2253
2254 // Replace all uses of the GEP with the new constexpr...
2255 return ReplaceInstUsesWith(GEP, CE);
2256 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002257 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP.getOperand(0))) {
2258 if (CE->getOpcode() == Instruction::Cast) {
2259 if (HasZeroPointerIndex) {
2260 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
2261 // into : GEP [10 x ubyte]* X, long 0, ...
2262 //
2263 // This occurs when the program declares an array extern like "int X[];"
2264 //
2265 Constant *X = CE->getOperand(0);
2266 const PointerType *CPTy = cast<PointerType>(CE->getType());
2267 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
2268 if (const ArrayType *XATy =
2269 dyn_cast<ArrayType>(XTy->getElementType()))
2270 if (const ArrayType *CATy =
2271 dyn_cast<ArrayType>(CPTy->getElementType()))
2272 if (CATy->getElementType() == XATy->getElementType()) {
2273 // At this point, we know that the cast source type is a pointer
2274 // to an array of the same type as the destination pointer
2275 // array. Because the array type is never stepped over (there
2276 // is a leading zero) we can fold the cast into this GEP.
2277 GEP.setOperand(0, X);
2278 return &GEP;
2279 }
2280 }
2281 }
Chris Lattnerca081252001-12-14 16:52:21 +00002282 }
2283
Chris Lattnerca081252001-12-14 16:52:21 +00002284 return 0;
2285}
2286
Chris Lattner1085bdf2002-11-04 16:18:53 +00002287Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
2288 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
2289 if (AI.isArrayAllocation()) // Check C != 1
2290 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
2291 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00002292 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00002293
2294 // Create and insert the replacement instruction...
2295 if (isa<MallocInst>(AI))
2296 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00002297 else {
2298 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner1085bdf2002-11-04 16:18:53 +00002299 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00002300 }
Chris Lattner1085bdf2002-11-04 16:18:53 +00002301
2302 // Scan to the end of the allocation instructions, to skip over a block of
2303 // allocas if possible...
2304 //
2305 BasicBlock::iterator It = New;
2306 while (isa<AllocationInst>(*It)) ++It;
2307
2308 // Now that I is pointing to the first non-allocation-inst in the block,
2309 // insert our getelementptr instruction...
2310 //
2311 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
2312 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
2313
2314 // Now make everything use the getelementptr instead of the original
2315 // allocation.
2316 ReplaceInstUsesWith(AI, V);
2317 return &AI;
2318 }
2319 return 0;
2320}
2321
Chris Lattner8427bff2003-12-07 01:24:23 +00002322Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
2323 Value *Op = FI.getOperand(0);
2324
2325 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
2326 if (CastInst *CI = dyn_cast<CastInst>(Op))
2327 if (isa<PointerType>(CI->getOperand(0)->getType())) {
2328 FI.setOperand(0, CI->getOperand(0));
2329 return &FI;
2330 }
2331
Chris Lattnerf3a36602004-02-28 04:57:37 +00002332 // If we have 'free null' delete the instruction. This can happen in stl code
2333 // when lots of inlining happens.
Chris Lattner51ea1272004-02-28 05:22:00 +00002334 if (isa<ConstantPointerNull>(Op))
2335 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00002336
Chris Lattner8427bff2003-12-07 01:24:23 +00002337 return 0;
2338}
2339
2340
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002341/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
2342/// constantexpr, return the constant value being addressed by the constant
2343/// expression, or null if something is funny.
2344///
2345static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
2346 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
2347 return 0; // Do not allow stepping over the value!
2348
2349 // Loop over all of the operands, tracking down which value we are
2350 // addressing...
2351 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
2352 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
Chris Lattner76b2ff42004-02-15 05:55:15 +00002353 ConstantStruct *CS = dyn_cast<ConstantStruct>(C);
2354 if (CS == 0) return 0;
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002355 if (CU->getValue() >= CS->getValues().size()) return 0;
2356 C = cast<Constant>(CS->getValues()[CU->getValue()]);
2357 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
Chris Lattner76b2ff42004-02-15 05:55:15 +00002358 ConstantArray *CA = dyn_cast<ConstantArray>(C);
2359 if (CA == 0) return 0;
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002360 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
2361 C = cast<Constant>(CA->getValues()[CS->getValue()]);
2362 } else
2363 return 0;
2364 return C;
2365}
2366
2367Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
2368 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00002369 if (LI.isVolatile()) return 0;
2370
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002371 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
2372 Op = CPR->getValue();
2373
2374 // Instcombine load (constant global) into the value loaded...
2375 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002376 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002377 return ReplaceInstUsesWith(LI, GV->getInitializer());
2378
2379 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
2380 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
2381 if (CE->getOpcode() == Instruction::GetElementPtr)
2382 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
2383 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002384 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002385 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
2386 return ReplaceInstUsesWith(LI, V);
2387 return 0;
2388}
2389
2390
Chris Lattner9eef8a72003-06-04 04:46:00 +00002391Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2392 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattner4f7acca2004-02-27 06:27:46 +00002393 if (BI.isConditional() && !isa<Constant>(BI.getCondition())) {
Chris Lattnere967b342003-06-04 05:10:11 +00002394 if (Value *V = dyn_castNotVal(BI.getCondition())) {
2395 BasicBlock *TrueDest = BI.getSuccessor(0);
2396 BasicBlock *FalseDest = BI.getSuccessor(1);
2397 // Swap Destinations and condition...
2398 BI.setCondition(V);
2399 BI.setSuccessor(0, FalseDest);
2400 BI.setSuccessor(1, TrueDest);
2401 return &BI;
Chris Lattner4f7acca2004-02-27 06:27:46 +00002402 } else if (SetCondInst *I = dyn_cast<SetCondInst>(BI.getCondition())) {
2403 // Cannonicalize setne -> seteq
2404 if ((I->getOpcode() == Instruction::SetNE ||
2405 I->getOpcode() == Instruction::SetLE ||
2406 I->getOpcode() == Instruction::SetGE) && I->hasOneUse()) {
2407 std::string Name = I->getName(); I->setName("");
2408 Instruction::BinaryOps NewOpcode =
2409 SetCondInst::getInverseCondition(I->getOpcode());
2410 Value *NewSCC = BinaryOperator::create(NewOpcode, I->getOperand(0),
2411 I->getOperand(1), Name, I);
2412 BasicBlock *TrueDest = BI.getSuccessor(0);
2413 BasicBlock *FalseDest = BI.getSuccessor(1);
2414 // Swap Destinations and condition...
2415 BI.setCondition(NewSCC);
2416 BI.setSuccessor(0, FalseDest);
2417 BI.setSuccessor(1, TrueDest);
2418 removeFromWorkList(I);
2419 I->getParent()->getInstList().erase(I);
2420 WorkList.push_back(cast<Instruction>(NewSCC));
2421 return &BI;
2422 }
Chris Lattnere967b342003-06-04 05:10:11 +00002423 }
Chris Lattner4f7acca2004-02-27 06:27:46 +00002424 }
Chris Lattner9eef8a72003-06-04 04:46:00 +00002425 return 0;
2426}
Chris Lattner1085bdf2002-11-04 16:18:53 +00002427
Chris Lattnerca081252001-12-14 16:52:21 +00002428
Chris Lattner99f48c62002-09-02 04:59:56 +00002429void InstCombiner::removeFromWorkList(Instruction *I) {
2430 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
2431 WorkList.end());
2432}
2433
Chris Lattner113f4f42002-06-25 16:13:24 +00002434bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00002435 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002436 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00002437
Chris Lattner260ab202002-04-18 17:39:14 +00002438 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
Chris Lattnerca081252001-12-14 16:52:21 +00002439
2440 while (!WorkList.empty()) {
2441 Instruction *I = WorkList.back(); // Get an instruction from the worklist
2442 WorkList.pop_back();
2443
Misha Brukman632df282002-10-29 23:06:16 +00002444 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00002445 // Check to see if we can DIE the instruction...
2446 if (isInstructionTriviallyDead(I)) {
2447 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002448 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00002449 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00002450 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002451
2452 I->getParent()->getInstList().erase(I);
2453 removeFromWorkList(I);
2454 continue;
2455 }
Chris Lattner99f48c62002-09-02 04:59:56 +00002456
Misha Brukman632df282002-10-29 23:06:16 +00002457 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00002458 if (Constant *C = ConstantFoldInstruction(I)) {
2459 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00002460 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00002461 ReplaceInstUsesWith(*I, C);
2462
Chris Lattner99f48c62002-09-02 04:59:56 +00002463 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002464 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00002465 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002466 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00002467 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002468
Chris Lattnerca081252001-12-14 16:52:21 +00002469 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002470 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00002471 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00002472 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00002473 if (Result != I) {
2474 // Instructions can end up on the worklist more than once. Make sure
2475 // we do not process an instruction that has been deleted.
Chris Lattner99f48c62002-09-02 04:59:56 +00002476 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002477
2478 // Move the name to the new instruction first...
2479 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00002480 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002481
2482 // Insert the new instruction into the basic block...
2483 BasicBlock *InstParent = I->getParent();
2484 InstParent->getInstList().insert(I, Result);
2485
2486 // Everything uses the new instruction now...
2487 I->replaceAllUsesWith(Result);
2488
2489 // Erase the old instruction.
2490 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002491 } else {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002492 BasicBlock::iterator II = I;
2493
2494 // If the instruction was modified, it's possible that it is now dead.
2495 // if so, remove it.
2496 if (dceInstruction(II)) {
2497 // Instructions may end up in the worklist more than once. Erase them
2498 // all.
Chris Lattner99f48c62002-09-02 04:59:56 +00002499 removeFromWorkList(I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002500 Result = 0;
2501 }
Chris Lattner053c0932002-05-14 15:24:07 +00002502 }
Chris Lattner260ab202002-04-18 17:39:14 +00002503
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002504 if (Result) {
2505 WorkList.push_back(Result);
Chris Lattner51ea1272004-02-28 05:22:00 +00002506 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002507 }
Chris Lattner260ab202002-04-18 17:39:14 +00002508 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00002509 }
2510 }
2511
Chris Lattner260ab202002-04-18 17:39:14 +00002512 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00002513}
2514
Chris Lattner8427bff2003-12-07 01:24:23 +00002515Pass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00002516 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00002517}
Brian Gaeke960707c2003-11-11 22:41:34 +00002518