blob: e579cf1a7bccd598db277621b0f47d651d0d71dd [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000032// N. This list is incomplete
33//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner471bd762003-05-22 19:07:21 +000038#include "llvm/Instructions.h"
Chris Lattner51ea1272004-02-28 05:22:00 +000039#include "llvm/Intrinsics.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner34428442003-05-27 16:40:51 +000041#include "llvm/Constants.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000042#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000043#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
48#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner60a65912002-02-12 21:07:25 +000049#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/Support/Debug.h"
53#include "llvm/ADT/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000057
Chris Lattner260ab202002-04-18 17:39:14 +000058namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000059 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
62
Chris Lattnerc8e66542002-04-27 06:56:12 +000063 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000064 public InstVisitor<InstCombiner, Instruction*> {
65 // Worklist of all of the instructions that need to be simplified.
66 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000067 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000068
Chris Lattner51ea1272004-02-28 05:22:00 +000069 /// AddUsersToWorkList - When an instruction is simplified, add all users of
70 /// the instruction to the work lists because they might get more simplified
71 /// now.
72 ///
73 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000074 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000075 UI != UE; ++UI)
76 WorkList.push_back(cast<Instruction>(*UI));
77 }
78
Chris Lattner51ea1272004-02-28 05:22:00 +000079 /// AddUsesToWorkList - When an instruction is simplified, add operands to
80 /// the work lists because they might get more simplified now.
81 ///
82 void AddUsesToWorkList(Instruction &I) {
83 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
84 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
85 WorkList.push_back(Op);
86 }
87
Chris Lattner99f48c62002-09-02 04:59:56 +000088 // removeFromWorkList - remove all instances of I from the worklist.
89 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000090 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000091 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000092
Chris Lattnerf12cc842002-04-28 21:27:06 +000093 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000094 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000095 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000096 }
97
Chris Lattner69193f92004-04-05 01:30:19 +000098 TargetData &getTargetData() const { return *TD; }
99
Chris Lattner260ab202002-04-18 17:39:14 +0000100 // Visitation implementation - Implement instruction combining for different
101 // instruction types. The semantics are as follows:
102 // Return Value:
103 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000104 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000105 // otherwise - Change was made, replace I with returned instruction
106 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000107 Instruction *visitAdd(BinaryOperator &I);
108 Instruction *visitSub(BinaryOperator &I);
109 Instruction *visitMul(BinaryOperator &I);
110 Instruction *visitDiv(BinaryOperator &I);
111 Instruction *visitRem(BinaryOperator &I);
112 Instruction *visitAnd(BinaryOperator &I);
113 Instruction *visitOr (BinaryOperator &I);
114 Instruction *visitXor(BinaryOperator &I);
115 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000116 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000117 Instruction *visitCastInst(CastInst &CI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000118 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000119 Instruction *visitCallInst(CallInst &CI);
120 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000121 Instruction *visitPHINode(PHINode &PN);
122 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000123 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000124 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000125 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000126 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000127 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000128
129 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000130 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000131
Chris Lattner970c33a2003-06-19 17:00:31 +0000132 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000133 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000134 bool transformConstExprCastCall(CallSite CS);
135
Chris Lattner69193f92004-04-05 01:30:19 +0000136 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000137 // InsertNewInstBefore - insert an instruction New before instruction Old
138 // in the program. Add the new instruction to the worklist.
139 //
Chris Lattnere79e8542004-02-23 06:38:22 +0000140 Value *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000141 assert(New && New->getParent() == 0 &&
142 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000143 BasicBlock *BB = Old.getParent();
144 BB->getInstList().insert(&Old, New); // Insert inst
145 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000146 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000147 }
148
Chris Lattner7e794272004-09-24 15:21:34 +0000149 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
150 /// This also adds the cast to the worklist. Finally, this returns the
151 /// cast.
152 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
153 if (V->getType() == Ty) return V;
154
155 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
156 WorkList.push_back(C);
157 return C;
158 }
159
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000160 // ReplaceInstUsesWith - This method is to be used when an instruction is
161 // found to be dead, replacable with another preexisting expression. Here
162 // we add all uses of I to the worklist, replace all uses of I with the new
163 // value, then return I, so that the inst combiner will know that I was
164 // modified.
165 //
166 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000167 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000168 if (&I != V) {
169 I.replaceAllUsesWith(V);
170 return &I;
171 } else {
172 // If we are replacing the instruction with itself, this must be in a
173 // segment of unreachable code, so just clobber the instruction.
174 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
175 return &I;
176 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000177 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000178
179 // EraseInstFromFunction - When dealing with an instruction that has side
180 // effects or produces a void value, we can't rely on DCE to delete the
181 // instruction. Instead, visit methods should return the value returned by
182 // this function.
183 Instruction *EraseInstFromFunction(Instruction &I) {
184 assert(I.use_empty() && "Cannot erase instruction that is used!");
185 AddUsesToWorkList(I);
186 removeFromWorkList(&I);
187 I.getParent()->getInstList().erase(&I);
188 return 0; // Don't do anything with FI
189 }
190
191
Chris Lattner3ac7c262003-08-13 20:16:26 +0000192 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000193 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
194 /// InsertBefore instruction. This is specialized a bit to avoid inserting
195 /// casts that are known to not do anything...
196 ///
197 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
198 Instruction *InsertBefore);
199
Chris Lattner7fb29e12003-03-11 00:12:48 +0000200 // SimplifyCommutative - This performs a few simplifications for commutative
201 // operators...
202 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000203
204 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
205 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner260ab202002-04-18 17:39:14 +0000206 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000207
Chris Lattnerc8b70922002-07-26 21:12:46 +0000208 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000209}
210
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000211// getComplexity: Assign a complexity or rank value to LLVM Values...
212// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
213static unsigned getComplexity(Value *V) {
214 if (isa<Instruction>(V)) {
215 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
216 return 2;
217 return 3;
218 }
219 if (isa<Argument>(V)) return 2;
220 return isa<Constant>(V) ? 0 : 1;
221}
Chris Lattner260ab202002-04-18 17:39:14 +0000222
Chris Lattner7fb29e12003-03-11 00:12:48 +0000223// isOnlyUse - Return true if this instruction will be deleted if we stop using
224// it.
225static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000226 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000227}
228
Chris Lattnere79e8542004-02-23 06:38:22 +0000229// getPromotedType - Return the specified type promoted as it would be to pass
230// though a va_arg area...
231static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000232 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000233 case Type::SByteTyID:
234 case Type::ShortTyID: return Type::IntTy;
235 case Type::UByteTyID:
236 case Type::UShortTyID: return Type::UIntTy;
237 case Type::FloatTyID: return Type::DoubleTy;
238 default: return Ty;
239 }
240}
241
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000242// SimplifyCommutative - This performs a few simplifications for commutative
243// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000244//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000245// 1. Order operands such that they are listed from right (least complex) to
246// left (most complex). This puts constants before unary operators before
247// binary operators.
248//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000249// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
250// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000251//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000252bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000253 bool Changed = false;
254 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
255 Changed = !I.swapOperands();
256
257 if (!I.isAssociative()) return Changed;
258 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000259 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
260 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
261 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000262 Constant *Folded = ConstantExpr::get(I.getOpcode(),
263 cast<Constant>(I.getOperand(1)),
264 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000265 I.setOperand(0, Op->getOperand(0));
266 I.setOperand(1, Folded);
267 return true;
268 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
269 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
270 isOnlyUse(Op) && isOnlyUse(Op1)) {
271 Constant *C1 = cast<Constant>(Op->getOperand(1));
272 Constant *C2 = cast<Constant>(Op1->getOperand(1));
273
274 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000275 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000276 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
277 Op1->getOperand(0),
278 Op1->getName(), &I);
279 WorkList.push_back(New);
280 I.setOperand(0, New);
281 I.setOperand(1, Folded);
282 return true;
283 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000284 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000285 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000286}
Chris Lattnerca081252001-12-14 16:52:21 +0000287
Chris Lattnerbb74e222003-03-10 23:06:50 +0000288// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
289// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000290//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000291static inline Value *dyn_castNegVal(Value *V) {
292 if (BinaryOperator::isNeg(V))
293 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
294
Chris Lattner9244df62003-04-30 22:19:10 +0000295 // Constants can be considered to be negated values if they can be folded...
296 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000297 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000298 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000299}
300
Chris Lattnerbb74e222003-03-10 23:06:50 +0000301static inline Value *dyn_castNotVal(Value *V) {
302 if (BinaryOperator::isNot(V))
303 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
304
305 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000306 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000307 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000308 return 0;
309}
310
Chris Lattner7fb29e12003-03-11 00:12:48 +0000311// dyn_castFoldableMul - If this value is a multiply that can be folded into
312// other computations (because it has a constant operand), return the
313// non-constant operand of the multiply.
314//
315static inline Value *dyn_castFoldableMul(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000316 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000317 if (Instruction *I = dyn_cast<Instruction>(V))
318 if (I->getOpcode() == Instruction::Mul)
319 if (isa<Constant>(I->getOperand(1)))
320 return I->getOperand(0);
321 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000322}
Chris Lattner31ae8632002-08-14 17:51:49 +0000323
Chris Lattner3082c5a2003-02-18 19:28:33 +0000324// Log2 - Calculate the log base 2 for the specified value if it is exactly a
325// power of 2.
326static unsigned Log2(uint64_t Val) {
327 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
328 unsigned Count = 0;
329 while (Val != 1) {
330 if (Val & 1) return 0; // Multiple bits set?
331 Val >>= 1;
332 ++Count;
333 }
334 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000335}
336
Chris Lattnerb8b97502003-08-13 19:01:45 +0000337
338/// AssociativeOpt - Perform an optimization on an associative operator. This
339/// function is designed to check a chain of associative operators for a
340/// potential to apply a certain optimization. Since the optimization may be
341/// applicable if the expression was reassociated, this checks the chain, then
342/// reassociates the expression as necessary to expose the optimization
343/// opportunity. This makes use of a special Functor, which must define
344/// 'shouldApply' and 'apply' methods.
345///
346template<typename Functor>
347Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
348 unsigned Opcode = Root.getOpcode();
349 Value *LHS = Root.getOperand(0);
350
351 // Quick check, see if the immediate LHS matches...
352 if (F.shouldApply(LHS))
353 return F.apply(Root);
354
355 // Otherwise, if the LHS is not of the same opcode as the root, return.
356 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000357 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000358 // Should we apply this transform to the RHS?
359 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
360
361 // If not to the RHS, check to see if we should apply to the LHS...
362 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
363 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
364 ShouldApply = true;
365 }
366
367 // If the functor wants to apply the optimization to the RHS of LHSI,
368 // reassociate the expression from ((? op A) op B) to (? op (A op B))
369 if (ShouldApply) {
370 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000371
372 // Now all of the instructions are in the current basic block, go ahead
373 // and perform the reassociation.
374 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
375
376 // First move the selected RHS to the LHS of the root...
377 Root.setOperand(0, LHSI->getOperand(1));
378
379 // Make what used to be the LHS of the root be the user of the root...
380 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000381 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000382 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
383 return 0;
384 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000385 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000386 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000387 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
388 BasicBlock::iterator ARI = &Root; ++ARI;
389 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
390 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000391
392 // Now propagate the ExtraOperand down the chain of instructions until we
393 // get to LHSI.
394 while (TmpLHSI != LHSI) {
395 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000396 // Move the instruction to immediately before the chain we are
397 // constructing to avoid breaking dominance properties.
398 NextLHSI->getParent()->getInstList().remove(NextLHSI);
399 BB->getInstList().insert(ARI, NextLHSI);
400 ARI = NextLHSI;
401
Chris Lattnerb8b97502003-08-13 19:01:45 +0000402 Value *NextOp = NextLHSI->getOperand(1);
403 NextLHSI->setOperand(1, ExtraOperand);
404 TmpLHSI = NextLHSI;
405 ExtraOperand = NextOp;
406 }
407
408 // Now that the instructions are reassociated, have the functor perform
409 // the transformation...
410 return F.apply(Root);
411 }
412
413 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
414 }
415 return 0;
416}
417
418
419// AddRHS - Implements: X + X --> X << 1
420struct AddRHS {
421 Value *RHS;
422 AddRHS(Value *rhs) : RHS(rhs) {}
423 bool shouldApply(Value *LHS) const { return LHS == RHS; }
424 Instruction *apply(BinaryOperator &Add) const {
425 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
426 ConstantInt::get(Type::UByteTy, 1));
427 }
428};
429
430// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
431// iff C1&C2 == 0
432struct AddMaskingAnd {
433 Constant *C2;
434 AddMaskingAnd(Constant *c) : C2(c) {}
435 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000436 ConstantInt *C1;
437 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
438 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000439 }
440 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000441 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000442 }
443};
444
Chris Lattner183b3362004-04-09 19:05:30 +0000445static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
446 InstCombiner *IC) {
447 // Figure out if the constant is the left or the right argument.
448 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
449 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000450
Chris Lattner183b3362004-04-09 19:05:30 +0000451 if (Constant *SOC = dyn_cast<Constant>(SO)) {
452 if (ConstIsRHS)
453 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
454 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
455 }
456
457 Value *Op0 = SO, *Op1 = ConstOperand;
458 if (!ConstIsRHS)
459 std::swap(Op0, Op1);
460 Instruction *New;
461 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
462 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
463 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
464 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattnerf9d96652004-04-10 19:15:56 +0000465 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000466 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000467 abort();
468 }
Chris Lattner183b3362004-04-09 19:05:30 +0000469 return IC->InsertNewInstBefore(New, BI);
470}
471
472// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
473// constant as the other operand, try to fold the binary operator into the
474// select arguments.
475static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
476 InstCombiner *IC) {
477 // Don't modify shared select instructions
478 if (!SI->hasOneUse()) return 0;
479 Value *TV = SI->getOperand(1);
480 Value *FV = SI->getOperand(2);
481
482 if (isa<Constant>(TV) || isa<Constant>(FV)) {
483 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
484 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
485
486 return new SelectInst(SI->getCondition(), SelectTrueVal,
487 SelectFalseVal);
488 }
489 return 0;
490}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000491
Chris Lattner113f4f42002-06-25 16:13:24 +0000492Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000493 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000494 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000495
Chris Lattnercf4a9962004-04-10 22:01:55 +0000496 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
497 // X + 0 --> X
498 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
499 RHSC->isNullValue())
500 return ReplaceInstUsesWith(I, LHS);
501
502 // X + (signbit) --> X ^ signbit
503 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
504 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
505 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
506 if (Val == (1ULL << NumBits-1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000507 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000508 }
509 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000510
Chris Lattnerb8b97502003-08-13 19:01:45 +0000511 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000512 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000513 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000514 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000515
Chris Lattner147e9752002-05-08 22:46:53 +0000516 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000517 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000518 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000519
520 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000521 if (!isa<Constant>(RHS))
522 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000523 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000524
Chris Lattner57c8d992003-02-18 19:57:07 +0000525 // X*C + X --> X * (C+1)
526 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000527 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000528 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000529 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
530 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000531 return BinaryOperator::createMul(RHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000532 }
533
534 // X + X*C --> X * (C+1)
535 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000536 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000537 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000538 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
539 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000540 return BinaryOperator::createMul(LHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000541 }
542
Chris Lattnerb8b97502003-08-13 19:01:45 +0000543 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000544 ConstantInt *C2;
545 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000546 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000547
Chris Lattnerb9cde762003-10-02 15:11:26 +0000548 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000549 Value *X;
550 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
551 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
552 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000553 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000554
555 // Try to fold constant add into select arguments.
556 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
557 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
558 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000559 }
560
Chris Lattner113f4f42002-06-25 16:13:24 +0000561 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000562}
563
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000564// isSignBit - Return true if the value represented by the constant only has the
565// highest order bit set.
566static bool isSignBit(ConstantInt *CI) {
567 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
568 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
569}
570
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000571static unsigned getTypeSizeInBits(const Type *Ty) {
572 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
573}
574
Chris Lattner022167f2004-03-13 00:11:49 +0000575/// RemoveNoopCast - Strip off nonconverting casts from the value.
576///
577static Value *RemoveNoopCast(Value *V) {
578 if (CastInst *CI = dyn_cast<CastInst>(V)) {
579 const Type *CTy = CI->getType();
580 const Type *OpTy = CI->getOperand(0)->getType();
581 if (CTy->isInteger() && OpTy->isInteger()) {
582 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
583 return RemoveNoopCast(CI->getOperand(0));
584 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
585 return RemoveNoopCast(CI->getOperand(0));
586 }
587 return V;
588}
589
Chris Lattner113f4f42002-06-25 16:13:24 +0000590Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000591 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000592
Chris Lattnere6794492002-08-12 21:17:25 +0000593 if (Op0 == Op1) // sub X, X -> 0
594 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000595
Chris Lattnere6794492002-08-12 21:17:25 +0000596 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000597 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000598 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000599
Chris Lattner8f2f5982003-11-05 01:06:05 +0000600 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
601 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000602 if (C->isAllOnesValue())
603 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000604
Chris Lattner8f2f5982003-11-05 01:06:05 +0000605 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000606 Value *X;
607 if (match(Op1, m_Not(m_Value(X))))
608 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000609 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000610 // -((uint)X >> 31) -> ((int)X >> 31)
611 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000612 if (C->isNullValue()) {
613 Value *NoopCastedRHS = RemoveNoopCast(Op1);
614 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000615 if (SI->getOpcode() == Instruction::Shr)
616 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
617 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000618 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000619 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000620 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000621 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000622 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000623 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000624 // Ok, the transformation is safe. Insert a cast of the incoming
625 // value, then the new shift, then the new cast.
626 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
627 SI->getOperand(0)->getName());
628 Value *InV = InsertNewInstBefore(FirstCast, I);
629 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
630 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000631 if (NewShift->getType() == I.getType())
632 return NewShift;
633 else {
634 InV = InsertNewInstBefore(NewShift, I);
635 return new CastInst(NewShift, I.getType());
636 }
Chris Lattner92295c52004-03-12 23:53:13 +0000637 }
638 }
Chris Lattner022167f2004-03-13 00:11:49 +0000639 }
Chris Lattner183b3362004-04-09 19:05:30 +0000640
641 // Try to fold constant sub into select arguments.
642 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
643 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
644 return R;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000645 }
646
Chris Lattner3082c5a2003-02-18 19:28:33 +0000647 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000648 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000649 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
650 // is not used by anyone else...
651 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000652 if (Op1I->getOpcode() == Instruction::Sub &&
653 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000654 // Swap the two operands of the subexpr...
655 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
656 Op1I->setOperand(0, IIOp1);
657 Op1I->setOperand(1, IIOp0);
658
659 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000660 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000661 }
662
663 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
664 //
665 if (Op1I->getOpcode() == Instruction::And &&
666 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
667 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
668
Chris Lattner396dbfe2004-06-09 05:08:07 +0000669 Value *NewNot =
670 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000671 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000672 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000673
674 // X - X*C --> X * (1-C)
675 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000676 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000677 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner34428442003-05-27 16:40:51 +0000678 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000679 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000680 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000681 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000682 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000683
Chris Lattner57c8d992003-02-18 19:57:07 +0000684 // X*C - X --> X * (C-1)
685 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000686 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000687 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner34428442003-05-27 16:40:51 +0000688 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000689 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000690 return BinaryOperator::createMul(Op1, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000691 }
692
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000693 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000694}
695
Chris Lattnere79e8542004-02-23 06:38:22 +0000696/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
697/// really just returns true if the most significant (sign) bit is set.
698static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
699 if (RHS->getType()->isSigned()) {
700 // True if source is LHS < 0 or LHS <= -1
701 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
702 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
703 } else {
704 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
705 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
706 // the size of the integer type.
707 if (Opcode == Instruction::SetGE)
708 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
709 if (Opcode == Instruction::SetGT)
710 return RHSC->getValue() ==
711 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
712 }
713 return false;
714}
715
Chris Lattner113f4f42002-06-25 16:13:24 +0000716Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000717 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000718 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000719
Chris Lattnere6794492002-08-12 21:17:25 +0000720 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000721 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
722 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000723
724 // ((X << C1)*C2) == (X * (C2 << C1))
725 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
726 if (SI->getOpcode() == Instruction::Shl)
727 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000728 return BinaryOperator::createMul(SI->getOperand(0),
729 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000730
Chris Lattnercce81be2003-09-11 22:24:54 +0000731 if (CI->isNullValue())
732 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
733 if (CI->equalsInt(1)) // X * 1 == X
734 return ReplaceInstUsesWith(I, Op0);
735 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000736 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000737
Chris Lattnercce81be2003-09-11 22:24:54 +0000738 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000739 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
740 return new ShiftInst(Instruction::Shl, Op0,
741 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000742 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000743 if (Op1F->isNullValue())
744 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000745
Chris Lattner3082c5a2003-02-18 19:28:33 +0000746 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
747 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
748 if (Op1F->getValue() == 1.0)
749 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
750 }
Chris Lattner183b3362004-04-09 19:05:30 +0000751
752 // Try to fold constant mul into select arguments.
753 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
754 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
755 return R;
Chris Lattner260ab202002-04-18 17:39:14 +0000756 }
757
Chris Lattner934a64cf2003-03-10 23:23:04 +0000758 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
759 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000760 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000761
Chris Lattner2635b522004-02-23 05:39:21 +0000762 // If one of the operands of the multiply is a cast from a boolean value, then
763 // we know the bool is either zero or one, so this is a 'masking' multiply.
764 // See if we can simplify things based on how the boolean was originally
765 // formed.
766 CastInst *BoolCast = 0;
767 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
768 if (CI->getOperand(0)->getType() == Type::BoolTy)
769 BoolCast = CI;
770 if (!BoolCast)
771 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
772 if (CI->getOperand(0)->getType() == Type::BoolTy)
773 BoolCast = CI;
774 if (BoolCast) {
775 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
776 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
777 const Type *SCOpTy = SCIOp0->getType();
778
Chris Lattnere79e8542004-02-23 06:38:22 +0000779 // If the setcc is true iff the sign bit of X is set, then convert this
780 // multiply into a shift/and combination.
781 if (isa<ConstantInt>(SCIOp1) &&
782 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000783 // Shift the X value right to turn it into "all signbits".
784 Constant *Amt = ConstantUInt::get(Type::UByteTy,
785 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000786 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000787 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000788 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
789 SCIOp0->getName()), I);
790 }
791
792 Value *V =
793 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
794 BoolCast->getOperand(0)->getName()+
795 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000796
797 // If the multiply type is not the same as the source type, sign extend
798 // or truncate to the multiply type.
799 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000800 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000801
802 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000803 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000804 }
805 }
806 }
807
Chris Lattner113f4f42002-06-25 16:13:24 +0000808 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000809}
810
Chris Lattner113f4f42002-06-25 16:13:24 +0000811Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000812 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000813 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000814 if (RHS->equalsInt(1))
815 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000816
Chris Lattnere20c3342004-04-26 14:01:59 +0000817 // div X, -1 == -X
818 if (RHS->isAllOnesValue())
819 return BinaryOperator::createNeg(I.getOperand(0));
820
Chris Lattner3082c5a2003-02-18 19:28:33 +0000821 // Check to see if this is an unsigned division with an exact power of 2,
822 // if so, convert to a right shift.
823 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
824 if (uint64_t Val = C->getValue()) // Don't break X / 0
825 if (uint64_t C = Log2(Val))
826 return new ShiftInst(Instruction::Shr, I.getOperand(0),
827 ConstantUInt::get(Type::UByteTy, C));
828 }
829
830 // 0 / X == 0, we don't need to preserve faults!
831 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
832 if (LHS->equalsInt(0))
833 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
834
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000835 return 0;
836}
837
838
Chris Lattner113f4f42002-06-25 16:13:24 +0000839Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000840 if (I.getType()->isSigned())
841 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner98c6bdf2004-07-06 07:11:42 +0000842 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +0000843 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000844 // X % -Y -> X % Y
845 AddUsesToWorkList(I);
846 I.setOperand(1, RHSNeg);
847 return &I;
848 }
849
Chris Lattner3082c5a2003-02-18 19:28:33 +0000850 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
851 if (RHS->equalsInt(1)) // X % 1 == 0
852 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
853
854 // Check to see if this is an unsigned remainder with an exact power of 2,
855 // if so, convert to a bitwise and.
856 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
857 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +0000858 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000859 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattner3082c5a2003-02-18 19:28:33 +0000860 ConstantUInt::get(I.getType(), Val-1));
861 }
862
863 // 0 % X == 0, we don't need to preserve faults!
864 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
865 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000866 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
867
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000868 return 0;
869}
870
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000871// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000872static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000873 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
874 // Calculate -1 casted to the right type...
875 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
876 uint64_t Val = ~0ULL; // All ones
877 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
878 return CU->getValue() == Val-1;
879 }
880
881 const ConstantSInt *CS = cast<ConstantSInt>(C);
882
883 // Calculate 0111111111..11111
884 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
885 int64_t Val = INT64_MAX; // All ones
886 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
887 return CS->getValue() == Val-1;
888}
889
890// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000891static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000892 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
893 return CU->getValue() == 1;
894
895 const ConstantSInt *CS = cast<ConstantSInt>(C);
896
897 // Calculate 1111111111000000000000
898 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
899 int64_t Val = -1; // All ones
900 Val <<= TypeBits-1; // Shift over to the right spot
901 return CS->getValue() == Val+1;
902}
903
Chris Lattner35167c32004-06-09 07:59:58 +0000904// isOneBitSet - Return true if there is exactly one bit set in the specified
905// constant.
906static bool isOneBitSet(const ConstantInt *CI) {
907 uint64_t V = CI->getRawValue();
908 return V && (V & (V-1)) == 0;
909}
910
Chris Lattner8fc5af42004-09-23 21:46:38 +0000911#if 0 // Currently unused
912// isLowOnes - Return true if the constant is of the form 0+1+.
913static bool isLowOnes(const ConstantInt *CI) {
914 uint64_t V = CI->getRawValue();
915
916 // There won't be bits set in parts that the type doesn't contain.
917 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
918
919 uint64_t U = V+1; // If it is low ones, this should be a power of two.
920 return U && V && (U & V) == 0;
921}
922#endif
923
924// isHighOnes - Return true if the constant is of the form 1+0+.
925// This is the same as lowones(~X).
926static bool isHighOnes(const ConstantInt *CI) {
927 uint64_t V = ~CI->getRawValue();
928
929 // There won't be bits set in parts that the type doesn't contain.
930 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
931
932 uint64_t U = V+1; // If it is low ones, this should be a power of two.
933 return U && V && (U & V) == 0;
934}
935
936
Chris Lattner3ac7c262003-08-13 20:16:26 +0000937/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
938/// are carefully arranged to allow folding of expressions such as:
939///
940/// (A < B) | (A > B) --> (A != B)
941///
942/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
943/// represents that the comparison is true if A == B, and bit value '1' is true
944/// if A < B.
945///
946static unsigned getSetCondCode(const SetCondInst *SCI) {
947 switch (SCI->getOpcode()) {
948 // False -> 0
949 case Instruction::SetGT: return 1;
950 case Instruction::SetEQ: return 2;
951 case Instruction::SetGE: return 3;
952 case Instruction::SetLT: return 4;
953 case Instruction::SetNE: return 5;
954 case Instruction::SetLE: return 6;
955 // True -> 7
956 default:
957 assert(0 && "Invalid SetCC opcode!");
958 return 0;
959 }
960}
961
962/// getSetCCValue - This is the complement of getSetCondCode, which turns an
963/// opcode and two operands into either a constant true or false, or a brand new
964/// SetCC instruction.
965static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
966 switch (Opcode) {
967 case 0: return ConstantBool::False;
968 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
969 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
970 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
971 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
972 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
973 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
974 case 7: return ConstantBool::True;
975 default: assert(0 && "Illegal SetCCCode!"); return 0;
976 }
977}
978
979// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
980struct FoldSetCCLogical {
981 InstCombiner &IC;
982 Value *LHS, *RHS;
983 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
984 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
985 bool shouldApply(Value *V) const {
986 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
987 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
988 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
989 return false;
990 }
991 Instruction *apply(BinaryOperator &Log) const {
992 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
993 if (SCI->getOperand(0) != LHS) {
994 assert(SCI->getOperand(1) == LHS);
995 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
996 }
997
998 unsigned LHSCode = getSetCondCode(SCI);
999 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1000 unsigned Code;
1001 switch (Log.getOpcode()) {
1002 case Instruction::And: Code = LHSCode & RHSCode; break;
1003 case Instruction::Or: Code = LHSCode | RHSCode; break;
1004 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001005 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001006 }
1007
1008 Value *RV = getSetCCValue(Code, LHS, RHS);
1009 if (Instruction *I = dyn_cast<Instruction>(RV))
1010 return I;
1011 // Otherwise, it's a constant boolean value...
1012 return IC.ReplaceInstUsesWith(Log, RV);
1013 }
1014};
1015
1016
Chris Lattnerba1cb382003-09-19 17:17:26 +00001017// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1018// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1019// guaranteed to be either a shift instruction or a binary operator.
1020Instruction *InstCombiner::OptAndOp(Instruction *Op,
1021 ConstantIntegral *OpRHS,
1022 ConstantIntegral *AndRHS,
1023 BinaryOperator &TheAnd) {
1024 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001025 Constant *Together = 0;
1026 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001027 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001028
Chris Lattnerba1cb382003-09-19 17:17:26 +00001029 switch (Op->getOpcode()) {
1030 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001031 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001032 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001033 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001034 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001035 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1036 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001037 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001038 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001039 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001040 }
1041 break;
1042 case Instruction::Or:
1043 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001044 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001045 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001046 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001047 if (Together == AndRHS) // (X | C) & C --> C
1048 return ReplaceInstUsesWith(TheAnd, AndRHS);
1049
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001050 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001051 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1052 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001053 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001054 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001055 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001056 }
1057 }
1058 break;
1059 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001060 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001061 // Adding a one to a single bit bit-field should be turned into an XOR
1062 // of the bit. First thing to check is to see if this AND is with a
1063 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001064 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001065
1066 // Clear bits that are not part of the constant.
1067 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1068
1069 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001070 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001071 // Ok, at this point, we know that we are masking the result of the
1072 // ADD down to exactly one bit. If the constant we are adding has
1073 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001074 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001075
1076 // Check to see if any bits below the one bit set in AndRHSV are set.
1077 if ((AddRHS & (AndRHSV-1)) == 0) {
1078 // If not, the only thing that can effect the output of the AND is
1079 // the bit specified by AndRHSV. If that bit is set, the effect of
1080 // the XOR is to toggle the bit. If it is clear, then the ADD has
1081 // no effect.
1082 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1083 TheAnd.setOperand(0, X);
1084 return &TheAnd;
1085 } else {
1086 std::string Name = Op->getName(); Op->setName("");
1087 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001088 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001089 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001090 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001091 }
1092 }
1093 }
1094 }
1095 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001096
1097 case Instruction::Shl: {
1098 // We know that the AND will not produce any of the bits shifted in, so if
1099 // the anded constant includes them, clear them now!
1100 //
1101 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001102 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1103 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1104
1105 if (CI == ShlMask) { // Masking out bits that the shift already masks
1106 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1107 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001108 TheAnd.setOperand(1, CI);
1109 return &TheAnd;
1110 }
1111 break;
1112 }
1113 case Instruction::Shr:
1114 // We know that the AND will not produce any of the bits shifted in, so if
1115 // the anded constant includes them, clear them now! This only applies to
1116 // unsigned shifts, because a signed shr may bring in set bits!
1117 //
1118 if (AndRHS->getType()->isUnsigned()) {
1119 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001120 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1121 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1122
1123 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1124 return ReplaceInstUsesWith(TheAnd, Op);
1125 } else if (CI != AndRHS) {
1126 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001127 return &TheAnd;
1128 }
Chris Lattner7e794272004-09-24 15:21:34 +00001129 } else { // Signed shr.
1130 // See if this is shifting in some sign extension, then masking it out
1131 // with an and.
1132 if (Op->hasOneUse()) {
1133 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1134 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1135 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1136 if (CI == ShrMask) { // Masking out bits shifted in.
1137 // Make the argument unsigned.
1138 Value *ShVal = Op->getOperand(0);
1139 ShVal = InsertCastBefore(ShVal,
1140 ShVal->getType()->getUnsignedVersion(),
1141 TheAnd);
1142 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1143 OpRHS, Op->getName()),
1144 TheAnd);
1145 return new CastInst(ShVal, Op->getType());
1146 }
1147 }
Chris Lattner2da29172003-09-19 19:05:02 +00001148 }
1149 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001150 }
1151 return 0;
1152}
1153
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001154
Chris Lattner113f4f42002-06-25 16:13:24 +00001155Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001156 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001157 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001158
1159 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001160 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1161 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001162
1163 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001164 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001165 if (RHS->isAllOnesValue())
1166 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001167
Chris Lattnerba1cb382003-09-19 17:17:26 +00001168 // Optimize a variety of ((val OP C1) & C2) combinations...
1169 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1170 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001171 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001172 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001173 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1174 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001175 }
Chris Lattner183b3362004-04-09 19:05:30 +00001176
1177 // Try to fold constant and into select arguments.
1178 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1179 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1180 return R;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001181 }
1182
Chris Lattnerbb74e222003-03-10 23:06:50 +00001183 Value *Op0NotVal = dyn_castNotVal(Op0);
1184 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001185
Chris Lattner023a4832004-06-18 06:07:51 +00001186 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1187 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1188
Misha Brukman9c003d82004-07-30 12:50:08 +00001189 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001190 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001191 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1192 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001193 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001194 return BinaryOperator::createNot(Or);
1195 }
1196
Chris Lattner3ac7c262003-08-13 20:16:26 +00001197 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1198 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1199 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1200 return R;
1201
Chris Lattner113f4f42002-06-25 16:13:24 +00001202 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001203}
1204
1205
1206
Chris Lattner113f4f42002-06-25 16:13:24 +00001207Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001208 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001209 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001210
1211 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001212 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1213 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001214
1215 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001216 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001217 if (RHS->isAllOnesValue())
1218 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001219
Chris Lattnerd4252a72004-07-30 07:50:03 +00001220 ConstantInt *C1; Value *X;
1221 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1222 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1223 std::string Op0Name = Op0->getName(); Op0->setName("");
1224 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1225 InsertNewInstBefore(Or, I);
1226 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1227 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001228
Chris Lattnerd4252a72004-07-30 07:50:03 +00001229 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1230 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1231 std::string Op0Name = Op0->getName(); Op0->setName("");
1232 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1233 InsertNewInstBefore(Or, I);
1234 return BinaryOperator::createXor(Or,
1235 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001236 }
Chris Lattner183b3362004-04-09 19:05:30 +00001237
1238 // Try to fold constant and into select arguments.
1239 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1240 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1241 return R;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001242 }
1243
Chris Lattner812aab72003-08-12 19:11:07 +00001244 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001245 Value *A, *B; ConstantInt *C1, *C2;
1246 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1247 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1248 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001249
Chris Lattnerd4252a72004-07-30 07:50:03 +00001250 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1251 if (A == Op1) // ~A | A == -1
1252 return ReplaceInstUsesWith(I,
1253 ConstantIntegral::getAllOnesValue(I.getType()));
1254 } else {
1255 A = 0;
1256 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001257
Chris Lattnerd4252a72004-07-30 07:50:03 +00001258 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1259 if (Op0 == B)
1260 return ReplaceInstUsesWith(I,
1261 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001262
Misha Brukman9c003d82004-07-30 12:50:08 +00001263 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001264 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1265 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1266 I.getName()+".demorgan"), I);
1267 return BinaryOperator::createNot(And);
1268 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001269 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001270
Chris Lattner3ac7c262003-08-13 20:16:26 +00001271 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
1272 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1273 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1274 return R;
1275
Chris Lattner113f4f42002-06-25 16:13:24 +00001276 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001277}
1278
Chris Lattnerc2076352004-02-16 01:20:27 +00001279// XorSelf - Implements: X ^ X --> 0
1280struct XorSelf {
1281 Value *RHS;
1282 XorSelf(Value *rhs) : RHS(rhs) {}
1283 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1284 Instruction *apply(BinaryOperator &Xor) const {
1285 return &Xor;
1286 }
1287};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001288
1289
Chris Lattner113f4f42002-06-25 16:13:24 +00001290Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001291 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001292 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001293
Chris Lattnerc2076352004-02-16 01:20:27 +00001294 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1295 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1296 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001297 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001298 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001299
Chris Lattner97638592003-07-23 21:37:07 +00001300 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001301 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001302 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001303 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001304
Chris Lattner97638592003-07-23 21:37:07 +00001305 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001306 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001307 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001308 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001309 return new SetCondInst(SCI->getInverseCondition(),
1310 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001311
Chris Lattner8f2f5982003-11-05 01:06:05 +00001312 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001313 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1314 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001315 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1316 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001317 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001318 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001319 }
Chris Lattner023a4832004-06-18 06:07:51 +00001320
1321 // ~(~X & Y) --> (X | ~Y)
1322 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1323 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1324 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1325 Instruction *NotY =
1326 BinaryOperator::createNot(Op0I->getOperand(1),
1327 Op0I->getOperand(1)->getName()+".not");
1328 InsertNewInstBefore(NotY, I);
1329 return BinaryOperator::createOr(Op0NotVal, NotY);
1330 }
1331 }
Chris Lattner97638592003-07-23 21:37:07 +00001332
1333 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001334 switch (Op0I->getOpcode()) {
1335 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001336 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001337 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001338 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1339 return BinaryOperator::createSub(
1340 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001341 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001342 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001343 }
Chris Lattnere5806662003-11-04 23:50:51 +00001344 break;
1345 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001346 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001347 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1348 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001349 break;
1350 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001351 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001352 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001353 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001354 break;
1355 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001356 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001357 }
Chris Lattner183b3362004-04-09 19:05:30 +00001358
1359 // Try to fold constant and into select arguments.
1360 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1361 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1362 return R;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001363 }
1364
Chris Lattnerbb74e222003-03-10 23:06:50 +00001365 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001366 if (X == Op1)
1367 return ReplaceInstUsesWith(I,
1368 ConstantIntegral::getAllOnesValue(I.getType()));
1369
Chris Lattnerbb74e222003-03-10 23:06:50 +00001370 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001371 if (X == Op0)
1372 return ReplaceInstUsesWith(I,
1373 ConstantIntegral::getAllOnesValue(I.getType()));
1374
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001375 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001376 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001377 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1378 cast<BinaryOperator>(Op1I)->swapOperands();
1379 I.swapOperands();
1380 std::swap(Op0, Op1);
1381 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1382 I.swapOperands();
1383 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001384 }
1385 } else if (Op1I->getOpcode() == Instruction::Xor) {
1386 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1387 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1388 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1389 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1390 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001391
1392 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001393 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001394 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1395 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001396 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001397 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1398 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001399 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001400 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001401 } else if (Op0I->getOpcode() == Instruction::Xor) {
1402 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1403 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1404 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1405 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001406 }
1407
Chris Lattner7aa2d472004-08-01 19:42:59 +00001408 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001409 Value *A, *B; ConstantInt *C1, *C2;
1410 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1411 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00001412 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00001413 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001414
Chris Lattner3ac7c262003-08-13 20:16:26 +00001415 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1416 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1417 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1418 return R;
1419
Chris Lattner113f4f42002-06-25 16:13:24 +00001420 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001421}
1422
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001423// AddOne, SubOne - Add or subtract a constant one from an integer constant...
1424static Constant *AddOne(ConstantInt *C) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001425 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001426}
1427static Constant *SubOne(ConstantInt *C) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001428 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001429}
1430
Chris Lattner1fc23f32002-05-09 20:11:54 +00001431// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1432// true when both operands are equal...
1433//
Chris Lattner113f4f42002-06-25 16:13:24 +00001434static bool isTrueWhenEqual(Instruction &I) {
1435 return I.getOpcode() == Instruction::SetEQ ||
1436 I.getOpcode() == Instruction::SetGE ||
1437 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +00001438}
1439
Chris Lattner113f4f42002-06-25 16:13:24 +00001440Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001441 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001442 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1443 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001444
1445 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001446 if (Op0 == Op1)
1447 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001448
Chris Lattnerd07283a2003-08-13 05:38:46 +00001449 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1450 if (isa<ConstantPointerNull>(Op1) &&
1451 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001452 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1453
Chris Lattnerd07283a2003-08-13 05:38:46 +00001454
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001455 // setcc's with boolean values can always be turned into bitwise operations
1456 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00001457 switch (I.getOpcode()) {
1458 default: assert(0 && "Invalid setcc instruction!");
1459 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001460 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001461 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001462 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001463 }
Chris Lattner4456da62004-08-11 00:50:51 +00001464 case Instruction::SetNE:
1465 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001466
Chris Lattner4456da62004-08-11 00:50:51 +00001467 case Instruction::SetGT:
1468 std::swap(Op0, Op1); // Change setgt -> setlt
1469 // FALL THROUGH
1470 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1471 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1472 InsertNewInstBefore(Not, I);
1473 return BinaryOperator::createAnd(Not, Op1);
1474 }
1475 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001476 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00001477 // FALL THROUGH
1478 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1479 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1480 InsertNewInstBefore(Not, I);
1481 return BinaryOperator::createOr(Not, Op1);
1482 }
1483 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001484 }
1485
Chris Lattner2dd01742004-06-09 04:24:29 +00001486 // See if we are doing a comparison between a constant and an instruction that
1487 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001488 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere1e10e12004-05-25 06:32:08 +00001489 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001490 switch (LHSI->getOpcode()) {
1491 case Instruction::And:
1492 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1493 LHSI->getOperand(0)->hasOneUse()) {
1494 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1495 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1496 // happens a LOT in code produced by the C front-end, for bitfield
1497 // access.
1498 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1499 ConstantUInt *ShAmt;
1500 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1501 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1502 const Type *Ty = LHSI->getType();
1503
1504 // We can fold this as long as we can't shift unknown bits
1505 // into the mask. This can only happen with signed shift
1506 // rights, as they sign-extend.
1507 if (ShAmt) {
1508 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
1509 Shift->getType()->isUnsigned();
1510 if (!CanFold) {
1511 // To test for the bad case of the signed shr, see if any
1512 // of the bits shifted in could be tested after the mask.
1513 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00001514 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001515 Constant *ShVal =
1516 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1517 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1518 CanFold = true;
1519 }
1520
1521 if (CanFold) {
1522 unsigned ShiftOp = Shift->getOpcode() == Instruction::Shl
1523 ? Instruction::Shr : Instruction::Shl;
1524 Constant *NewCst = ConstantExpr::get(ShiftOp, CI, ShAmt);
1525
1526 // Check to see if we are shifting out any of the bits being
1527 // compared.
1528 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1529 // If we shifted bits out, the fold is not going to work out.
1530 // As a special case, check to see if this means that the
1531 // result is always true or false now.
1532 if (I.getOpcode() == Instruction::SetEQ)
1533 return ReplaceInstUsesWith(I, ConstantBool::False);
1534 if (I.getOpcode() == Instruction::SetNE)
1535 return ReplaceInstUsesWith(I, ConstantBool::True);
1536 } else {
1537 I.setOperand(1, NewCst);
1538 LHSI->setOperand(1, ConstantExpr::get(ShiftOp, AndCST,ShAmt));
1539 LHSI->setOperand(0, Shift->getOperand(0));
1540 WorkList.push_back(Shift); // Shift is dead.
1541 AddUsesToWorkList(I);
1542 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00001543 }
1544 }
Chris Lattner35167c32004-06-09 07:59:58 +00001545 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001546 }
1547 break;
Chris Lattner7e794272004-09-24 15:21:34 +00001548
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001549 case Instruction::Div:
1550 if (0 && isa<ConstantInt>(LHSI->getOperand(1))) {
1551 std::cerr << "COULD FOLD: " << *LHSI;
1552 std::cerr << "COULD FOLD: " << I << "\n";
1553 }
1554 break;
1555 case Instruction::Select:
1556 // If either operand of the select is a constant, we can fold the
1557 // comparison into the select arms, which will cause one to be
1558 // constant folded and the select turned into a bitwise or.
1559 Value *Op1 = 0, *Op2 = 0;
1560 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00001561 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00001562 // Fold the known value into the constant operand.
1563 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
1564 // Insert a new SetCC of the other select operand.
1565 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00001566 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00001567 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00001568 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00001569 // Fold the known value into the constant operand.
1570 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
1571 // Insert a new SetCC of the other select operand.
1572 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00001573 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00001574 I.getName()), I);
1575 }
Chris Lattner2dd01742004-06-09 04:24:29 +00001576 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001577
1578 if (Op1)
1579 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
1580 break;
1581 }
1582
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001583 // Simplify seteq and setne instructions...
1584 if (I.getOpcode() == Instruction::SetEQ ||
1585 I.getOpcode() == Instruction::SetNE) {
1586 bool isSetNE = I.getOpcode() == Instruction::SetNE;
1587
Chris Lattnercfbce7c2003-07-23 17:26:36 +00001588 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001589 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00001590 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1591 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00001592 case Instruction::Rem:
1593 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1594 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
1595 BO->hasOneUse() &&
1596 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
1597 if (unsigned L2 =
1598 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
1599 const Type *UTy = BO->getType()->getUnsignedVersion();
1600 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
1601 UTy, "tmp"), I);
1602 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
1603 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
1604 RHSCst, BO->getName()), I);
1605 return BinaryOperator::create(I.getOpcode(), NewRem,
1606 Constant::getNullValue(UTy));
1607 }
1608 break;
1609
Chris Lattnerc992add2003-08-13 05:33:12 +00001610 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00001611 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1612 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00001613 if (BO->hasOneUse())
1614 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1615 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00001616 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00001617 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1618 // efficiently invertible, or if the add has just this one use.
1619 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00001620
Chris Lattnerc992add2003-08-13 05:33:12 +00001621 if (Value *NegVal = dyn_castNegVal(BOp1))
1622 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1623 else if (Value *NegVal = dyn_castNegVal(BOp0))
1624 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001625 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00001626 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1627 BO->setName("");
1628 InsertNewInstBefore(Neg, I);
1629 return new SetCondInst(I.getOpcode(), BOp0, Neg);
1630 }
1631 }
1632 break;
1633 case Instruction::Xor:
1634 // For the xor case, we can xor two constants together, eliminating
1635 // the explicit xor.
1636 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1637 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001638 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00001639
1640 // FALLTHROUGH
1641 case Instruction::Sub:
1642 // Replace (([sub|xor] A, B) != 0) with (A != B)
1643 if (CI->isNullValue())
1644 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1645 BO->getOperand(1));
1646 break;
1647
1648 case Instruction::Or:
1649 // If bits are being or'd in that are not present in the constant we
1650 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001651 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001652 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001653 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001654 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001655 }
Chris Lattnerc992add2003-08-13 05:33:12 +00001656 break;
1657
1658 case Instruction::And:
1659 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001660 // If bits are being compared against that are and'd out, then the
1661 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001662 if (!ConstantExpr::getAnd(CI,
1663 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001664 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00001665
Chris Lattner35167c32004-06-09 07:59:58 +00001666 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00001667 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00001668 return new SetCondInst(isSetNE ? Instruction::SetEQ :
1669 Instruction::SetNE, Op0,
1670 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00001671
Chris Lattnerc992add2003-08-13 05:33:12 +00001672 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
1673 // to be a signed value as appropriate.
1674 if (isSignBit(BOC)) {
1675 Value *X = BO->getOperand(0);
1676 // If 'X' is not signed, insert a cast now...
1677 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001678 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerc992add2003-08-13 05:33:12 +00001679 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1680 InsertNewInstBefore(NewCI, I);
1681 X = NewCI;
1682 }
1683 return new SetCondInst(isSetNE ? Instruction::SetLT :
1684 Instruction::SetGE, X,
1685 Constant::getNullValue(X->getType()));
1686 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00001687
1688 // ((X & ~7) == 0) --> X < 7
1689 if (CI->isNullValue() && isHighOnes(BOC)) {
1690 Value *X = BO->getOperand(0);
1691 Constant *NotX = ConstantExpr::getNot(BOC);
1692
1693 // If 'X' is signed, insert a cast now.
1694 if (!NotX->getType()->isSigned()) {
1695 const Type *DestTy = NotX->getType()->getUnsignedVersion();
1696 CastInst *NewCI = new CastInst(X, DestTy, X->getName()+".uns");
1697 InsertNewInstBefore(NewCI, I);
1698 X = NewCI;
1699 NotX = ConstantExpr::getCast(NotX, DestTy);
1700 }
1701
1702 return new SetCondInst(isSetNE ? Instruction::SetGE :
1703 Instruction::SetLT, X, NotX);
1704 }
1705
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001706 }
Chris Lattnerc992add2003-08-13 05:33:12 +00001707 default: break;
1708 }
1709 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00001710 } else { // Not a SetEQ/SetNE
1711 // If the LHS is a cast from an integral value of the same size,
1712 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
1713 Value *CastOp = Cast->getOperand(0);
1714 const Type *SrcTy = CastOp->getType();
1715 unsigned SrcTySize = SrcTy->getPrimitiveSize();
1716 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
1717 SrcTySize == Cast->getType()->getPrimitiveSize()) {
1718 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
1719 "Source and destination signednesses should differ!");
1720 if (Cast->getType()->isSigned()) {
1721 // If this is a signed comparison, check for comparisons in the
1722 // vicinity of zero.
1723 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
1724 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001725 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00001726 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
1727 else if (I.getOpcode() == Instruction::SetGT &&
1728 cast<ConstantSInt>(CI)->getValue() == -1)
1729 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001730 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00001731 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
1732 } else {
1733 ConstantUInt *CUI = cast<ConstantUInt>(CI);
1734 if (I.getOpcode() == Instruction::SetLT &&
1735 CUI->getValue() == 1ULL << (SrcTySize*8-1))
1736 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001737 return BinaryOperator::createSetGT(CastOp,
1738 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00001739 else if (I.getOpcode() == Instruction::SetGT &&
1740 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
1741 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001742 return BinaryOperator::createSetLT(CastOp,
1743 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00001744 }
1745 }
1746 }
Chris Lattnere967b342003-06-04 05:10:11 +00001747 }
Chris Lattner791ac1a2003-06-01 03:35:25 +00001748
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001749 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +00001750 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001751 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1752 return ReplaceInstUsesWith(I, ConstantBool::False);
1753 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1754 return ReplaceInstUsesWith(I, ConstantBool::True);
1755 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001756 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001757 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001758 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001759
Chris Lattnere6794492002-08-12 21:17:25 +00001760 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001761 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1762 return ReplaceInstUsesWith(I, ConstantBool::False);
1763 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1764 return ReplaceInstUsesWith(I, ConstantBool::True);
1765 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001766 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001767 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001768 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001769
1770 // Comparing against a value really close to min or max?
1771 } else if (isMinValuePlusOne(CI)) {
1772 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001773 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001774 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001775 return BinaryOperator::createSetNE(Op0, SubOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001776
1777 } else if (isMaxValueMinusOne(CI)) {
1778 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001779 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001780 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001781 return BinaryOperator::createSetNE(Op0, AddOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001782 }
Chris Lattner59611142004-02-23 05:47:48 +00001783
1784 // If we still have a setle or setge instruction, turn it into the
1785 // appropriate setlt or setgt instruction. Since the border cases have
1786 // already been handled above, this requires little checking.
1787 //
1788 if (I.getOpcode() == Instruction::SetLE)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001789 return BinaryOperator::createSetLT(Op0, AddOne(CI));
Chris Lattner59611142004-02-23 05:47:48 +00001790 if (I.getOpcode() == Instruction::SetGE)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001791 return BinaryOperator::createSetGT(Op0, SubOne(CI));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001792 }
1793
Chris Lattner16930792003-11-03 04:25:02 +00001794 // Test to see if the operands of the setcc are casted versions of other
1795 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00001796 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1797 Value *CastOp0 = CI->getOperand(0);
1798 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00001799 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00001800 (I.getOpcode() == Instruction::SetEQ ||
1801 I.getOpcode() == Instruction::SetNE)) {
1802 // We keep moving the cast from the left operand over to the right
1803 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00001804 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00001805
1806 // If operand #1 is a cast instruction, see if we can eliminate it as
1807 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00001808 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
1809 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00001810 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00001811 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00001812
1813 // If Op1 is a constant, we can fold the cast into the constant.
1814 if (Op1->getType() != Op0->getType())
1815 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1816 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
1817 } else {
1818 // Otherwise, cast the RHS right before the setcc
1819 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
1820 InsertNewInstBefore(cast<Instruction>(Op1), I);
1821 }
1822 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
1823 }
1824
Chris Lattner6444c372003-11-03 05:17:03 +00001825 // Handle the special case of: setcc (cast bool to X), <cst>
1826 // This comes up when you have code like
1827 // int X = A < B;
1828 // if (X) ...
1829 // For generality, we handle any zero-extension of any operand comparison
1830 // with a constant.
1831 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
1832 const Type *SrcTy = CastOp0->getType();
1833 const Type *DestTy = Op0->getType();
1834 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
1835 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
1836 // Ok, we have an expansion of operand 0 into a new type. Get the
1837 // constant value, masink off bits which are not set in the RHS. These
1838 // could be set if the destination value is signed.
1839 uint64_t ConstVal = ConstantRHS->getRawValue();
1840 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
1841
1842 // If the constant we are comparing it with has high bits set, which
1843 // don't exist in the original value, the values could never be equal,
1844 // because the source would be zero extended.
1845 unsigned SrcBits =
1846 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00001847 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
1848 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00001849 switch (I.getOpcode()) {
1850 default: assert(0 && "Unknown comparison type!");
1851 case Instruction::SetEQ:
1852 return ReplaceInstUsesWith(I, ConstantBool::False);
1853 case Instruction::SetNE:
1854 return ReplaceInstUsesWith(I, ConstantBool::True);
1855 case Instruction::SetLT:
1856 case Instruction::SetLE:
1857 if (DestTy->isSigned() && HasSignBit)
1858 return ReplaceInstUsesWith(I, ConstantBool::False);
1859 return ReplaceInstUsesWith(I, ConstantBool::True);
1860 case Instruction::SetGT:
1861 case Instruction::SetGE:
1862 if (DestTy->isSigned() && HasSignBit)
1863 return ReplaceInstUsesWith(I, ConstantBool::True);
1864 return ReplaceInstUsesWith(I, ConstantBool::False);
1865 }
1866 }
1867
1868 // Otherwise, we can replace the setcc with a setcc of the smaller
1869 // operand value.
1870 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
1871 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
1872 }
1873 }
1874 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001875 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001876}
1877
1878
1879
Chris Lattnere8d6c602003-03-10 19:16:08 +00001880Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001881 assert(I.getOperand(1)->getType() == Type::UByteTy);
1882 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001883 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001884
1885 // shl X, 0 == X and shr X, 0 == X
1886 // shl 0, X == 0 and shr 0, X == 0
1887 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00001888 Op0 == Constant::getNullValue(Op0->getType()))
1889 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001890
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001891 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
1892 if (!isLeftShift)
1893 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1894 if (CSI->isAllOnesValue())
1895 return ReplaceInstUsesWith(I, CSI);
1896
Chris Lattner183b3362004-04-09 19:05:30 +00001897 // Try to fold constant and into select arguments.
1898 if (isa<Constant>(Op0))
1899 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1900 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1901 return R;
1902
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001903 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001904 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1905 // of a signed value.
1906 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00001907 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00001908 if (CUI->getValue() >= TypeBits) {
1909 if (!Op0->getType()->isSigned() || isLeftShift)
1910 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
1911 else {
1912 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
1913 return &I;
1914 }
1915 }
Chris Lattner55f3d942002-09-10 23:04:09 +00001916
Chris Lattnerede3fe02003-08-13 04:18:28 +00001917 // ((X*C1) << C2) == (X * (C1 << C2))
1918 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1919 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1920 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001921 return BinaryOperator::createMul(BO->getOperand(0),
1922 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00001923
Chris Lattner183b3362004-04-09 19:05:30 +00001924 // Try to fold constant and into select arguments.
1925 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1926 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1927 return R;
Chris Lattnerede3fe02003-08-13 04:18:28 +00001928
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001929 // If the operand is an bitwise operator with a constant RHS, and the
1930 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001931 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001932 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1933 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1934 bool isValid = true; // Valid only for And, Or, Xor
1935 bool highBitSet = false; // Transform if high bit of constant set?
1936
1937 switch (Op0BO->getOpcode()) {
1938 default: isValid = false; break; // Do not perform transform!
1939 case Instruction::Or:
1940 case Instruction::Xor:
1941 highBitSet = false;
1942 break;
1943 case Instruction::And:
1944 highBitSet = true;
1945 break;
1946 }
1947
1948 // If this is a signed shift right, and the high bit is modified
1949 // by the logical operation, do not perform the transformation.
1950 // The highBitSet boolean indicates the value of the high bit of
1951 // the constant which would cause it to be modified for this
1952 // operation.
1953 //
1954 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1955 uint64_t Val = Op0C->getRawValue();
1956 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1957 }
1958
1959 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001960 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001961
1962 Instruction *NewShift =
1963 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1964 Op0BO->getName());
1965 Op0BO->setName("");
1966 InsertNewInstBefore(NewShift, I);
1967
1968 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1969 NewRHS);
1970 }
1971 }
1972
Chris Lattner3204d4e2003-07-24 17:52:58 +00001973 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001974 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00001975 if (ConstantUInt *ShiftAmt1C =
1976 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001977 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1978 unsigned ShiftAmt2 = CUI->getValue();
1979
1980 // Check for (A << c1) << c2 and (A >> c1) >> c2
1981 if (I.getOpcode() == Op0SI->getOpcode()) {
1982 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00001983 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
1984 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00001985 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1986 ConstantUInt::get(Type::UByteTy, Amt));
1987 }
1988
Chris Lattnerab780df2003-07-24 18:38:56 +00001989 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1990 // signed types, we can only support the (A >> c1) << c2 configuration,
1991 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001992 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001993 // Calculate bitmask for what gets shifted off the edge...
1994 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001995 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001996 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001997 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001998 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00001999
2000 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002001 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2002 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00002003 InsertNewInstBefore(Mask, I);
2004
2005 // Figure out what flavor of shift we should use...
2006 if (ShiftAmt1 == ShiftAmt2)
2007 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2008 else if (ShiftAmt1 < ShiftAmt2) {
2009 return new ShiftInst(I.getOpcode(), Mask,
2010 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2011 } else {
2012 return new ShiftInst(Op0SI->getOpcode(), Mask,
2013 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2014 }
2015 }
2016 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002017 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00002018
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002019 return 0;
2020}
2021
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002022enum CastType {
2023 Noop = 0,
2024 Truncate = 1,
2025 Signext = 2,
2026 Zeroext = 3
2027};
2028
2029/// getCastType - In the future, we will split the cast instruction into these
2030/// various types. Until then, we have to do the analysis here.
2031static CastType getCastType(const Type *Src, const Type *Dest) {
2032 assert(Src->isIntegral() && Dest->isIntegral() &&
2033 "Only works on integral types!");
2034 unsigned SrcSize = Src->getPrimitiveSize()*8;
2035 if (Src == Type::BoolTy) SrcSize = 1;
2036 unsigned DestSize = Dest->getPrimitiveSize()*8;
2037 if (Dest == Type::BoolTy) DestSize = 1;
2038
2039 if (SrcSize == DestSize) return Noop;
2040 if (SrcSize > DestSize) return Truncate;
2041 if (Src->isSigned()) return Signext;
2042 return Zeroext;
2043}
2044
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002045
Chris Lattner48a44f72002-05-02 17:06:02 +00002046// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2047// instruction.
2048//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002049static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00002050 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002051
Chris Lattner650b6da2002-08-02 20:00:25 +00002052 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2053 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00002054 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00002055 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00002056 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00002057
Chris Lattner4fbad962004-07-21 04:27:24 +00002058 // If we are casting between pointer and integer types, treat pointers as
2059 // integers of the appropriate size for the code below.
2060 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2061 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2062 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00002063
Chris Lattner48a44f72002-05-02 17:06:02 +00002064 // Allow free casting and conversion of sizes as long as the sign doesn't
2065 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002066 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002067 CastType FirstCast = getCastType(SrcTy, MidTy);
2068 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00002069
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002070 // Capture the effect of these two casts. If the result is a legal cast,
2071 // the CastType is stored here, otherwise a special code is used.
2072 static const unsigned CastResult[] = {
2073 // First cast is noop
2074 0, 1, 2, 3,
2075 // First cast is a truncate
2076 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2077 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00002078 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002079 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00002080 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002081 };
2082
2083 unsigned Result = CastResult[FirstCast*4+SecondCast];
2084 switch (Result) {
2085 default: assert(0 && "Illegal table value!");
2086 case 0:
2087 case 1:
2088 case 2:
2089 case 3:
2090 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2091 // truncates, we could eliminate more casts.
2092 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2093 case 4:
2094 return false; // Not possible to eliminate this here.
2095 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00002096 // Sign or zero extend followed by truncate is always ok if the result
2097 // is a truncate or noop.
2098 CastType ResultCast = getCastType(SrcTy, DstTy);
2099 if (ResultCast == Noop || ResultCast == Truncate)
2100 return true;
2101 // Otherwise we are still growing the value, we are only safe if the
2102 // result will match the sign/zeroextendness of the result.
2103 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00002104 }
Chris Lattner650b6da2002-08-02 20:00:25 +00002105 }
Chris Lattner48a44f72002-05-02 17:06:02 +00002106 return false;
2107}
2108
Chris Lattner11ffd592004-07-20 05:21:00 +00002109static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002110 if (V->getType() == Ty || isa<Constant>(V)) return false;
2111 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00002112 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2113 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002114 return false;
2115 return true;
2116}
2117
2118/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2119/// InsertBefore instruction. This is specialized a bit to avoid inserting
2120/// casts that are known to not do anything...
2121///
2122Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2123 Instruction *InsertBefore) {
2124 if (V->getType() == DestTy) return V;
2125 if (Constant *C = dyn_cast<Constant>(V))
2126 return ConstantExpr::getCast(C, DestTy);
2127
2128 CastInst *CI = new CastInst(V, DestTy, V->getName());
2129 InsertNewInstBefore(CI, *InsertBefore);
2130 return CI;
2131}
Chris Lattner48a44f72002-05-02 17:06:02 +00002132
2133// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002134//
Chris Lattner113f4f42002-06-25 16:13:24 +00002135Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002136 Value *Src = CI.getOperand(0);
2137
Chris Lattner48a44f72002-05-02 17:06:02 +00002138 // If the user is casting a value to the same type, eliminate this cast
2139 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002140 if (CI.getType() == Src->getType())
2141 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002142
Chris Lattner48a44f72002-05-02 17:06:02 +00002143 // If casting the result of another cast instruction, try to eliminate this
2144 // one!
2145 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002146 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002147 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner11ffd592004-07-20 05:21:00 +00002148 CSrc->getType(), CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002149 // This instruction now refers directly to the cast's src operand. This
2150 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002151 CI.setOperand(0, CSrc->getOperand(0));
2152 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002153 }
2154
Chris Lattner650b6da2002-08-02 20:00:25 +00002155 // If this is an A->B->A cast, and we are dealing with integral types, try
2156 // to convert this into a logical 'and' instruction.
2157 //
2158 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002159 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002160 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2161 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2162 assert(CSrc->getType() != Type::ULongTy &&
2163 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002164 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002165 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002166 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002167 }
2168 }
2169
Chris Lattner03841652004-05-25 04:29:21 +00002170 // If this is a cast to bool, turn it into the appropriate setne instruction.
2171 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002172 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002173 Constant::getNullValue(CI.getOperand(0)->getType()));
2174
Chris Lattnerd0d51602003-06-21 23:12:02 +00002175 // If casting the result of a getelementptr instruction with no offset, turn
2176 // this into a cast of the original pointer!
2177 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002178 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002179 bool AllZeroOperands = true;
2180 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2181 if (!isa<Constant>(GEP->getOperand(i)) ||
2182 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2183 AllZeroOperands = false;
2184 break;
2185 }
2186 if (AllZeroOperands) {
2187 CI.setOperand(0, GEP->getOperand(0));
2188 return &CI;
2189 }
2190 }
2191
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002192 // If we are casting a malloc or alloca to a pointer to a type of the same
2193 // size, rewrite the allocation instruction to allocate the "right" type.
2194 //
2195 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002196 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002197 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2198 // Get the type really allocated and the type casted to...
2199 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002200 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002201 if (AllocElTy->isSized() && CastElTy->isSized()) {
2202 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2203 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002204
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002205 // If the allocation is for an even multiple of the cast type size
2206 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2207 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002208 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002209 std::string Name = AI->getName(); AI->setName("");
2210 AllocationInst *New;
2211 if (isa<MallocInst>(AI))
2212 New = new MallocInst(CastElTy, Amt, Name);
2213 else
2214 New = new AllocaInst(CastElTy, Amt, Name);
2215 InsertNewInstBefore(New, *AI);
2216 return ReplaceInstUsesWith(CI, New);
2217 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002218 }
2219 }
2220
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002221 // If the source value is an instruction with only this use, we can attempt to
2222 // propagate the cast into the instruction. Also, only handle integral types
2223 // for now.
2224 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002225 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002226 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2227 const Type *DestTy = CI.getType();
2228 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2229 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2230
2231 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2232 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2233
2234 switch (SrcI->getOpcode()) {
2235 case Instruction::Add:
2236 case Instruction::Mul:
2237 case Instruction::And:
2238 case Instruction::Or:
2239 case Instruction::Xor:
2240 // If we are discarding information, or just changing the sign, rewrite.
2241 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2242 // Don't insert two casts if they cannot be eliminated. We allow two
2243 // casts to be inserted if the sizes are the same. This could only be
2244 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00002245 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2246 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002247 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2248 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2249 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2250 ->getOpcode(), Op0c, Op1c);
2251 }
2252 }
2253 break;
2254 case Instruction::Shl:
2255 // Allow changing the sign of the source operand. Do not allow changing
2256 // the size of the shift, UNLESS the shift amount is a constant. We
2257 // mush not change variable sized shifts to a smaller size, because it
2258 // is undefined to shift more bits out than exist in the value.
2259 if (DestBitSize == SrcBitSize ||
2260 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2261 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2262 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2263 }
2264 break;
2265 }
2266 }
2267
Chris Lattner260ab202002-04-18 17:39:14 +00002268 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00002269}
2270
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002271/// GetSelectFoldableOperands - We want to turn code that looks like this:
2272/// %C = or %A, %B
2273/// %D = select %cond, %C, %A
2274/// into:
2275/// %C = select %cond, %B, 0
2276/// %D = or %A, %C
2277///
2278/// Assuming that the specified instruction is an operand to the select, return
2279/// a bitmask indicating which operands of this instruction are foldable if they
2280/// equal the other incoming value of the select.
2281///
2282static unsigned GetSelectFoldableOperands(Instruction *I) {
2283 switch (I->getOpcode()) {
2284 case Instruction::Add:
2285 case Instruction::Mul:
2286 case Instruction::And:
2287 case Instruction::Or:
2288 case Instruction::Xor:
2289 return 3; // Can fold through either operand.
2290 case Instruction::Sub: // Can only fold on the amount subtracted.
2291 case Instruction::Shl: // Can only fold on the shift amount.
2292 case Instruction::Shr:
2293 return 1;
2294 default:
2295 return 0; // Cannot fold
2296 }
2297}
2298
2299/// GetSelectFoldableConstant - For the same transformation as the previous
2300/// function, return the identity constant that goes into the select.
2301static Constant *GetSelectFoldableConstant(Instruction *I) {
2302 switch (I->getOpcode()) {
2303 default: assert(0 && "This cannot happen!"); abort();
2304 case Instruction::Add:
2305 case Instruction::Sub:
2306 case Instruction::Or:
2307 case Instruction::Xor:
2308 return Constant::getNullValue(I->getType());
2309 case Instruction::Shl:
2310 case Instruction::Shr:
2311 return Constant::getNullValue(Type::UByteTy);
2312 case Instruction::And:
2313 return ConstantInt::getAllOnesValue(I->getType());
2314 case Instruction::Mul:
2315 return ConstantInt::get(I->getType(), 1);
2316 }
2317}
2318
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002319Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00002320 Value *CondVal = SI.getCondition();
2321 Value *TrueVal = SI.getTrueValue();
2322 Value *FalseVal = SI.getFalseValue();
2323
2324 // select true, X, Y -> X
2325 // select false, X, Y -> Y
2326 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002327 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00002328 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002329 else {
2330 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00002331 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002332 }
Chris Lattner533bc492004-03-30 19:37:13 +00002333
2334 // select C, X, X -> X
2335 if (TrueVal == FalseVal)
2336 return ReplaceInstUsesWith(SI, TrueVal);
2337
Chris Lattner1c631e82004-04-08 04:43:23 +00002338 if (SI.getType() == Type::BoolTy)
2339 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2340 if (C == ConstantBool::True) {
2341 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002342 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002343 } else {
2344 // Change: A = select B, false, C --> A = and !B, C
2345 Value *NotCond =
2346 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2347 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002348 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002349 }
2350 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2351 if (C == ConstantBool::False) {
2352 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002353 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002354 } else {
2355 // Change: A = select B, C, true --> A = or !B, C
2356 Value *NotCond =
2357 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2358 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002359 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002360 }
2361 }
2362
Chris Lattner183b3362004-04-09 19:05:30 +00002363 // Selecting between two integer constants?
2364 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2365 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2366 // select C, 1, 0 -> cast C to int
2367 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2368 return new CastInst(CondVal, SI.getType());
2369 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2370 // select C, 0, 1 -> cast !C to int
2371 Value *NotCond =
2372 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00002373 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00002374 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00002375 }
Chris Lattner35167c32004-06-09 07:59:58 +00002376
2377 // If one of the constants is zero (we know they can't both be) and we
2378 // have a setcc instruction with zero, and we have an 'and' with the
2379 // non-constant value, eliminate this whole mess. This corresponds to
2380 // cases like this: ((X & 27) ? 27 : 0)
2381 if (TrueValC->isNullValue() || FalseValC->isNullValue())
2382 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
2383 if ((IC->getOpcode() == Instruction::SetEQ ||
2384 IC->getOpcode() == Instruction::SetNE) &&
2385 isa<ConstantInt>(IC->getOperand(1)) &&
2386 cast<Constant>(IC->getOperand(1))->isNullValue())
2387 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
2388 if (ICA->getOpcode() == Instruction::And &&
2389 isa<ConstantInt>(ICA->getOperand(1)) &&
2390 (ICA->getOperand(1) == TrueValC ||
2391 ICA->getOperand(1) == FalseValC) &&
2392 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
2393 // Okay, now we know that everything is set up, we just don't
2394 // know whether we have a setne or seteq and whether the true or
2395 // false val is the zero.
2396 bool ShouldNotVal = !TrueValC->isNullValue();
2397 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
2398 Value *V = ICA;
2399 if (ShouldNotVal)
2400 V = InsertNewInstBefore(BinaryOperator::create(
2401 Instruction::Xor, V, ICA->getOperand(1)), SI);
2402 return ReplaceInstUsesWith(SI, V);
2403 }
Chris Lattner533bc492004-03-30 19:37:13 +00002404 }
Chris Lattner623fba12004-04-10 22:21:27 +00002405
2406 // See if we are selecting two values based on a comparison of the two values.
2407 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
2408 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
2409 // Transform (X == Y) ? X : Y -> Y
2410 if (SCI->getOpcode() == Instruction::SetEQ)
2411 return ReplaceInstUsesWith(SI, FalseVal);
2412 // Transform (X != Y) ? X : Y -> X
2413 if (SCI->getOpcode() == Instruction::SetNE)
2414 return ReplaceInstUsesWith(SI, TrueVal);
2415 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2416
2417 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
2418 // Transform (X == Y) ? Y : X -> X
2419 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00002420 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00002421 // Transform (X != Y) ? Y : X -> Y
2422 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00002423 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00002424 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2425 }
2426 }
Chris Lattner1c631e82004-04-08 04:43:23 +00002427
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002428 // See if we can fold the select into one of our operands.
2429 if (SI.getType()->isInteger()) {
2430 // See the comment above GetSelectFoldableOperands for a description of the
2431 // transformation we are doing here.
2432 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
2433 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
2434 !isa<Constant>(FalseVal))
2435 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
2436 unsigned OpToFold = 0;
2437 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
2438 OpToFold = 1;
2439 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
2440 OpToFold = 2;
2441 }
2442
2443 if (OpToFold) {
2444 Constant *C = GetSelectFoldableConstant(TVI);
2445 std::string Name = TVI->getName(); TVI->setName("");
2446 Instruction *NewSel =
2447 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
2448 Name);
2449 InsertNewInstBefore(NewSel, SI);
2450 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
2451 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
2452 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
2453 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
2454 else {
2455 assert(0 && "Unknown instruction!!");
2456 }
2457 }
2458 }
2459
2460 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
2461 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
2462 !isa<Constant>(TrueVal))
2463 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
2464 unsigned OpToFold = 0;
2465 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
2466 OpToFold = 1;
2467 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
2468 OpToFold = 2;
2469 }
2470
2471 if (OpToFold) {
2472 Constant *C = GetSelectFoldableConstant(FVI);
2473 std::string Name = FVI->getName(); FVI->setName("");
2474 Instruction *NewSel =
2475 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
2476 Name);
2477 InsertNewInstBefore(NewSel, SI);
2478 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
2479 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
2480 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
2481 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
2482 else {
2483 assert(0 && "Unknown instruction!!");
2484 }
2485 }
2486 }
2487 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002488 return 0;
2489}
2490
2491
Chris Lattner970c33a2003-06-19 17:00:31 +00002492// CallInst simplification
2493//
2494Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00002495 // Intrinsics cannot occur in an invoke, so handle them here instead of in
2496 // visitCallSite.
2497 if (Function *F = CI.getCalledFunction())
2498 switch (F->getIntrinsicID()) {
2499 case Intrinsic::memmove:
2500 case Intrinsic::memcpy:
2501 case Intrinsic::memset:
2502 // memmove/cpy/set of zero bytes is a noop.
2503 if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
2504 if (NumBytes->isNullValue())
2505 return EraseInstFromFunction(CI);
2506 }
2507 break;
2508 default:
2509 break;
2510 }
2511
Chris Lattneraec3d942003-10-07 22:32:43 +00002512 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00002513}
2514
2515// InvokeInst simplification
2516//
2517Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00002518 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00002519}
2520
Chris Lattneraec3d942003-10-07 22:32:43 +00002521// visitCallSite - Improvements for call and invoke instructions.
2522//
2523Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002524 bool Changed = false;
2525
2526 // If the callee is a constexpr cast of a function, attempt to move the cast
2527 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00002528 if (transformConstExprCastCall(CS)) return 0;
2529
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002530 Value *Callee = CS.getCalledValue();
2531 const PointerType *PTy = cast<PointerType>(Callee->getType());
2532 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2533 if (FTy->isVarArg()) {
2534 // See if we can optimize any arguments passed through the varargs area of
2535 // the call.
2536 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
2537 E = CS.arg_end(); I != E; ++I)
2538 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
2539 // If this cast does not effect the value passed through the varargs
2540 // area, we can eliminate the use of the cast.
2541 Value *Op = CI->getOperand(0);
2542 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
2543 *I = Op;
2544 Changed = true;
2545 }
2546 }
2547 }
Chris Lattneraec3d942003-10-07 22:32:43 +00002548
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002549 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00002550}
2551
Chris Lattner970c33a2003-06-19 17:00:31 +00002552// transformConstExprCastCall - If the callee is a constexpr cast of a function,
2553// attempt to move the cast to the arguments of the call/invoke.
2554//
2555bool InstCombiner::transformConstExprCastCall(CallSite CS) {
2556 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
2557 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00002558 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00002559 return false;
Reid Spencer87436872004-07-18 00:38:32 +00002560 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00002561 Instruction *Caller = CS.getInstruction();
2562
2563 // Okay, this is a cast from a function to a different type. Unless doing so
2564 // would cause a type conversion of one of our arguments, change this call to
2565 // be a direct call with arguments casted to the appropriate types.
2566 //
2567 const FunctionType *FT = Callee->getFunctionType();
2568 const Type *OldRetTy = Caller->getType();
2569
Chris Lattner1f7942f2004-01-14 06:06:08 +00002570 // Check to see if we are changing the return type...
2571 if (OldRetTy != FT->getReturnType()) {
2572 if (Callee->isExternal() &&
2573 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
2574 !Caller->use_empty())
2575 return false; // Cannot transform this return value...
2576
2577 // If the callsite is an invoke instruction, and the return value is used by
2578 // a PHI node in a successor, we cannot change the return type of the call
2579 // because there is no place to put the cast instruction (without breaking
2580 // the critical edge). Bail out in this case.
2581 if (!Caller->use_empty())
2582 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
2583 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
2584 UI != E; ++UI)
2585 if (PHINode *PN = dyn_cast<PHINode>(*UI))
2586 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00002587 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00002588 return false;
2589 }
Chris Lattner970c33a2003-06-19 17:00:31 +00002590
2591 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
2592 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2593
2594 CallSite::arg_iterator AI = CS.arg_begin();
2595 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
2596 const Type *ParamTy = FT->getParamType(i);
2597 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
2598 if (Callee->isExternal() && !isConvertible) return false;
2599 }
2600
2601 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
2602 Callee->isExternal())
2603 return false; // Do not delete arguments unless we have a function body...
2604
2605 // Okay, we decided that this is a safe thing to do: go ahead and start
2606 // inserting cast instructions as necessary...
2607 std::vector<Value*> Args;
2608 Args.reserve(NumActualArgs);
2609
2610 AI = CS.arg_begin();
2611 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
2612 const Type *ParamTy = FT->getParamType(i);
2613 if ((*AI)->getType() == ParamTy) {
2614 Args.push_back(*AI);
2615 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00002616 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
2617 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00002618 }
2619 }
2620
2621 // If the function takes more arguments than the call was taking, add them
2622 // now...
2623 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2624 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2625
2626 // If we are removing arguments to the function, emit an obnoxious warning...
2627 if (FT->getNumParams() < NumActualArgs)
2628 if (!FT->isVarArg()) {
2629 std::cerr << "WARNING: While resolving call to function '"
2630 << Callee->getName() << "' arguments were dropped!\n";
2631 } else {
2632 // Add all of the arguments in their promoted form to the arg list...
2633 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
2634 const Type *PTy = getPromotedType((*AI)->getType());
2635 if (PTy != (*AI)->getType()) {
2636 // Must promote to pass through va_arg area!
2637 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
2638 InsertNewInstBefore(Cast, *Caller);
2639 Args.push_back(Cast);
2640 } else {
2641 Args.push_back(*AI);
2642 }
2643 }
2644 }
2645
2646 if (FT->getReturnType() == Type::VoidTy)
2647 Caller->setName(""); // Void type should not have a name...
2648
2649 Instruction *NC;
2650 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00002651 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00002652 Args, Caller->getName(), Caller);
2653 } else {
2654 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
2655 }
2656
2657 // Insert a cast of the return type as necessary...
2658 Value *NV = NC;
2659 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
2660 if (NV->getType() != Type::VoidTy) {
2661 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00002662
2663 // If this is an invoke instruction, we should insert it after the first
2664 // non-phi, instruction in the normal successor block.
2665 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
2666 BasicBlock::iterator I = II->getNormalDest()->begin();
2667 while (isa<PHINode>(I)) ++I;
2668 InsertNewInstBefore(NC, *I);
2669 } else {
2670 // Otherwise, it's a call, just insert cast right after the call instr
2671 InsertNewInstBefore(NC, *Caller);
2672 }
Chris Lattner51ea1272004-02-28 05:22:00 +00002673 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00002674 } else {
2675 NV = Constant::getNullValue(Caller->getType());
2676 }
2677 }
2678
2679 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
2680 Caller->replaceAllUsesWith(NV);
2681 Caller->getParent()->getInstList().erase(Caller);
2682 removeFromWorkList(Caller);
2683 return true;
2684}
2685
2686
Chris Lattner48a44f72002-05-02 17:06:02 +00002687
Chris Lattnerbbbdd852002-05-06 18:06:38 +00002688// PHINode simplification
2689//
Chris Lattner113f4f42002-06-25 16:13:24 +00002690Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner91daeb52003-12-19 05:58:40 +00002691 if (Value *V = hasConstantValue(&PN))
2692 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00002693
2694 // If the only user of this instruction is a cast instruction, and all of the
2695 // incoming values are constants, change this PHI to merge together the casted
2696 // constants.
2697 if (PN.hasOneUse())
2698 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
2699 if (CI->getType() != PN.getType()) { // noop casts will be folded
2700 bool AllConstant = true;
2701 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2702 if (!isa<Constant>(PN.getIncomingValue(i))) {
2703 AllConstant = false;
2704 break;
2705 }
2706 if (AllConstant) {
2707 // Make a new PHI with all casted values.
2708 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
2709 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2710 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
2711 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
2712 PN.getIncomingBlock(i));
2713 }
2714
2715 // Update the cast instruction.
2716 CI->setOperand(0, New);
2717 WorkList.push_back(CI); // revisit the cast instruction to fold.
2718 WorkList.push_back(New); // Make sure to revisit the new Phi
2719 return &PN; // PN is now dead!
2720 }
2721 }
Chris Lattner91daeb52003-12-19 05:58:40 +00002722 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00002723}
2724
Chris Lattner69193f92004-04-05 01:30:19 +00002725static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
2726 Instruction *InsertPoint,
2727 InstCombiner *IC) {
2728 unsigned PS = IC->getTargetData().getPointerSize();
2729 const Type *VTy = V->getType();
2730 Instruction *Cast;
2731 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
2732 // We must insert a cast to ensure we sign-extend.
2733 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
2734 V->getName()), *InsertPoint);
2735 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
2736 *InsertPoint);
2737}
2738
Chris Lattner48a44f72002-05-02 17:06:02 +00002739
Chris Lattner113f4f42002-06-25 16:13:24 +00002740Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00002741 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00002742 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00002743 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002744 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00002745 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002746
2747 bool HasZeroPointerIndex = false;
2748 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
2749 HasZeroPointerIndex = C->isNullValue();
2750
2751 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00002752 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00002753
Chris Lattner69193f92004-04-05 01:30:19 +00002754 // Eliminate unneeded casts for indices.
2755 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00002756 gep_type_iterator GTI = gep_type_begin(GEP);
2757 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
2758 if (isa<SequentialType>(*GTI)) {
2759 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
2760 Value *Src = CI->getOperand(0);
2761 const Type *SrcTy = Src->getType();
2762 const Type *DestTy = CI->getType();
2763 if (Src->getType()->isInteger()) {
2764 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
2765 // We can always eliminate a cast from ulong or long to the other.
2766 // We can always eliminate a cast from uint to int or the other on
2767 // 32-bit pointer platforms.
2768 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
2769 MadeChange = true;
2770 GEP.setOperand(i, Src);
2771 }
2772 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2773 SrcTy->getPrimitiveSize() == 4) {
2774 // We can always eliminate a cast from int to [u]long. We can
2775 // eliminate a cast from uint to [u]long iff the target is a 32-bit
2776 // pointer target.
2777 if (SrcTy->isSigned() ||
2778 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
2779 MadeChange = true;
2780 GEP.setOperand(i, Src);
2781 }
Chris Lattner69193f92004-04-05 01:30:19 +00002782 }
2783 }
2784 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00002785 // If we are using a wider index than needed for this platform, shrink it
2786 // to what we need. If the incoming value needs a cast instruction,
2787 // insert it. This explicit cast can make subsequent optimizations more
2788 // obvious.
2789 Value *Op = GEP.getOperand(i);
2790 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00002791 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00002792 GEP.setOperand(i, ConstantExpr::getCast(C,
2793 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00002794 MadeChange = true;
2795 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00002796 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
2797 Op->getName()), GEP);
2798 GEP.setOperand(i, Op);
2799 MadeChange = true;
2800 }
Chris Lattner44d0b952004-07-20 01:48:15 +00002801
2802 // If this is a constant idx, make sure to canonicalize it to be a signed
2803 // operand, otherwise CSE and other optimizations are pessimized.
2804 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
2805 GEP.setOperand(i, ConstantExpr::getCast(CUI,
2806 CUI->getType()->getSignedVersion()));
2807 MadeChange = true;
2808 }
Chris Lattner69193f92004-04-05 01:30:19 +00002809 }
2810 if (MadeChange) return &GEP;
2811
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002812 // Combine Indices - If the source pointer to this getelementptr instruction
2813 // is a getelementptr instruction, combine the indices of the two
2814 // getelementptr instructions into a single instruction.
2815 //
Chris Lattner57c67b02004-03-25 22:59:29 +00002816 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00002817 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00002818 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00002819 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00002820 if (CE->getOpcode() == Instruction::GetElementPtr)
2821 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
2822 }
2823
2824 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00002825 // Note that if our source is a gep chain itself that we wait for that
2826 // chain to be resolved before we perform this transformation. This
2827 // avoids us creating a TON of code in some cases.
2828 //
2829 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
2830 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
2831 return 0; // Wait until our source is folded to completion.
2832
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002833 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00002834
2835 // Find out whether the last index in the source GEP is a sequential idx.
2836 bool EndsWithSequential = false;
2837 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
2838 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00002839 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00002840
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002841 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00002842 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00002843 // Replace: gep (gep %P, long B), long A, ...
2844 // With: T = long A+B; gep %P, T, ...
2845 //
Chris Lattner5f667a62004-05-07 22:09:22 +00002846 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00002847 if (SO1 == Constant::getNullValue(SO1->getType())) {
2848 Sum = GO1;
2849 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
2850 Sum = SO1;
2851 } else {
2852 // If they aren't the same type, convert both to an integer of the
2853 // target's pointer size.
2854 if (SO1->getType() != GO1->getType()) {
2855 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
2856 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
2857 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
2858 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
2859 } else {
2860 unsigned PS = TD->getPointerSize();
2861 Instruction *Cast;
2862 if (SO1->getType()->getPrimitiveSize() == PS) {
2863 // Convert GO1 to SO1's type.
2864 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
2865
2866 } else if (GO1->getType()->getPrimitiveSize() == PS) {
2867 // Convert SO1 to GO1's type.
2868 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
2869 } else {
2870 const Type *PT = TD->getIntPtrType();
2871 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
2872 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
2873 }
2874 }
2875 }
Chris Lattner5f667a62004-05-07 22:09:22 +00002876 if (isa<Constant>(SO1) && isa<Constant>(GO1))
2877 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
2878 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002879 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
2880 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00002881 }
Chris Lattner69193f92004-04-05 01:30:19 +00002882 }
Chris Lattner5f667a62004-05-07 22:09:22 +00002883
2884 // Recycle the GEP we already have if possible.
2885 if (SrcGEPOperands.size() == 2) {
2886 GEP.setOperand(0, SrcGEPOperands[0]);
2887 GEP.setOperand(1, Sum);
2888 return &GEP;
2889 } else {
2890 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2891 SrcGEPOperands.end()-1);
2892 Indices.push_back(Sum);
2893 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
2894 }
Chris Lattner69193f92004-04-05 01:30:19 +00002895 } else if (isa<Constant>(*GEP.idx_begin()) &&
2896 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00002897 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002898 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00002899 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2900 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002901 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
2902 }
2903
2904 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00002905 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002906
Chris Lattner5f667a62004-05-07 22:09:22 +00002907 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002908 // GEP of global variable. If all of the indices for this GEP are
2909 // constants, we can promote this to a constexpr instead of an instruction.
2910
2911 // Scan for nonconstants...
2912 std::vector<Constant*> Indices;
2913 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
2914 for (; I != E && isa<Constant>(*I); ++I)
2915 Indices.push_back(cast<Constant>(*I));
2916
2917 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00002918 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002919
2920 // Replace all uses of the GEP with the new constexpr...
2921 return ReplaceInstUsesWith(GEP, CE);
2922 }
Chris Lattner5f667a62004-05-07 22:09:22 +00002923 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002924 if (CE->getOpcode() == Instruction::Cast) {
2925 if (HasZeroPointerIndex) {
2926 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
2927 // into : GEP [10 x ubyte]* X, long 0, ...
2928 //
2929 // This occurs when the program declares an array extern like "int X[];"
2930 //
2931 Constant *X = CE->getOperand(0);
2932 const PointerType *CPTy = cast<PointerType>(CE->getType());
2933 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
2934 if (const ArrayType *XATy =
2935 dyn_cast<ArrayType>(XTy->getElementType()))
2936 if (const ArrayType *CATy =
2937 dyn_cast<ArrayType>(CPTy->getElementType()))
2938 if (CATy->getElementType() == XATy->getElementType()) {
2939 // At this point, we know that the cast source type is a pointer
2940 // to an array of the same type as the destination pointer
2941 // array. Because the array type is never stepped over (there
2942 // is a leading zero) we can fold the cast into this GEP.
2943 GEP.setOperand(0, X);
2944 return &GEP;
2945 }
2946 }
2947 }
Chris Lattnerca081252001-12-14 16:52:21 +00002948 }
2949
Chris Lattnerca081252001-12-14 16:52:21 +00002950 return 0;
2951}
2952
Chris Lattner1085bdf2002-11-04 16:18:53 +00002953Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
2954 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
2955 if (AI.isArrayAllocation()) // Check C != 1
2956 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
2957 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00002958 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00002959
2960 // Create and insert the replacement instruction...
2961 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00002962 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00002963 else {
2964 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00002965 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00002966 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00002967
2968 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00002969
2970 // Scan to the end of the allocation instructions, to skip over a block of
2971 // allocas if possible...
2972 //
2973 BasicBlock::iterator It = New;
2974 while (isa<AllocationInst>(*It)) ++It;
2975
2976 // Now that I is pointing to the first non-allocation-inst in the block,
2977 // insert our getelementptr instruction...
2978 //
Chris Lattner69193f92004-04-05 01:30:19 +00002979 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00002980 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
2981
2982 // Now make everything use the getelementptr instead of the original
2983 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00002984 return ReplaceInstUsesWith(AI, V);
Chris Lattner1085bdf2002-11-04 16:18:53 +00002985 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00002986
2987 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
2988 // Note that we only do this for alloca's, because malloc should allocate and
2989 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00002990 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
2991 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00002992 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
2993
Chris Lattner1085bdf2002-11-04 16:18:53 +00002994 return 0;
2995}
2996
Chris Lattner8427bff2003-12-07 01:24:23 +00002997Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
2998 Value *Op = FI.getOperand(0);
2999
3000 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3001 if (CastInst *CI = dyn_cast<CastInst>(Op))
3002 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3003 FI.setOperand(0, CI->getOperand(0));
3004 return &FI;
3005 }
3006
Chris Lattnerf3a36602004-02-28 04:57:37 +00003007 // If we have 'free null' delete the instruction. This can happen in stl code
3008 // when lots of inlining happens.
Chris Lattner51ea1272004-02-28 05:22:00 +00003009 if (isa<ConstantPointerNull>(Op))
3010 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00003011
Chris Lattner8427bff2003-12-07 01:24:23 +00003012 return 0;
3013}
3014
3015
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003016/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3017/// constantexpr, return the constant value being addressed by the constant
3018/// expression, or null if something is funny.
3019///
3020static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00003021 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003022 return 0; // Do not allow stepping over the value!
3023
3024 // Loop over all of the operands, tracking down which value we are
3025 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00003026 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3027 for (++I; I != E; ++I)
3028 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3029 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3030 assert(CU->getValue() < STy->getNumElements() &&
3031 "Struct index out of range!");
3032 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003033 C = CS->getOperand(CU->getValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003034 } else if (isa<ConstantAggregateZero>(C)) {
3035 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
3036 } else {
3037 return 0;
3038 }
3039 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3040 const ArrayType *ATy = cast<ArrayType>(*I);
3041 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3042 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003043 C = CA->getOperand(CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003044 else if (isa<ConstantAggregateZero>(C))
3045 C = Constant::getNullValue(ATy->getElementType());
3046 else
3047 return 0;
3048 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003049 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00003050 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003051 return C;
3052}
3053
Chris Lattner35e24772004-07-13 01:49:43 +00003054static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3055 User *CI = cast<User>(LI.getOperand(0));
3056
3057 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3058 if (const PointerType *SrcTy =
3059 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3060 const Type *SrcPTy = SrcTy->getElementType();
3061 if (SrcPTy->isSized() && DestPTy->isSized() &&
3062 IC.getTargetData().getTypeSize(SrcPTy) ==
3063 IC.getTargetData().getTypeSize(DestPTy) &&
3064 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3065 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3066 // Okay, we are casting from one integer or pointer type to another of
3067 // the same size. Instead of casting the pointer before the load, cast
3068 // the result of the loaded value.
3069 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003070 CI->getName(),
3071 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00003072 // Now cast the result of the load.
3073 return new CastInst(NewLoad, LI.getType());
3074 }
3075 }
3076 return 0;
3077}
3078
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003079/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00003080/// from this value cannot trap. If it is not obviously safe to load from the
3081/// specified pointer, we do a quick local scan of the basic block containing
3082/// ScanFrom, to determine if the address is already accessed.
3083static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3084 // If it is an alloca or global variable, it is always safe to load from.
3085 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3086
3087 // Otherwise, be a little bit agressive by scanning the local block where we
3088 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003089 // from/to. If so, the previous load or store would have already trapped,
3090 // so there is no harm doing an extra load (also, CSE will later eliminate
3091 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00003092 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3093
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003094 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00003095 --BBI;
3096
3097 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3098 if (LI->getOperand(0) == V) return true;
3099 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3100 if (SI->getOperand(1) == V) return true;
3101
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003102 }
Chris Lattnere6f13092004-09-19 19:18:10 +00003103 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003104}
3105
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003106Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3107 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00003108
Chris Lattner6679e462004-04-14 03:28:36 +00003109 if (Constant *C = dyn_cast<Constant>(Op))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003110 if (C->isNullValue() && !LI.isVolatile()) // load null -> 0
Chris Lattner6679e462004-04-14 03:28:36 +00003111 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003112
3113 // Instcombine load (constant global) into the value loaded...
3114 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00003115 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003116 return ReplaceInstUsesWith(LI, GV->getInitializer());
3117
3118 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
3119 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
Chris Lattner35e24772004-07-13 01:49:43 +00003120 if (CE->getOpcode() == Instruction::GetElementPtr) {
Reid Spencer87436872004-07-18 00:38:32 +00003121 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3122 if (GV->isConstant() && !GV->isExternal())
3123 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3124 return ReplaceInstUsesWith(LI, V);
Chris Lattner35e24772004-07-13 01:49:43 +00003125 } else if (CE->getOpcode() == Instruction::Cast) {
3126 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3127 return Res;
3128 }
Chris Lattnere228ee52004-04-08 20:39:49 +00003129
3130 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00003131 if (CastInst *CI = dyn_cast<CastInst>(Op))
3132 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3133 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00003134
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003135 if (!LI.isVolatile() && Op->hasOneUse()) {
3136 // Change select and PHI nodes to select values instead of addresses: this
3137 // helps alias analysis out a lot, allows many others simplifications, and
3138 // exposes redundancy in the code.
3139 //
3140 // Note that we cannot do the transformation unless we know that the
3141 // introduced loads cannot trap! Something like this is valid as long as
3142 // the condition is always false: load (select bool %C, int* null, int* %G),
3143 // but it would not be valid if we transformed it to load from null
3144 // unconditionally.
3145 //
3146 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3147 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00003148 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3149 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003150 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00003151 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003152 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00003153 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003154 return new SelectInst(SI->getCondition(), V1, V2);
3155 }
3156
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00003157 // load (select (cond, null, P)) -> load P
3158 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3159 if (C->isNullValue()) {
3160 LI.setOperand(0, SI->getOperand(2));
3161 return &LI;
3162 }
3163
3164 // load (select (cond, P, null)) -> load P
3165 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3166 if (C->isNullValue()) {
3167 LI.setOperand(0, SI->getOperand(1));
3168 return &LI;
3169 }
3170
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003171 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3172 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00003173 bool Safe = PN->getParent() == LI.getParent();
3174
3175 // Scan all of the instructions between the PHI and the load to make
3176 // sure there are no instructions that might possibly alter the value
3177 // loaded from the PHI.
3178 if (Safe) {
3179 BasicBlock::iterator I = &LI;
3180 for (--I; !isa<PHINode>(I); --I)
3181 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3182 Safe = false;
3183 break;
3184 }
3185 }
3186
3187 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00003188 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00003189 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003190 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00003191
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003192 if (Safe) {
3193 // Create the PHI.
3194 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3195 InsertNewInstBefore(NewPN, *PN);
3196 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3197
3198 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3199 BasicBlock *BB = PN->getIncomingBlock(i);
3200 Value *&TheLoad = LoadMap[BB];
3201 if (TheLoad == 0) {
3202 Value *InVal = PN->getIncomingValue(i);
3203 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3204 InVal->getName()+".val"),
3205 *BB->getTerminator());
3206 }
3207 NewPN->addIncoming(TheLoad, BB);
3208 }
3209 return ReplaceInstUsesWith(LI, NewPN);
3210 }
3211 }
3212 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003213 return 0;
3214}
3215
3216
Chris Lattner9eef8a72003-06-04 04:46:00 +00003217Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3218 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00003219 Value *X;
3220 BasicBlock *TrueDest;
3221 BasicBlock *FalseDest;
3222 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3223 !isa<Constant>(X)) {
3224 // Swap Destinations and condition...
3225 BI.setCondition(X);
3226 BI.setSuccessor(0, FalseDest);
3227 BI.setSuccessor(1, TrueDest);
3228 return &BI;
3229 }
3230
3231 // Cannonicalize setne -> seteq
3232 Instruction::BinaryOps Op; Value *Y;
3233 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3234 TrueDest, FalseDest)))
3235 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3236 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3237 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3238 std::string Name = I->getName(); I->setName("");
3239 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3240 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00003241 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00003242 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00003243 BI.setSuccessor(0, FalseDest);
3244 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003245 removeFromWorkList(I);
3246 I->getParent()->getInstList().erase(I);
3247 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00003248 return &BI;
3249 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00003250
Chris Lattner9eef8a72003-06-04 04:46:00 +00003251 return 0;
3252}
Chris Lattner1085bdf2002-11-04 16:18:53 +00003253
Chris Lattner4c9c20a2004-07-03 00:26:11 +00003254Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3255 Value *Cond = SI.getCondition();
3256 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3257 if (I->getOpcode() == Instruction::Add)
3258 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3259 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3260 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
3261 SI.setOperand(i, ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
3262 AddRHS));
3263 SI.setOperand(0, I->getOperand(0));
3264 WorkList.push_back(I);
3265 return &SI;
3266 }
3267 }
3268 return 0;
3269}
3270
Chris Lattnerca081252001-12-14 16:52:21 +00003271
Chris Lattner99f48c62002-09-02 04:59:56 +00003272void InstCombiner::removeFromWorkList(Instruction *I) {
3273 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3274 WorkList.end());
3275}
3276
Chris Lattner113f4f42002-06-25 16:13:24 +00003277bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00003278 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003279 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00003280
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003281 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3282 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00003283
Chris Lattnerca081252001-12-14 16:52:21 +00003284
3285 while (!WorkList.empty()) {
3286 Instruction *I = WorkList.back(); // Get an instruction from the worklist
3287 WorkList.pop_back();
3288
Misha Brukman632df282002-10-29 23:06:16 +00003289 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00003290 // Check to see if we can DIE the instruction...
3291 if (isInstructionTriviallyDead(I)) {
3292 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003293 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00003294 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00003295 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003296
3297 I->getParent()->getInstList().erase(I);
3298 removeFromWorkList(I);
3299 continue;
3300 }
Chris Lattner99f48c62002-09-02 04:59:56 +00003301
Misha Brukman632df282002-10-29 23:06:16 +00003302 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00003303 if (Constant *C = ConstantFoldInstruction(I)) {
3304 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00003305 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00003306 ReplaceInstUsesWith(*I, C);
3307
Chris Lattner99f48c62002-09-02 04:59:56 +00003308 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003309 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00003310 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003311 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00003312 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003313
Chris Lattnerca081252001-12-14 16:52:21 +00003314 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003315 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00003316 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00003317 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00003318 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003319 DEBUG(std::cerr << "IC: Old = " << *I
3320 << " New = " << *Result);
3321
Chris Lattner396dbfe2004-06-09 05:08:07 +00003322 // Everything uses the new instruction now.
3323 I->replaceAllUsesWith(Result);
3324
3325 // Push the new instruction and any users onto the worklist.
3326 WorkList.push_back(Result);
3327 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003328
3329 // Move the name to the new instruction first...
3330 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00003331 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003332
3333 // Insert the new instruction into the basic block...
3334 BasicBlock *InstParent = I->getParent();
3335 InstParent->getInstList().insert(I, Result);
3336
Chris Lattner63d75af2004-05-01 23:27:23 +00003337 // Make sure that we reprocess all operands now that we reduced their
3338 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003339 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3340 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3341 WorkList.push_back(OpI);
3342
Chris Lattner396dbfe2004-06-09 05:08:07 +00003343 // Instructions can end up on the worklist more than once. Make sure
3344 // we do not process an instruction that has been deleted.
3345 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003346
3347 // Erase the old instruction.
3348 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003349 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003350 DEBUG(std::cerr << "IC: MOD = " << *I);
3351
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003352 // If the instruction was modified, it's possible that it is now dead.
3353 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00003354 if (isInstructionTriviallyDead(I)) {
3355 // Make sure we process all operands now that we are reducing their
3356 // use counts.
3357 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3358 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3359 WorkList.push_back(OpI);
3360
3361 // Instructions may end up in the worklist more than once. Erase all
3362 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00003363 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00003364 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00003365 } else {
3366 WorkList.push_back(Result);
3367 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003368 }
Chris Lattner053c0932002-05-14 15:24:07 +00003369 }
Chris Lattner260ab202002-04-18 17:39:14 +00003370 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00003371 }
3372 }
3373
Chris Lattner260ab202002-04-18 17:39:14 +00003374 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00003375}
3376
Brian Gaeke38b79e82004-07-27 17:43:21 +00003377FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00003378 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00003379}
Brian Gaeke960707c2003-11-11 22:41:34 +00003380