blob: 807653b56d12637609b715273773e846fe9e42f3 [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 Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
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 Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner60a65912002-02-12 21:07:25 +000048#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000049#include "llvm/Support/InstVisitor.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000051#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000052#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000053#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000054using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000055using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000056
Chris Lattner260ab202002-04-18 17:39:14 +000057namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000058 Statistic<> NumCombined ("instcombine", "Number of insts combined");
59 Statistic<> NumConstProp("instcombine", "Number of constant folds");
60 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000061 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000062
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);
Reid Spencer279fa252004-11-28 21:31:15 +0000116 Instruction *visitSetCondInstWithCastAndConstant(BinaryOperator&I,
117 CastInst*LHSI,
118 ConstantInt* CI);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000119 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000120 Instruction *visitCastInst(CastInst &CI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000121 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000122 Instruction *visitCallInst(CallInst &CI);
123 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000124 Instruction *visitPHINode(PHINode &PN);
125 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000126 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000127 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000128 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000129 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000130 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000131
132 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000133 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000134
Chris Lattner970c33a2003-06-19 17:00:31 +0000135 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000136 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000137 bool transformConstExprCastCall(CallSite CS);
138
Chris Lattner69193f92004-04-05 01:30:19 +0000139 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000140 // InsertNewInstBefore - insert an instruction New before instruction Old
141 // in the program. Add the new instruction to the worklist.
142 //
Chris Lattner623826c2004-09-28 21:48:02 +0000143 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000144 assert(New && New->getParent() == 0 &&
145 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000146 BasicBlock *BB = Old.getParent();
147 BB->getInstList().insert(&Old, New); // Insert inst
148 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000149 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000150 }
151
Chris Lattner7e794272004-09-24 15:21:34 +0000152 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
153 /// This also adds the cast to the worklist. Finally, this returns the
154 /// cast.
155 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
156 if (V->getType() == Ty) return V;
157
158 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
159 WorkList.push_back(C);
160 return C;
161 }
162
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000163 // ReplaceInstUsesWith - This method is to be used when an instruction is
164 // found to be dead, replacable with another preexisting expression. Here
165 // we add all uses of I to the worklist, replace all uses of I with the new
166 // value, then return I, so that the inst combiner will know that I was
167 // modified.
168 //
169 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000170 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000171 if (&I != V) {
172 I.replaceAllUsesWith(V);
173 return &I;
174 } else {
175 // If we are replacing the instruction with itself, this must be in a
176 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000177 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000178 return &I;
179 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000180 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000181
182 // EraseInstFromFunction - When dealing with an instruction that has side
183 // effects or produces a void value, we can't rely on DCE to delete the
184 // instruction. Instead, visit methods should return the value returned by
185 // this function.
186 Instruction *EraseInstFromFunction(Instruction &I) {
187 assert(I.use_empty() && "Cannot erase instruction that is used!");
188 AddUsesToWorkList(I);
189 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000190 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000191 return 0; // Don't do anything with FI
192 }
193
194
Chris Lattner3ac7c262003-08-13 20:16:26 +0000195 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000196 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
197 /// InsertBefore instruction. This is specialized a bit to avoid inserting
198 /// casts that are known to not do anything...
199 ///
200 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
201 Instruction *InsertBefore);
202
Chris Lattner7fb29e12003-03-11 00:12:48 +0000203 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000204 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000205 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000206
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000207
208 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
209 // PHI node as operand #0, see if we can fold the instruction into the PHI
210 // (which is only possible if all operands to the PHI are constants).
211 Instruction *FoldOpIntoPhi(Instruction &I);
212
Chris Lattner7515cab2004-11-14 19:13:23 +0000213 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
214 // operator and they all are only used by the PHI, PHI together their
215 // inputs, and do the operation once, to the result of the PHI.
216 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
217
Chris Lattnerba1cb382003-09-19 17:17:26 +0000218 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
219 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000220
221 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
222 bool Inside, Instruction &IB);
Chris Lattner260ab202002-04-18 17:39:14 +0000223 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000224
Chris Lattnerc8b70922002-07-26 21:12:46 +0000225 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000226}
227
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000228// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000229// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000230static unsigned getComplexity(Value *V) {
231 if (isa<Instruction>(V)) {
232 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000233 return 3;
234 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000235 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000236 if (isa<Argument>(V)) return 3;
237 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000238}
Chris Lattner260ab202002-04-18 17:39:14 +0000239
Chris Lattner7fb29e12003-03-11 00:12:48 +0000240// isOnlyUse - Return true if this instruction will be deleted if we stop using
241// it.
242static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000243 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000244}
245
Chris Lattnere79e8542004-02-23 06:38:22 +0000246// getPromotedType - Return the specified type promoted as it would be to pass
247// though a va_arg area...
248static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000249 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000250 case Type::SByteTyID:
251 case Type::ShortTyID: return Type::IntTy;
252 case Type::UByteTyID:
253 case Type::UShortTyID: return Type::UIntTy;
254 case Type::FloatTyID: return Type::DoubleTy;
255 default: return Ty;
256 }
257}
258
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000259// SimplifyCommutative - This performs a few simplifications for commutative
260// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000261//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000262// 1. Order operands such that they are listed from right (least complex) to
263// left (most complex). This puts constants before unary operators before
264// binary operators.
265//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000266// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
267// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000268//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000269bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000270 bool Changed = false;
271 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
272 Changed = !I.swapOperands();
273
274 if (!I.isAssociative()) return Changed;
275 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000276 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
277 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
278 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000279 Constant *Folded = ConstantExpr::get(I.getOpcode(),
280 cast<Constant>(I.getOperand(1)),
281 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000282 I.setOperand(0, Op->getOperand(0));
283 I.setOperand(1, Folded);
284 return true;
285 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
286 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
287 isOnlyUse(Op) && isOnlyUse(Op1)) {
288 Constant *C1 = cast<Constant>(Op->getOperand(1));
289 Constant *C2 = cast<Constant>(Op1->getOperand(1));
290
291 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000292 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000293 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
294 Op1->getOperand(0),
295 Op1->getName(), &I);
296 WorkList.push_back(New);
297 I.setOperand(0, New);
298 I.setOperand(1, Folded);
299 return true;
300 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000301 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000302 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000303}
Chris Lattnerca081252001-12-14 16:52:21 +0000304
Chris Lattnerbb74e222003-03-10 23:06:50 +0000305// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
306// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000307//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000308static inline Value *dyn_castNegVal(Value *V) {
309 if (BinaryOperator::isNeg(V))
310 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
311
Chris Lattner9244df62003-04-30 22:19:10 +0000312 // Constants can be considered to be negated values if they can be folded...
313 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner8f30caf2004-12-08 22:20:34 +0000314 if (!isa<UndefValue>(C))
315 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000316 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000317}
318
Chris Lattnerbb74e222003-03-10 23:06:50 +0000319static inline Value *dyn_castNotVal(Value *V) {
320 if (BinaryOperator::isNot(V))
321 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
322
323 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000324 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000325 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000326 return 0;
327}
328
Chris Lattner7fb29e12003-03-11 00:12:48 +0000329// dyn_castFoldableMul - If this value is a multiply that can be folded into
330// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000331// non-constant operand of the multiply, and set CST to point to the multiplier.
332// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000333//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000334static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000335 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000336 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000337 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000338 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000339 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000340 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000341 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000342 // The multiplier is really 1 << CST.
343 Constant *One = ConstantInt::get(V->getType(), 1);
344 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
345 return I->getOperand(0);
346 }
347 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000348 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000349}
Chris Lattner31ae8632002-08-14 17:51:49 +0000350
Chris Lattner3082c5a2003-02-18 19:28:33 +0000351// Log2 - Calculate the log base 2 for the specified value if it is exactly a
352// power of 2.
353static unsigned Log2(uint64_t Val) {
354 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
355 unsigned Count = 0;
356 while (Val != 1) {
357 if (Val & 1) return 0; // Multiple bits set?
358 Val >>= 1;
359 ++Count;
360 }
361 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000362}
363
Chris Lattner623826c2004-09-28 21:48:02 +0000364// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000365static ConstantInt *AddOne(ConstantInt *C) {
366 return cast<ConstantInt>(ConstantExpr::getAdd(C,
367 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000368}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000369static ConstantInt *SubOne(ConstantInt *C) {
370 return cast<ConstantInt>(ConstantExpr::getSub(C,
371 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000372}
373
374// isTrueWhenEqual - Return true if the specified setcondinst instruction is
375// true when both operands are equal...
376//
377static bool isTrueWhenEqual(Instruction &I) {
378 return I.getOpcode() == Instruction::SetEQ ||
379 I.getOpcode() == Instruction::SetGE ||
380 I.getOpcode() == Instruction::SetLE;
381}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000382
383/// AssociativeOpt - Perform an optimization on an associative operator. This
384/// function is designed to check a chain of associative operators for a
385/// potential to apply a certain optimization. Since the optimization may be
386/// applicable if the expression was reassociated, this checks the chain, then
387/// reassociates the expression as necessary to expose the optimization
388/// opportunity. This makes use of a special Functor, which must define
389/// 'shouldApply' and 'apply' methods.
390///
391template<typename Functor>
392Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
393 unsigned Opcode = Root.getOpcode();
394 Value *LHS = Root.getOperand(0);
395
396 // Quick check, see if the immediate LHS matches...
397 if (F.shouldApply(LHS))
398 return F.apply(Root);
399
400 // Otherwise, if the LHS is not of the same opcode as the root, return.
401 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000402 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000403 // Should we apply this transform to the RHS?
404 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
405
406 // If not to the RHS, check to see if we should apply to the LHS...
407 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
408 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
409 ShouldApply = true;
410 }
411
412 // If the functor wants to apply the optimization to the RHS of LHSI,
413 // reassociate the expression from ((? op A) op B) to (? op (A op B))
414 if (ShouldApply) {
415 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000416
417 // Now all of the instructions are in the current basic block, go ahead
418 // and perform the reassociation.
419 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
420
421 // First move the selected RHS to the LHS of the root...
422 Root.setOperand(0, LHSI->getOperand(1));
423
424 // Make what used to be the LHS of the root be the user of the root...
425 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000426 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000427 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
428 return 0;
429 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000430 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000431 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000432 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
433 BasicBlock::iterator ARI = &Root; ++ARI;
434 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
435 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000436
437 // Now propagate the ExtraOperand down the chain of instructions until we
438 // get to LHSI.
439 while (TmpLHSI != LHSI) {
440 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000441 // Move the instruction to immediately before the chain we are
442 // constructing to avoid breaking dominance properties.
443 NextLHSI->getParent()->getInstList().remove(NextLHSI);
444 BB->getInstList().insert(ARI, NextLHSI);
445 ARI = NextLHSI;
446
Chris Lattnerb8b97502003-08-13 19:01:45 +0000447 Value *NextOp = NextLHSI->getOperand(1);
448 NextLHSI->setOperand(1, ExtraOperand);
449 TmpLHSI = NextLHSI;
450 ExtraOperand = NextOp;
451 }
452
453 // Now that the instructions are reassociated, have the functor perform
454 // the transformation...
455 return F.apply(Root);
456 }
457
458 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
459 }
460 return 0;
461}
462
463
464// AddRHS - Implements: X + X --> X << 1
465struct AddRHS {
466 Value *RHS;
467 AddRHS(Value *rhs) : RHS(rhs) {}
468 bool shouldApply(Value *LHS) const { return LHS == RHS; }
469 Instruction *apply(BinaryOperator &Add) const {
470 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
471 ConstantInt::get(Type::UByteTy, 1));
472 }
473};
474
475// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
476// iff C1&C2 == 0
477struct AddMaskingAnd {
478 Constant *C2;
479 AddMaskingAnd(Constant *c) : C2(c) {}
480 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000481 ConstantInt *C1;
482 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
483 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000484 }
485 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000486 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000487 }
488};
489
Chris Lattner183b3362004-04-09 19:05:30 +0000490static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
491 InstCombiner *IC) {
492 // Figure out if the constant is the left or the right argument.
493 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
494 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000495
Chris Lattner183b3362004-04-09 19:05:30 +0000496 if (Constant *SOC = dyn_cast<Constant>(SO)) {
497 if (ConstIsRHS)
498 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
499 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
500 }
501
502 Value *Op0 = SO, *Op1 = ConstOperand;
503 if (!ConstIsRHS)
504 std::swap(Op0, Op1);
505 Instruction *New;
506 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
507 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
508 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
509 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattnerf9d96652004-04-10 19:15:56 +0000510 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000511 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000512 abort();
513 }
Chris Lattner183b3362004-04-09 19:05:30 +0000514 return IC->InsertNewInstBefore(New, BI);
515}
516
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000517
518/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
519/// node as operand #0, see if we can fold the instruction into the PHI (which
520/// is only possible if all operands to the PHI are constants).
521Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
522 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000523 unsigned NumPHIValues = PN->getNumIncomingValues();
524 if (!PN->hasOneUse() || NumPHIValues == 0 ||
525 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000526
527 // Check to see if all of the operands of the PHI are constants. If not, we
528 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000529 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000530 if (!isa<Constant>(PN->getIncomingValue(i)))
531 return 0;
532
533 // Okay, we can do the transformation: create the new PHI node.
534 PHINode *NewPN = new PHINode(I.getType(), I.getName());
535 I.setName("");
536 NewPN->op_reserve(PN->getNumOperands());
537 InsertNewInstBefore(NewPN, *PN);
538
539 // Next, add all of the operands to the PHI.
540 if (I.getNumOperands() == 2) {
541 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000542 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000543 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
544 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
545 PN->getIncomingBlock(i));
546 }
547 } else {
548 assert(isa<CastInst>(I) && "Unary op should be a cast!");
549 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000550 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000551 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
552 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
553 PN->getIncomingBlock(i));
554 }
555 }
556 return ReplaceInstUsesWith(I, NewPN);
557}
558
Chris Lattner183b3362004-04-09 19:05:30 +0000559// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
560// constant as the other operand, try to fold the binary operator into the
561// select arguments.
562static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
563 InstCombiner *IC) {
564 // Don't modify shared select instructions
565 if (!SI->hasOneUse()) return 0;
566 Value *TV = SI->getOperand(1);
567 Value *FV = SI->getOperand(2);
568
569 if (isa<Constant>(TV) || isa<Constant>(FV)) {
570 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
571 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
572
573 return new SelectInst(SI->getCondition(), SelectTrueVal,
574 SelectFalseVal);
575 }
576 return 0;
577}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000578
Chris Lattner113f4f42002-06-25 16:13:24 +0000579Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000580 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000581 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000582
Chris Lattnercf4a9962004-04-10 22:01:55 +0000583 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000584 // X + undef -> undef
585 if (isa<UndefValue>(RHS))
586 return ReplaceInstUsesWith(I, RHS);
587
Chris Lattnercf4a9962004-04-10 22:01:55 +0000588 // X + 0 --> X
589 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
590 RHSC->isNullValue())
591 return ReplaceInstUsesWith(I, LHS);
592
593 // X + (signbit) --> X ^ signbit
594 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
595 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
596 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattner33eb9092004-11-05 04:45:43 +0000597 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000598 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000599 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000600
601 if (isa<PHINode>(LHS))
602 if (Instruction *NV = FoldOpIntoPhi(I))
603 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000604 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000605
Chris Lattnerb8b97502003-08-13 19:01:45 +0000606 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000607 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000608 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000609 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000610
Chris Lattner147e9752002-05-08 22:46:53 +0000611 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000612 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000613 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000614
615 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000616 if (!isa<Constant>(RHS))
617 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000618 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000619
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000620 ConstantInt *C2;
621 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
622 if (X == RHS) // X*C + X --> X * (C+1)
623 return BinaryOperator::createMul(RHS, AddOne(C2));
624
625 // X*C1 + X*C2 --> X * (C1+C2)
626 ConstantInt *C1;
627 if (X == dyn_castFoldableMul(RHS, C1))
628 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000629 }
630
631 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000632 if (dyn_castFoldableMul(RHS, C2) == LHS)
633 return BinaryOperator::createMul(LHS, AddOne(C2));
634
Chris Lattner57c8d992003-02-18 19:57:07 +0000635
Chris Lattnerb8b97502003-08-13 19:01:45 +0000636 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000637 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000638 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000639
Chris Lattnerb9cde762003-10-02 15:11:26 +0000640 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000641 Value *X;
642 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
643 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
644 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000645 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000646
Chris Lattnerbff91d92004-10-08 05:07:56 +0000647 // (X & FF00) + xx00 -> (X+xx00) & FF00
648 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
649 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
650 if (Anded == CRHS) {
651 // See if all bits from the first bit set in the Add RHS up are included
652 // in the mask. First, get the rightmost bit.
653 uint64_t AddRHSV = CRHS->getRawValue();
654
655 // Form a mask of all bits from the lowest bit added through the top.
656 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
657 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
658
659 // See if the and mask includes all of these bits.
660 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
661
662 if (AddRHSHighBits == AddRHSHighBitsAnd) {
663 // Okay, the xform is safe. Insert the new add pronto.
664 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
665 LHS->getName()), I);
666 return BinaryOperator::createAnd(NewAdd, C2);
667 }
668 }
669 }
670
671
Chris Lattnerd4252a72004-07-30 07:50:03 +0000672 // Try to fold constant add into select arguments.
673 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
674 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
675 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000676 }
677
Chris Lattner113f4f42002-06-25 16:13:24 +0000678 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000679}
680
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000681// isSignBit - Return true if the value represented by the constant only has the
682// highest order bit set.
683static bool isSignBit(ConstantInt *CI) {
684 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
685 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
686}
687
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000688static unsigned getTypeSizeInBits(const Type *Ty) {
689 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
690}
691
Chris Lattner022167f2004-03-13 00:11:49 +0000692/// RemoveNoopCast - Strip off nonconverting casts from the value.
693///
694static Value *RemoveNoopCast(Value *V) {
695 if (CastInst *CI = dyn_cast<CastInst>(V)) {
696 const Type *CTy = CI->getType();
697 const Type *OpTy = CI->getOperand(0)->getType();
698 if (CTy->isInteger() && OpTy->isInteger()) {
699 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
700 return RemoveNoopCast(CI->getOperand(0));
701 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
702 return RemoveNoopCast(CI->getOperand(0));
703 }
704 return V;
705}
706
Chris Lattner113f4f42002-06-25 16:13:24 +0000707Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000708 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000709
Chris Lattnere6794492002-08-12 21:17:25 +0000710 if (Op0 == Op1) // sub X, X -> 0
711 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000712
Chris Lattnere6794492002-08-12 21:17:25 +0000713 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000714 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000715 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000716
Chris Lattner81a7a232004-10-16 18:11:37 +0000717 if (isa<UndefValue>(Op0))
718 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
719 if (isa<UndefValue>(Op1))
720 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
721
Chris Lattner8f2f5982003-11-05 01:06:05 +0000722 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
723 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000724 if (C->isAllOnesValue())
725 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000726
Chris Lattner8f2f5982003-11-05 01:06:05 +0000727 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000728 Value *X;
729 if (match(Op1, m_Not(m_Value(X))))
730 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000731 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000732 // -((uint)X >> 31) -> ((int)X >> 31)
733 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000734 if (C->isNullValue()) {
735 Value *NoopCastedRHS = RemoveNoopCast(Op1);
736 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000737 if (SI->getOpcode() == Instruction::Shr)
738 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
739 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000740 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000741 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000742 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000743 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000744 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000745 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000746 // Ok, the transformation is safe. Insert a cast of the incoming
747 // value, then the new shift, then the new cast.
748 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
749 SI->getOperand(0)->getName());
750 Value *InV = InsertNewInstBefore(FirstCast, I);
751 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
752 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000753 if (NewShift->getType() == I.getType())
754 return NewShift;
755 else {
756 InV = InsertNewInstBefore(NewShift, I);
757 return new CastInst(NewShift, I.getType());
758 }
Chris Lattner92295c52004-03-12 23:53:13 +0000759 }
760 }
Chris Lattner022167f2004-03-13 00:11:49 +0000761 }
Chris Lattner183b3362004-04-09 19:05:30 +0000762
763 // Try to fold constant sub into select arguments.
764 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
765 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
766 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000767
768 if (isa<PHINode>(Op0))
769 if (Instruction *NV = FoldOpIntoPhi(I))
770 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000771 }
772
Chris Lattner3082c5a2003-02-18 19:28:33 +0000773 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000774 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000775 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
776 // is not used by anyone else...
777 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000778 if (Op1I->getOpcode() == Instruction::Sub &&
779 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000780 // Swap the two operands of the subexpr...
781 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
782 Op1I->setOperand(0, IIOp1);
783 Op1I->setOperand(1, IIOp0);
784
785 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000786 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000787 }
788
789 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
790 //
791 if (Op1I->getOpcode() == Instruction::And &&
792 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
793 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
794
Chris Lattner396dbfe2004-06-09 05:08:07 +0000795 Value *NewNot =
796 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000797 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000798 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000799
Chris Lattner0aee4b72004-10-06 15:08:25 +0000800 // -(X sdiv C) -> (X sdiv -C)
801 if (Op1I->getOpcode() == Instruction::Div)
802 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
803 if (CSI->getValue() == 0)
804 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
805 return BinaryOperator::createDiv(Op1I->getOperand(0),
806 ConstantExpr::getNeg(DivRHS));
807
Chris Lattner57c8d992003-02-18 19:57:07 +0000808 // X - X*C --> X * (1-C)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000809 ConstantInt *C2;
810 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
811 Constant *CP1 =
812 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000813 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000814 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000815 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000816
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000817
818 ConstantInt *C1;
819 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
820 if (X == Op1) { // X*C - X --> X * (C-1)
821 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
822 return BinaryOperator::createMul(Op1, CP1);
823 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000824
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000825 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
826 if (X == dyn_castFoldableMul(Op1, C2))
827 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
828 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000829 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000830}
831
Chris Lattnere79e8542004-02-23 06:38:22 +0000832/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
833/// really just returns true if the most significant (sign) bit is set.
834static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
835 if (RHS->getType()->isSigned()) {
836 // True if source is LHS < 0 or LHS <= -1
837 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
838 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
839 } else {
840 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
841 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
842 // the size of the integer type.
843 if (Opcode == Instruction::SetGE)
844 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
845 if (Opcode == Instruction::SetGT)
846 return RHSC->getValue() ==
847 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
848 }
849 return false;
850}
851
Chris Lattner113f4f42002-06-25 16:13:24 +0000852Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000853 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000854 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000855
Chris Lattner81a7a232004-10-16 18:11:37 +0000856 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
857 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
858
Chris Lattnere6794492002-08-12 21:17:25 +0000859 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000860 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
861 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000862
863 // ((X << C1)*C2) == (X * (C2 << C1))
864 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
865 if (SI->getOpcode() == Instruction::Shl)
866 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000867 return BinaryOperator::createMul(SI->getOperand(0),
868 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000869
Chris Lattnercce81be2003-09-11 22:24:54 +0000870 if (CI->isNullValue())
871 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
872 if (CI->equalsInt(1)) // X * 1 == X
873 return ReplaceInstUsesWith(I, Op0);
874 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000875 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000876
Chris Lattnercce81be2003-09-11 22:24:54 +0000877 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000878 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
879 return new ShiftInst(Instruction::Shl, Op0,
880 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000881 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000882 if (Op1F->isNullValue())
883 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000884
Chris Lattner3082c5a2003-02-18 19:28:33 +0000885 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
886 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
887 if (Op1F->getValue() == 1.0)
888 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
889 }
Chris Lattner183b3362004-04-09 19:05:30 +0000890
891 // Try to fold constant mul into select arguments.
892 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
893 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
894 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000895
896 if (isa<PHINode>(Op0))
897 if (Instruction *NV = FoldOpIntoPhi(I))
898 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000899 }
900
Chris Lattner934a64cf2003-03-10 23:23:04 +0000901 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
902 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000903 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000904
Chris Lattner2635b522004-02-23 05:39:21 +0000905 // If one of the operands of the multiply is a cast from a boolean value, then
906 // we know the bool is either zero or one, so this is a 'masking' multiply.
907 // See if we can simplify things based on how the boolean was originally
908 // formed.
909 CastInst *BoolCast = 0;
910 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
911 if (CI->getOperand(0)->getType() == Type::BoolTy)
912 BoolCast = CI;
913 if (!BoolCast)
914 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
915 if (CI->getOperand(0)->getType() == Type::BoolTy)
916 BoolCast = CI;
917 if (BoolCast) {
918 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
919 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
920 const Type *SCOpTy = SCIOp0->getType();
921
Chris Lattnere79e8542004-02-23 06:38:22 +0000922 // If the setcc is true iff the sign bit of X is set, then convert this
923 // multiply into a shift/and combination.
924 if (isa<ConstantInt>(SCIOp1) &&
925 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000926 // Shift the X value right to turn it into "all signbits".
927 Constant *Amt = ConstantUInt::get(Type::UByteTy,
928 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000929 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000930 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000931 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
932 SCIOp0->getName()), I);
933 }
934
935 Value *V =
936 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
937 BoolCast->getOperand(0)->getName()+
938 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000939
940 // If the multiply type is not the same as the source type, sign extend
941 // or truncate to the multiply type.
942 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000943 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000944
945 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000946 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000947 }
948 }
949 }
950
Chris Lattner113f4f42002-06-25 16:13:24 +0000951 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000952}
953
Chris Lattner113f4f42002-06-25 16:13:24 +0000954Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000955 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +0000956
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000957 if (isa<UndefValue>(Op0)) // undef / X -> 0
958 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
959 if (isa<UndefValue>(Op1))
960 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
961
962 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000963 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000964 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000965 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000966
Chris Lattnere20c3342004-04-26 14:01:59 +0000967 // div X, -1 == -X
968 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000969 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +0000970
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000971 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +0000972 if (LHS->getOpcode() == Instruction::Div)
973 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +0000974 // (X / C1) / C2 -> X / (C1*C2)
975 return BinaryOperator::createDiv(LHS->getOperand(0),
976 ConstantExpr::getMul(RHS, LHSRHS));
977 }
978
Chris Lattner3082c5a2003-02-18 19:28:33 +0000979 // Check to see if this is an unsigned division with an exact power of 2,
980 // if so, convert to a right shift.
981 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
982 if (uint64_t Val = C->getValue()) // Don't break X / 0
983 if (uint64_t C = Log2(Val))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000984 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +0000985 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000986
Chris Lattner4ad08352004-10-09 02:50:40 +0000987 // -X/C -> X/-C
988 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000989 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +0000990 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
991
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000992 if (!RHS->isNullValue()) {
993 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
994 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
995 return R;
996 if (isa<PHINode>(Op0))
997 if (Instruction *NV = FoldOpIntoPhi(I))
998 return NV;
999 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001000 }
1001
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001002 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1003 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1004 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1005 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1006 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1007 if (STO->getValue() == 0) { // Couldn't be this argument.
1008 I.setOperand(1, SFO);
1009 return &I;
1010 } else if (SFO->getValue() == 0) {
1011 I.setOperand(1, STO);
1012 return &I;
1013 }
1014
1015 if (uint64_t TSA = Log2(STO->getValue()))
1016 if (uint64_t FSA = Log2(SFO->getValue())) {
1017 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1018 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1019 TC, SI->getName()+".t");
1020 TSI = InsertNewInstBefore(TSI, I);
1021
1022 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1023 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1024 FC, SI->getName()+".f");
1025 FSI = InsertNewInstBefore(FSI, I);
1026 return new SelectInst(SI->getOperand(0), TSI, FSI);
1027 }
1028 }
1029
Chris Lattner3082c5a2003-02-18 19:28:33 +00001030 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001031 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001032 if (LHS->equalsInt(0))
1033 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1034
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001035 return 0;
1036}
1037
1038
Chris Lattner113f4f42002-06-25 16:13:24 +00001039Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001040 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner7fd5f072004-07-06 07:01:22 +00001041 if (I.getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001042 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001043 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001044 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001045 // X % -Y -> X % Y
1046 AddUsesToWorkList(I);
1047 I.setOperand(1, RHSNeg);
1048 return &I;
1049 }
1050
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001051 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001052 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001053 if (isa<UndefValue>(Op1))
1054 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001055
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001056 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001057 if (RHS->equalsInt(1)) // X % 1 == 0
1058 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1059
1060 // Check to see if this is an unsigned remainder with an exact power of 2,
1061 // if so, convert to a bitwise and.
1062 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1063 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001064 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001065 return BinaryOperator::createAnd(Op0,
1066 ConstantUInt::get(I.getType(), Val-1));
1067
1068 if (!RHS->isNullValue()) {
1069 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1070 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1071 return R;
1072 if (isa<PHINode>(Op0))
1073 if (Instruction *NV = FoldOpIntoPhi(I))
1074 return NV;
1075 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001076 }
1077
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001078 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1079 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1080 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1081 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1082 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1083 if (STO->getValue() == 0) { // Couldn't be this argument.
1084 I.setOperand(1, SFO);
1085 return &I;
1086 } else if (SFO->getValue() == 0) {
1087 I.setOperand(1, STO);
1088 return &I;
1089 }
1090
1091 if (!(STO->getValue() & (STO->getValue()-1)) &&
1092 !(SFO->getValue() & (SFO->getValue()-1))) {
1093 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1094 SubOne(STO), SI->getName()+".t"), I);
1095 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1096 SubOne(SFO), SI->getName()+".f"), I);
1097 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1098 }
1099 }
1100
Chris Lattner3082c5a2003-02-18 19:28:33 +00001101 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001102 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001103 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001104 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1105
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001106 return 0;
1107}
1108
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001109// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001110static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001111 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1112 // Calculate -1 casted to the right type...
1113 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1114 uint64_t Val = ~0ULL; // All ones
1115 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1116 return CU->getValue() == Val-1;
1117 }
1118
1119 const ConstantSInt *CS = cast<ConstantSInt>(C);
1120
1121 // Calculate 0111111111..11111
1122 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1123 int64_t Val = INT64_MAX; // All ones
1124 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1125 return CS->getValue() == Val-1;
1126}
1127
1128// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001129static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001130 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1131 return CU->getValue() == 1;
1132
1133 const ConstantSInt *CS = cast<ConstantSInt>(C);
1134
1135 // Calculate 1111111111000000000000
1136 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1137 int64_t Val = -1; // All ones
1138 Val <<= TypeBits-1; // Shift over to the right spot
1139 return CS->getValue() == Val+1;
1140}
1141
Chris Lattner35167c32004-06-09 07:59:58 +00001142// isOneBitSet - Return true if there is exactly one bit set in the specified
1143// constant.
1144static bool isOneBitSet(const ConstantInt *CI) {
1145 uint64_t V = CI->getRawValue();
1146 return V && (V & (V-1)) == 0;
1147}
1148
Chris Lattner8fc5af42004-09-23 21:46:38 +00001149#if 0 // Currently unused
1150// isLowOnes - Return true if the constant is of the form 0+1+.
1151static bool isLowOnes(const ConstantInt *CI) {
1152 uint64_t V = CI->getRawValue();
1153
1154 // There won't be bits set in parts that the type doesn't contain.
1155 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1156
1157 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1158 return U && V && (U & V) == 0;
1159}
1160#endif
1161
1162// isHighOnes - Return true if the constant is of the form 1+0+.
1163// This is the same as lowones(~X).
1164static bool isHighOnes(const ConstantInt *CI) {
1165 uint64_t V = ~CI->getRawValue();
1166
1167 // There won't be bits set in parts that the type doesn't contain.
1168 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1169
1170 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1171 return U && V && (U & V) == 0;
1172}
1173
1174
Chris Lattner3ac7c262003-08-13 20:16:26 +00001175/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1176/// are carefully arranged to allow folding of expressions such as:
1177///
1178/// (A < B) | (A > B) --> (A != B)
1179///
1180/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1181/// represents that the comparison is true if A == B, and bit value '1' is true
1182/// if A < B.
1183///
1184static unsigned getSetCondCode(const SetCondInst *SCI) {
1185 switch (SCI->getOpcode()) {
1186 // False -> 0
1187 case Instruction::SetGT: return 1;
1188 case Instruction::SetEQ: return 2;
1189 case Instruction::SetGE: return 3;
1190 case Instruction::SetLT: return 4;
1191 case Instruction::SetNE: return 5;
1192 case Instruction::SetLE: return 6;
1193 // True -> 7
1194 default:
1195 assert(0 && "Invalid SetCC opcode!");
1196 return 0;
1197 }
1198}
1199
1200/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1201/// opcode and two operands into either a constant true or false, or a brand new
1202/// SetCC instruction.
1203static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1204 switch (Opcode) {
1205 case 0: return ConstantBool::False;
1206 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1207 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1208 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1209 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1210 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1211 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1212 case 7: return ConstantBool::True;
1213 default: assert(0 && "Illegal SetCCCode!"); return 0;
1214 }
1215}
1216
1217// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1218struct FoldSetCCLogical {
1219 InstCombiner &IC;
1220 Value *LHS, *RHS;
1221 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1222 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1223 bool shouldApply(Value *V) const {
1224 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1225 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1226 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1227 return false;
1228 }
1229 Instruction *apply(BinaryOperator &Log) const {
1230 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1231 if (SCI->getOperand(0) != LHS) {
1232 assert(SCI->getOperand(1) == LHS);
1233 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1234 }
1235
1236 unsigned LHSCode = getSetCondCode(SCI);
1237 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1238 unsigned Code;
1239 switch (Log.getOpcode()) {
1240 case Instruction::And: Code = LHSCode & RHSCode; break;
1241 case Instruction::Or: Code = LHSCode | RHSCode; break;
1242 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001243 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001244 }
1245
1246 Value *RV = getSetCCValue(Code, LHS, RHS);
1247 if (Instruction *I = dyn_cast<Instruction>(RV))
1248 return I;
1249 // Otherwise, it's a constant boolean value...
1250 return IC.ReplaceInstUsesWith(Log, RV);
1251 }
1252};
1253
1254
Chris Lattnerba1cb382003-09-19 17:17:26 +00001255// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1256// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1257// guaranteed to be either a shift instruction or a binary operator.
1258Instruction *InstCombiner::OptAndOp(Instruction *Op,
1259 ConstantIntegral *OpRHS,
1260 ConstantIntegral *AndRHS,
1261 BinaryOperator &TheAnd) {
1262 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001263 Constant *Together = 0;
1264 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001265 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001266
Chris Lattnerba1cb382003-09-19 17:17:26 +00001267 switch (Op->getOpcode()) {
1268 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001269 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001270 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001271 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001272 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001273 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1274 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001275 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001276 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001277 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001278 }
1279 break;
1280 case Instruction::Or:
1281 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001282 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001283 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001284 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001285 if (Together == AndRHS) // (X | C) & C --> C
1286 return ReplaceInstUsesWith(TheAnd, AndRHS);
1287
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001288 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001289 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1290 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001291 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001292 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001293 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001294 }
1295 }
1296 break;
1297 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001298 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001299 // Adding a one to a single bit bit-field should be turned into an XOR
1300 // of the bit. First thing to check is to see if this AND is with a
1301 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001302 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001303
1304 // Clear bits that are not part of the constant.
1305 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1306
1307 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001308 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001309 // Ok, at this point, we know that we are masking the result of the
1310 // ADD down to exactly one bit. If the constant we are adding has
1311 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001312 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001313
1314 // Check to see if any bits below the one bit set in AndRHSV are set.
1315 if ((AddRHS & (AndRHSV-1)) == 0) {
1316 // If not, the only thing that can effect the output of the AND is
1317 // the bit specified by AndRHSV. If that bit is set, the effect of
1318 // the XOR is to toggle the bit. If it is clear, then the ADD has
1319 // no effect.
1320 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1321 TheAnd.setOperand(0, X);
1322 return &TheAnd;
1323 } else {
1324 std::string Name = Op->getName(); Op->setName("");
1325 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001326 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001327 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001328 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001329 }
1330 }
1331 }
1332 }
1333 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001334
1335 case Instruction::Shl: {
1336 // We know that the AND will not produce any of the bits shifted in, so if
1337 // the anded constant includes them, clear them now!
1338 //
1339 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001340 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1341 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1342
1343 if (CI == ShlMask) { // Masking out bits that the shift already masks
1344 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1345 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001346 TheAnd.setOperand(1, CI);
1347 return &TheAnd;
1348 }
1349 break;
1350 }
1351 case Instruction::Shr:
1352 // We know that the AND will not produce any of the bits shifted in, so if
1353 // the anded constant includes them, clear them now! This only applies to
1354 // unsigned shifts, because a signed shr may bring in set bits!
1355 //
1356 if (AndRHS->getType()->isUnsigned()) {
1357 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001358 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1359 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1360
1361 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1362 return ReplaceInstUsesWith(TheAnd, Op);
1363 } else if (CI != AndRHS) {
1364 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001365 return &TheAnd;
1366 }
Chris Lattner7e794272004-09-24 15:21:34 +00001367 } else { // Signed shr.
1368 // See if this is shifting in some sign extension, then masking it out
1369 // with an and.
1370 if (Op->hasOneUse()) {
1371 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1372 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1373 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001374 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001375 // Make the argument unsigned.
1376 Value *ShVal = Op->getOperand(0);
1377 ShVal = InsertCastBefore(ShVal,
1378 ShVal->getType()->getUnsignedVersion(),
1379 TheAnd);
1380 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1381 OpRHS, Op->getName()),
1382 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001383 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1384 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1385 TheAnd.getName()),
1386 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001387 return new CastInst(ShVal, Op->getType());
1388 }
1389 }
Chris Lattner2da29172003-09-19 19:05:02 +00001390 }
1391 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001392 }
1393 return 0;
1394}
1395
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001396
Chris Lattner6862fbd2004-09-29 17:40:11 +00001397/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1398/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1399/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1400/// insert new instructions.
1401Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1402 bool Inside, Instruction &IB) {
1403 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1404 "Lo is not <= Hi in range emission code!");
1405 if (Inside) {
1406 if (Lo == Hi) // Trivially false.
1407 return new SetCondInst(Instruction::SetNE, V, V);
1408 if (cast<ConstantIntegral>(Lo)->isMinValue())
1409 return new SetCondInst(Instruction::SetLT, V, Hi);
1410
1411 Constant *AddCST = ConstantExpr::getNeg(Lo);
1412 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1413 InsertNewInstBefore(Add, IB);
1414 // Convert to unsigned for the comparison.
1415 const Type *UnsType = Add->getType()->getUnsignedVersion();
1416 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1417 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1418 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1419 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1420 }
1421
1422 if (Lo == Hi) // Trivially true.
1423 return new SetCondInst(Instruction::SetEQ, V, V);
1424
1425 Hi = SubOne(cast<ConstantInt>(Hi));
1426 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1427 return new SetCondInst(Instruction::SetGT, V, Hi);
1428
1429 // Emit X-Lo > Hi-Lo-1
1430 Constant *AddCST = ConstantExpr::getNeg(Lo);
1431 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1432 InsertNewInstBefore(Add, IB);
1433 // Convert to unsigned for the comparison.
1434 const Type *UnsType = Add->getType()->getUnsignedVersion();
1435 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1436 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1437 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1438 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1439}
1440
1441
Chris Lattner113f4f42002-06-25 16:13:24 +00001442Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001443 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001444 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001445
Chris Lattner81a7a232004-10-16 18:11:37 +00001446 if (isa<UndefValue>(Op1)) // X & undef -> 0
1447 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1448
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001449 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001450 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1451 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001452
1453 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001454 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001455 if (RHS->isAllOnesValue())
1456 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001457
Chris Lattnerba1cb382003-09-19 17:17:26 +00001458 // Optimize a variety of ((val OP C1) & C2) combinations...
1459 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1460 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001461 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001462 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001463 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1464 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001465 }
Chris Lattner183b3362004-04-09 19:05:30 +00001466
1467 // Try to fold constant and into select arguments.
1468 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1469 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1470 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001471 if (isa<PHINode>(Op0))
1472 if (Instruction *NV = FoldOpIntoPhi(I))
1473 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001474 }
1475
Chris Lattnerbb74e222003-03-10 23:06:50 +00001476 Value *Op0NotVal = dyn_castNotVal(Op0);
1477 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001478
Chris Lattner023a4832004-06-18 06:07:51 +00001479 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1480 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1481
Misha Brukman9c003d82004-07-30 12:50:08 +00001482 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001483 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001484 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1485 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001486 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001487 return BinaryOperator::createNot(Or);
1488 }
1489
Chris Lattner623826c2004-09-28 21:48:02 +00001490 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1491 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001492 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1493 return R;
1494
Chris Lattner623826c2004-09-28 21:48:02 +00001495 Value *LHSVal, *RHSVal;
1496 ConstantInt *LHSCst, *RHSCst;
1497 Instruction::BinaryOps LHSCC, RHSCC;
1498 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1499 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1500 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1501 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1502 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1503 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1504 // Ensure that the larger constant is on the RHS.
1505 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1506 SetCondInst *LHS = cast<SetCondInst>(Op0);
1507 if (cast<ConstantBool>(Cmp)->getValue()) {
1508 std::swap(LHS, RHS);
1509 std::swap(LHSCst, RHSCst);
1510 std::swap(LHSCC, RHSCC);
1511 }
1512
1513 // At this point, we know we have have two setcc instructions
1514 // comparing a value against two constants and and'ing the result
1515 // together. Because of the above check, we know that we only have
1516 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1517 // FoldSetCCLogical check above), that the two constants are not
1518 // equal.
1519 assert(LHSCst != RHSCst && "Compares not folded above?");
1520
1521 switch (LHSCC) {
1522 default: assert(0 && "Unknown integer condition code!");
1523 case Instruction::SetEQ:
1524 switch (RHSCC) {
1525 default: assert(0 && "Unknown integer condition code!");
1526 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1527 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1528 return ReplaceInstUsesWith(I, ConstantBool::False);
1529 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1530 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1531 return ReplaceInstUsesWith(I, LHS);
1532 }
1533 case Instruction::SetNE:
1534 switch (RHSCC) {
1535 default: assert(0 && "Unknown integer condition code!");
1536 case Instruction::SetLT:
1537 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1538 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1539 break; // (X != 13 & X < 15) -> no change
1540 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1541 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1542 return ReplaceInstUsesWith(I, RHS);
1543 case Instruction::SetNE:
1544 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1545 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1546 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1547 LHSVal->getName()+".off");
1548 InsertNewInstBefore(Add, I);
1549 const Type *UnsType = Add->getType()->getUnsignedVersion();
1550 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1551 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1552 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1553 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1554 }
1555 break; // (X != 13 & X != 15) -> no change
1556 }
1557 break;
1558 case Instruction::SetLT:
1559 switch (RHSCC) {
1560 default: assert(0 && "Unknown integer condition code!");
1561 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1562 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1563 return ReplaceInstUsesWith(I, ConstantBool::False);
1564 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1565 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1566 return ReplaceInstUsesWith(I, LHS);
1567 }
1568 case Instruction::SetGT:
1569 switch (RHSCC) {
1570 default: assert(0 && "Unknown integer condition code!");
1571 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1572 return ReplaceInstUsesWith(I, LHS);
1573 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1574 return ReplaceInstUsesWith(I, RHS);
1575 case Instruction::SetNE:
1576 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1577 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1578 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001579 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1580 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001581 }
1582 }
1583 }
1584 }
1585
Chris Lattner113f4f42002-06-25 16:13:24 +00001586 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001587}
1588
Chris Lattner113f4f42002-06-25 16:13:24 +00001589Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001590 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001591 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001592
Chris Lattner81a7a232004-10-16 18:11:37 +00001593 if (isa<UndefValue>(Op1))
1594 return ReplaceInstUsesWith(I, // X | undef -> -1
1595 ConstantIntegral::getAllOnesValue(I.getType()));
1596
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001597 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001598 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1599 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001600
1601 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001602 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001603 if (RHS->isAllOnesValue())
1604 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001605
Chris Lattnerd4252a72004-07-30 07:50:03 +00001606 ConstantInt *C1; Value *X;
1607 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1608 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1609 std::string Op0Name = Op0->getName(); Op0->setName("");
1610 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1611 InsertNewInstBefore(Or, I);
1612 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1613 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001614
Chris Lattnerd4252a72004-07-30 07:50:03 +00001615 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1616 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1617 std::string Op0Name = Op0->getName(); Op0->setName("");
1618 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1619 InsertNewInstBefore(Or, I);
1620 return BinaryOperator::createXor(Or,
1621 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001622 }
Chris Lattner183b3362004-04-09 19:05:30 +00001623
1624 // Try to fold constant and into select arguments.
1625 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1626 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1627 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001628 if (isa<PHINode>(Op0))
1629 if (Instruction *NV = FoldOpIntoPhi(I))
1630 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001631 }
1632
Chris Lattner812aab72003-08-12 19:11:07 +00001633 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001634 Value *A, *B; ConstantInt *C1, *C2;
1635 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1636 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1637 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001638
Chris Lattnerd4252a72004-07-30 07:50:03 +00001639 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1640 if (A == Op1) // ~A | A == -1
1641 return ReplaceInstUsesWith(I,
1642 ConstantIntegral::getAllOnesValue(I.getType()));
1643 } else {
1644 A = 0;
1645 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001646
Chris Lattnerd4252a72004-07-30 07:50:03 +00001647 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1648 if (Op0 == B)
1649 return ReplaceInstUsesWith(I,
1650 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001651
Misha Brukman9c003d82004-07-30 12:50:08 +00001652 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001653 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1654 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1655 I.getName()+".demorgan"), I);
1656 return BinaryOperator::createNot(And);
1657 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001658 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001659
Chris Lattner3ac7c262003-08-13 20:16:26 +00001660 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001661 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001662 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1663 return R;
1664
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001665 Value *LHSVal, *RHSVal;
1666 ConstantInt *LHSCst, *RHSCst;
1667 Instruction::BinaryOps LHSCC, RHSCC;
1668 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1669 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1670 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1671 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1672 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1673 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1674 // Ensure that the larger constant is on the RHS.
1675 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1676 SetCondInst *LHS = cast<SetCondInst>(Op0);
1677 if (cast<ConstantBool>(Cmp)->getValue()) {
1678 std::swap(LHS, RHS);
1679 std::swap(LHSCst, RHSCst);
1680 std::swap(LHSCC, RHSCC);
1681 }
1682
1683 // At this point, we know we have have two setcc instructions
1684 // comparing a value against two constants and or'ing the result
1685 // together. Because of the above check, we know that we only have
1686 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1687 // FoldSetCCLogical check above), that the two constants are not
1688 // equal.
1689 assert(LHSCst != RHSCst && "Compares not folded above?");
1690
1691 switch (LHSCC) {
1692 default: assert(0 && "Unknown integer condition code!");
1693 case Instruction::SetEQ:
1694 switch (RHSCC) {
1695 default: assert(0 && "Unknown integer condition code!");
1696 case Instruction::SetEQ:
1697 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1698 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1699 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1700 LHSVal->getName()+".off");
1701 InsertNewInstBefore(Add, I);
1702 const Type *UnsType = Add->getType()->getUnsignedVersion();
1703 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1704 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1705 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1706 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1707 }
1708 break; // (X == 13 | X == 15) -> no change
1709
1710 case Instruction::SetGT:
1711 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1712 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1713 break; // (X == 13 | X > 15) -> no change
1714 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1715 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1716 return ReplaceInstUsesWith(I, RHS);
1717 }
1718 break;
1719 case Instruction::SetNE:
1720 switch (RHSCC) {
1721 default: assert(0 && "Unknown integer condition code!");
1722 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1723 return ReplaceInstUsesWith(I, RHS);
1724 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1725 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1726 return ReplaceInstUsesWith(I, LHS);
1727 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1728 return ReplaceInstUsesWith(I, ConstantBool::True);
1729 }
1730 break;
1731 case Instruction::SetLT:
1732 switch (RHSCC) {
1733 default: assert(0 && "Unknown integer condition code!");
1734 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1735 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001736 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1737 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001738 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1739 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1740 return ReplaceInstUsesWith(I, RHS);
1741 }
1742 break;
1743 case Instruction::SetGT:
1744 switch (RHSCC) {
1745 default: assert(0 && "Unknown integer condition code!");
1746 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1747 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1748 return ReplaceInstUsesWith(I, LHS);
1749 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1750 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1751 return ReplaceInstUsesWith(I, ConstantBool::True);
1752 }
1753 }
1754 }
1755 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001756 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001757}
1758
Chris Lattnerc2076352004-02-16 01:20:27 +00001759// XorSelf - Implements: X ^ X --> 0
1760struct XorSelf {
1761 Value *RHS;
1762 XorSelf(Value *rhs) : RHS(rhs) {}
1763 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1764 Instruction *apply(BinaryOperator &Xor) const {
1765 return &Xor;
1766 }
1767};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001768
1769
Chris Lattner113f4f42002-06-25 16:13:24 +00001770Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001771 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001772 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001773
Chris Lattner81a7a232004-10-16 18:11:37 +00001774 if (isa<UndefValue>(Op1))
1775 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1776
Chris Lattnerc2076352004-02-16 01:20:27 +00001777 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1778 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1779 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001780 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001781 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001782
Chris Lattner97638592003-07-23 21:37:07 +00001783 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001784 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001785 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001786 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001787
Chris Lattner97638592003-07-23 21:37:07 +00001788 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001789 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001790 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001791 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001792 return new SetCondInst(SCI->getInverseCondition(),
1793 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001794
Chris Lattner8f2f5982003-11-05 01:06:05 +00001795 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001796 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1797 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001798 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1799 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001800 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001801 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001802 }
Chris Lattner023a4832004-06-18 06:07:51 +00001803
1804 // ~(~X & Y) --> (X | ~Y)
1805 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1806 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1807 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1808 Instruction *NotY =
1809 BinaryOperator::createNot(Op0I->getOperand(1),
1810 Op0I->getOperand(1)->getName()+".not");
1811 InsertNewInstBefore(NotY, I);
1812 return BinaryOperator::createOr(Op0NotVal, NotY);
1813 }
1814 }
Chris Lattner97638592003-07-23 21:37:07 +00001815
1816 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001817 switch (Op0I->getOpcode()) {
1818 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001819 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001820 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001821 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1822 return BinaryOperator::createSub(
1823 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001824 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001825 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001826 }
Chris Lattnere5806662003-11-04 23:50:51 +00001827 break;
1828 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001829 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001830 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1831 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001832 break;
1833 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001834 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001835 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001836 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001837 break;
1838 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001839 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001840 }
Chris Lattner183b3362004-04-09 19:05:30 +00001841
1842 // Try to fold constant and into select arguments.
1843 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1844 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1845 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001846 if (isa<PHINode>(Op0))
1847 if (Instruction *NV = FoldOpIntoPhi(I))
1848 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001849 }
1850
Chris Lattnerbb74e222003-03-10 23:06:50 +00001851 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001852 if (X == Op1)
1853 return ReplaceInstUsesWith(I,
1854 ConstantIntegral::getAllOnesValue(I.getType()));
1855
Chris Lattnerbb74e222003-03-10 23:06:50 +00001856 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001857 if (X == Op0)
1858 return ReplaceInstUsesWith(I,
1859 ConstantIntegral::getAllOnesValue(I.getType()));
1860
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001861 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001862 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001863 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1864 cast<BinaryOperator>(Op1I)->swapOperands();
1865 I.swapOperands();
1866 std::swap(Op0, Op1);
1867 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1868 I.swapOperands();
1869 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001870 }
1871 } else if (Op1I->getOpcode() == Instruction::Xor) {
1872 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1873 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1874 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1875 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1876 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001877
1878 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001879 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001880 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1881 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001882 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001883 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1884 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001885 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001886 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001887 } else if (Op0I->getOpcode() == Instruction::Xor) {
1888 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1889 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1890 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1891 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001892 }
1893
Chris Lattner7aa2d472004-08-01 19:42:59 +00001894 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001895 Value *A, *B; ConstantInt *C1, *C2;
1896 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1897 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00001898 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00001899 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001900
Chris Lattner3ac7c262003-08-13 20:16:26 +00001901 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1902 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1903 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1904 return R;
1905
Chris Lattner113f4f42002-06-25 16:13:24 +00001906 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001907}
1908
Chris Lattner6862fbd2004-09-29 17:40:11 +00001909/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1910/// overflowed for this type.
1911static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1912 ConstantInt *In2) {
1913 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1914 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1915}
1916
1917static bool isPositive(ConstantInt *C) {
1918 return cast<ConstantSInt>(C)->getValue() >= 0;
1919}
1920
1921/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1922/// overflowed for this type.
1923static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1924 ConstantInt *In2) {
1925 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1926
1927 if (In1->getType()->isUnsigned())
1928 return cast<ConstantUInt>(Result)->getValue() <
1929 cast<ConstantUInt>(In1)->getValue();
1930 if (isPositive(In1) != isPositive(In2))
1931 return false;
1932 if (isPositive(In1))
1933 return cast<ConstantSInt>(Result)->getValue() <
1934 cast<ConstantSInt>(In1)->getValue();
1935 return cast<ConstantSInt>(Result)->getValue() >
1936 cast<ConstantSInt>(In1)->getValue();
1937}
1938
Chris Lattner113f4f42002-06-25 16:13:24 +00001939Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001940 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001941 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1942 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001943
1944 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001945 if (Op0 == Op1)
1946 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001947
Chris Lattner81a7a232004-10-16 18:11:37 +00001948 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
1949 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
1950
Chris Lattner15ff1e12004-11-14 07:33:16 +00001951 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
1952 // addresses never equal each other! We already know that Op0 != Op1.
1953 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
1954 isa<ConstantPointerNull>(Op0)) &&
1955 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
1956 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001957 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1958
1959 // setcc's with boolean values can always be turned into bitwise operations
1960 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00001961 switch (I.getOpcode()) {
1962 default: assert(0 && "Invalid setcc instruction!");
1963 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001964 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001965 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001966 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001967 }
Chris Lattner4456da62004-08-11 00:50:51 +00001968 case Instruction::SetNE:
1969 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001970
Chris Lattner4456da62004-08-11 00:50:51 +00001971 case Instruction::SetGT:
1972 std::swap(Op0, Op1); // Change setgt -> setlt
1973 // FALL THROUGH
1974 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1975 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1976 InsertNewInstBefore(Not, I);
1977 return BinaryOperator::createAnd(Not, Op1);
1978 }
1979 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001980 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00001981 // FALL THROUGH
1982 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1983 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1984 InsertNewInstBefore(Not, I);
1985 return BinaryOperator::createOr(Not, Op1);
1986 }
1987 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001988 }
1989
Chris Lattner2dd01742004-06-09 04:24:29 +00001990 // See if we are doing a comparison between a constant and an instruction that
1991 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001992 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00001993 // Check to see if we are comparing against the minimum or maximum value...
1994 if (CI->isMinValue()) {
1995 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1996 return ReplaceInstUsesWith(I, ConstantBool::False);
1997 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1998 return ReplaceInstUsesWith(I, ConstantBool::True);
1999 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2000 return BinaryOperator::createSetEQ(Op0, Op1);
2001 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2002 return BinaryOperator::createSetNE(Op0, Op1);
2003
2004 } else if (CI->isMaxValue()) {
2005 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2006 return ReplaceInstUsesWith(I, ConstantBool::False);
2007 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2008 return ReplaceInstUsesWith(I, ConstantBool::True);
2009 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2010 return BinaryOperator::createSetEQ(Op0, Op1);
2011 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2012 return BinaryOperator::createSetNE(Op0, Op1);
2013
2014 // Comparing against a value really close to min or max?
2015 } else if (isMinValuePlusOne(CI)) {
2016 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2017 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2018 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2019 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2020
2021 } else if (isMaxValueMinusOne(CI)) {
2022 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2023 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2024 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2025 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2026 }
2027
2028 // If we still have a setle or setge instruction, turn it into the
2029 // appropriate setlt or setgt instruction. Since the border cases have
2030 // already been handled above, this requires little checking.
2031 //
2032 if (I.getOpcode() == Instruction::SetLE)
2033 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2034 if (I.getOpcode() == Instruction::SetGE)
2035 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2036
Chris Lattnere1e10e12004-05-25 06:32:08 +00002037 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002038 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002039 case Instruction::PHI:
2040 if (Instruction *NV = FoldOpIntoPhi(I))
2041 return NV;
2042 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002043 case Instruction::And:
2044 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2045 LHSI->getOperand(0)->hasOneUse()) {
2046 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2047 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2048 // happens a LOT in code produced by the C front-end, for bitfield
2049 // access.
2050 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2051 ConstantUInt *ShAmt;
2052 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2053 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2054 const Type *Ty = LHSI->getType();
2055
2056 // We can fold this as long as we can't shift unknown bits
2057 // into the mask. This can only happen with signed shift
2058 // rights, as they sign-extend.
2059 if (ShAmt) {
2060 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002061 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002062 if (!CanFold) {
2063 // To test for the bad case of the signed shr, see if any
2064 // of the bits shifted in could be tested after the mask.
2065 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00002066 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002067 Constant *ShVal =
2068 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2069 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2070 CanFold = true;
2071 }
2072
2073 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002074 Constant *NewCst;
2075 if (Shift->getOpcode() == Instruction::Shl)
2076 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2077 else
2078 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002079
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002080 // Check to see if we are shifting out any of the bits being
2081 // compared.
2082 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2083 // If we shifted bits out, the fold is not going to work out.
2084 // As a special case, check to see if this means that the
2085 // result is always true or false now.
2086 if (I.getOpcode() == Instruction::SetEQ)
2087 return ReplaceInstUsesWith(I, ConstantBool::False);
2088 if (I.getOpcode() == Instruction::SetNE)
2089 return ReplaceInstUsesWith(I, ConstantBool::True);
2090 } else {
2091 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002092 Constant *NewAndCST;
2093 if (Shift->getOpcode() == Instruction::Shl)
2094 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2095 else
2096 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2097 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002098 LHSI->setOperand(0, Shift->getOperand(0));
2099 WorkList.push_back(Shift); // Shift is dead.
2100 AddUsesToWorkList(I);
2101 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002102 }
2103 }
Chris Lattner35167c32004-06-09 07:59:58 +00002104 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002105 }
2106 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002107
Reid Spencer279fa252004-11-28 21:31:15 +00002108 // (setcc (cast X to larger), CI)
2109 case Instruction::Cast: {
2110 Instruction* replacement =
2111 visitSetCondInstWithCastAndConstant(I,cast<CastInst>(LHSI),CI);
2112 if (replacement)
2113 return replacement;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002114 break;
2115 }
Reid Spencer279fa252004-11-28 21:31:15 +00002116
Chris Lattner272d5ca2004-09-28 18:22:15 +00002117 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2118 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2119 switch (I.getOpcode()) {
2120 default: break;
2121 case Instruction::SetEQ:
2122 case Instruction::SetNE: {
2123 // If we are comparing against bits always shifted out, the
2124 // comparison cannot succeed.
2125 Constant *Comp =
2126 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2127 if (Comp != CI) {// Comparing against a bit that we know is zero.
2128 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2129 Constant *Cst = ConstantBool::get(IsSetNE);
2130 return ReplaceInstUsesWith(I, Cst);
2131 }
2132
2133 if (LHSI->hasOneUse()) {
2134 // Otherwise strength reduce the shift into an and.
2135 unsigned ShAmtVal = ShAmt->getValue();
2136 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2137 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2138
2139 Constant *Mask;
2140 if (CI->getType()->isUnsigned()) {
2141 Mask = ConstantUInt::get(CI->getType(), Val);
2142 } else if (ShAmtVal != 0) {
2143 Mask = ConstantSInt::get(CI->getType(), Val);
2144 } else {
2145 Mask = ConstantInt::getAllOnesValue(CI->getType());
2146 }
2147
2148 Instruction *AndI =
2149 BinaryOperator::createAnd(LHSI->getOperand(0),
2150 Mask, LHSI->getName()+".mask");
2151 Value *And = InsertNewInstBefore(AndI, I);
2152 return new SetCondInst(I.getOpcode(), And,
2153 ConstantExpr::getUShr(CI, ShAmt));
2154 }
2155 }
2156 }
2157 }
2158 break;
2159
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002160 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002161 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002162 switch (I.getOpcode()) {
2163 default: break;
2164 case Instruction::SetEQ:
2165 case Instruction::SetNE: {
2166 // If we are comparing against bits always shifted out, the
2167 // comparison cannot succeed.
2168 Constant *Comp =
2169 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2170
2171 if (Comp != CI) {// Comparing against a bit that we know is zero.
2172 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2173 Constant *Cst = ConstantBool::get(IsSetNE);
2174 return ReplaceInstUsesWith(I, Cst);
2175 }
2176
2177 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00002178 unsigned ShAmtVal = ShAmt->getValue();
2179
Chris Lattner1023b872004-09-27 16:18:50 +00002180 // Otherwise strength reduce the shift into an and.
2181 uint64_t Val = ~0ULL; // All ones.
2182 Val <<= ShAmtVal; // Shift over to the right spot.
2183
2184 Constant *Mask;
2185 if (CI->getType()->isUnsigned()) {
2186 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2187 Val &= (1ULL << TypeBits)-1;
2188 Mask = ConstantUInt::get(CI->getType(), Val);
2189 } else {
2190 Mask = ConstantSInt::get(CI->getType(), Val);
2191 }
2192
2193 Instruction *AndI =
2194 BinaryOperator::createAnd(LHSI->getOperand(0),
2195 Mask, LHSI->getName()+".mask");
2196 Value *And = InsertNewInstBefore(AndI, I);
2197 return new SetCondInst(I.getOpcode(), And,
2198 ConstantExpr::getShl(CI, ShAmt));
2199 }
2200 break;
2201 }
2202 }
2203 }
2204 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002205
Chris Lattner6862fbd2004-09-29 17:40:11 +00002206 case Instruction::Div:
2207 // Fold: (div X, C1) op C2 -> range check
2208 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2209 // Fold this div into the comparison, producing a range check.
2210 // Determine, based on the divide type, what the range is being
2211 // checked. If there is an overflow on the low or high side, remember
2212 // it, otherwise compute the range [low, hi) bounding the new value.
2213 bool LoOverflow = false, HiOverflow = 0;
2214 ConstantInt *LoBound = 0, *HiBound = 0;
2215
2216 ConstantInt *Prod;
2217 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2218
Chris Lattnera92af962004-10-11 19:40:04 +00002219 Instruction::BinaryOps Opcode = I.getOpcode();
2220
Chris Lattner6862fbd2004-09-29 17:40:11 +00002221 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2222 } else if (LHSI->getType()->isUnsigned()) { // udiv
2223 LoBound = Prod;
2224 LoOverflow = ProdOV;
2225 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2226 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2227 if (CI->isNullValue()) { // (X / pos) op 0
2228 // Can't overflow.
2229 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2230 HiBound = DivRHS;
2231 } else if (isPositive(CI)) { // (X / pos) op pos
2232 LoBound = Prod;
2233 LoOverflow = ProdOV;
2234 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2235 } else { // (X / pos) op neg
2236 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2237 LoOverflow = AddWithOverflow(LoBound, Prod,
2238 cast<ConstantInt>(DivRHSH));
2239 HiBound = Prod;
2240 HiOverflow = ProdOV;
2241 }
2242 } else { // Divisor is < 0.
2243 if (CI->isNullValue()) { // (X / neg) op 0
2244 LoBound = AddOne(DivRHS);
2245 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2246 } else if (isPositive(CI)) { // (X / neg) op pos
2247 HiOverflow = LoOverflow = ProdOV;
2248 if (!LoOverflow)
2249 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2250 HiBound = AddOne(Prod);
2251 } else { // (X / neg) op neg
2252 LoBound = Prod;
2253 LoOverflow = HiOverflow = ProdOV;
2254 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2255 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002256
Chris Lattnera92af962004-10-11 19:40:04 +00002257 // Dividing by a negate swaps the condition.
2258 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002259 }
2260
2261 if (LoBound) {
2262 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002263 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002264 default: assert(0 && "Unhandled setcc opcode!");
2265 case Instruction::SetEQ:
2266 if (LoOverflow && HiOverflow)
2267 return ReplaceInstUsesWith(I, ConstantBool::False);
2268 else if (HiOverflow)
2269 return new SetCondInst(Instruction::SetGE, X, LoBound);
2270 else if (LoOverflow)
2271 return new SetCondInst(Instruction::SetLT, X, HiBound);
2272 else
2273 return InsertRangeTest(X, LoBound, HiBound, true, I);
2274 case Instruction::SetNE:
2275 if (LoOverflow && HiOverflow)
2276 return ReplaceInstUsesWith(I, ConstantBool::True);
2277 else if (HiOverflow)
2278 return new SetCondInst(Instruction::SetLT, X, LoBound);
2279 else if (LoOverflow)
2280 return new SetCondInst(Instruction::SetGE, X, HiBound);
2281 else
2282 return InsertRangeTest(X, LoBound, HiBound, false, I);
2283 case Instruction::SetLT:
2284 if (LoOverflow)
2285 return ReplaceInstUsesWith(I, ConstantBool::False);
2286 return new SetCondInst(Instruction::SetLT, X, LoBound);
2287 case Instruction::SetGT:
2288 if (HiOverflow)
2289 return ReplaceInstUsesWith(I, ConstantBool::False);
2290 return new SetCondInst(Instruction::SetGE, X, HiBound);
2291 }
2292 }
2293 }
2294 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002295 case Instruction::Select:
2296 // If either operand of the select is a constant, we can fold the
2297 // comparison into the select arms, which will cause one to be
2298 // constant folded and the select turned into a bitwise or.
2299 Value *Op1 = 0, *Op2 = 0;
2300 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00002301 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002302 // Fold the known value into the constant operand.
2303 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2304 // Insert a new SetCC of the other select operand.
2305 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002306 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002307 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00002308 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002309 // Fold the known value into the constant operand.
2310 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2311 // Insert a new SetCC of the other select operand.
2312 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002313 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002314 I.getName()), I);
2315 }
Chris Lattner2dd01742004-06-09 04:24:29 +00002316 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002317
2318 if (Op1)
2319 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2320 break;
2321 }
2322
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002323 // Simplify seteq and setne instructions...
2324 if (I.getOpcode() == Instruction::SetEQ ||
2325 I.getOpcode() == Instruction::SetNE) {
2326 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2327
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002328 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002329 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002330 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2331 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002332 case Instruction::Rem:
2333 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2334 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2335 BO->hasOneUse() &&
2336 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2337 if (unsigned L2 =
2338 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2339 const Type *UTy = BO->getType()->getUnsignedVersion();
2340 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2341 UTy, "tmp"), I);
2342 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2343 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2344 RHSCst, BO->getName()), I);
2345 return BinaryOperator::create(I.getOpcode(), NewRem,
2346 Constant::getNullValue(UTy));
2347 }
2348 break;
2349
Chris Lattnerc992add2003-08-13 05:33:12 +00002350 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002351 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2352 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002353 if (BO->hasOneUse())
2354 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2355 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002356 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002357 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2358 // efficiently invertible, or if the add has just this one use.
2359 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00002360
Chris Lattnerc992add2003-08-13 05:33:12 +00002361 if (Value *NegVal = dyn_castNegVal(BOp1))
2362 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2363 else if (Value *NegVal = dyn_castNegVal(BOp0))
2364 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002365 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002366 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2367 BO->setName("");
2368 InsertNewInstBefore(Neg, I);
2369 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2370 }
2371 }
2372 break;
2373 case Instruction::Xor:
2374 // For the xor case, we can xor two constants together, eliminating
2375 // the explicit xor.
2376 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2377 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002378 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002379
2380 // FALLTHROUGH
2381 case Instruction::Sub:
2382 // Replace (([sub|xor] A, B) != 0) with (A != B)
2383 if (CI->isNullValue())
2384 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2385 BO->getOperand(1));
2386 break;
2387
2388 case Instruction::Or:
2389 // If bits are being or'd in that are not present in the constant we
2390 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002391 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002392 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002393 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002394 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002395 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002396 break;
2397
2398 case Instruction::And:
2399 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002400 // If bits are being compared against that are and'd out, then the
2401 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002402 if (!ConstantExpr::getAnd(CI,
2403 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002404 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002405
Chris Lattner35167c32004-06-09 07:59:58 +00002406 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002407 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002408 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2409 Instruction::SetNE, Op0,
2410 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002411
Chris Lattnerc992add2003-08-13 05:33:12 +00002412 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2413 // to be a signed value as appropriate.
2414 if (isSignBit(BOC)) {
2415 Value *X = BO->getOperand(0);
2416 // If 'X' is not signed, insert a cast now...
2417 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002418 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002419 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002420 }
2421 return new SetCondInst(isSetNE ? Instruction::SetLT :
2422 Instruction::SetGE, X,
2423 Constant::getNullValue(X->getType()));
2424 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002425
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002426 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002427 if (CI->isNullValue() && isHighOnes(BOC)) {
2428 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002429 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002430
2431 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002432 if (NegX->getType()->isSigned()) {
2433 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2434 X = InsertCastBefore(X, DestTy, I);
2435 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002436 }
2437
2438 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002439 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002440 }
2441
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002442 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002443 default: break;
2444 }
2445 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002446 } else { // Not a SetEQ/SetNE
2447 // If the LHS is a cast from an integral value of the same size,
2448 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2449 Value *CastOp = Cast->getOperand(0);
2450 const Type *SrcTy = CastOp->getType();
2451 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2452 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2453 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2454 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2455 "Source and destination signednesses should differ!");
2456 if (Cast->getType()->isSigned()) {
2457 // If this is a signed comparison, check for comparisons in the
2458 // vicinity of zero.
2459 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2460 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002461 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002462 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2463 else if (I.getOpcode() == Instruction::SetGT &&
2464 cast<ConstantSInt>(CI)->getValue() == -1)
2465 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002466 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002467 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2468 } else {
2469 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2470 if (I.getOpcode() == Instruction::SetLT &&
2471 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2472 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002473 return BinaryOperator::createSetGT(CastOp,
2474 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002475 else if (I.getOpcode() == Instruction::SetGT &&
2476 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2477 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002478 return BinaryOperator::createSetLT(CastOp,
2479 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002480 }
2481 }
2482 }
Chris Lattnere967b342003-06-04 05:10:11 +00002483 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002484 }
2485
Chris Lattner16930792003-11-03 04:25:02 +00002486 // Test to see if the operands of the setcc are casted versions of other
2487 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002488 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2489 Value *CastOp0 = CI->getOperand(0);
2490 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002491 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002492 (I.getOpcode() == Instruction::SetEQ ||
2493 I.getOpcode() == Instruction::SetNE)) {
2494 // We keep moving the cast from the left operand over to the right
2495 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002496 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002497
2498 // If operand #1 is a cast instruction, see if we can eliminate it as
2499 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002500 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2501 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002502 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002503 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002504
2505 // If Op1 is a constant, we can fold the cast into the constant.
2506 if (Op1->getType() != Op0->getType())
2507 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2508 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2509 } else {
2510 // Otherwise, cast the RHS right before the setcc
2511 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2512 InsertNewInstBefore(cast<Instruction>(Op1), I);
2513 }
2514 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2515 }
2516
Chris Lattner6444c372003-11-03 05:17:03 +00002517 // Handle the special case of: setcc (cast bool to X), <cst>
2518 // This comes up when you have code like
2519 // int X = A < B;
2520 // if (X) ...
2521 // For generality, we handle any zero-extension of any operand comparison
2522 // with a constant.
2523 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2524 const Type *SrcTy = CastOp0->getType();
2525 const Type *DestTy = Op0->getType();
2526 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2527 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2528 // Ok, we have an expansion of operand 0 into a new type. Get the
2529 // constant value, masink off bits which are not set in the RHS. These
2530 // could be set if the destination value is signed.
2531 uint64_t ConstVal = ConstantRHS->getRawValue();
2532 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2533
2534 // If the constant we are comparing it with has high bits set, which
2535 // don't exist in the original value, the values could never be equal,
2536 // because the source would be zero extended.
2537 unsigned SrcBits =
2538 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002539 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2540 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002541 switch (I.getOpcode()) {
2542 default: assert(0 && "Unknown comparison type!");
2543 case Instruction::SetEQ:
2544 return ReplaceInstUsesWith(I, ConstantBool::False);
2545 case Instruction::SetNE:
2546 return ReplaceInstUsesWith(I, ConstantBool::True);
2547 case Instruction::SetLT:
2548 case Instruction::SetLE:
2549 if (DestTy->isSigned() && HasSignBit)
2550 return ReplaceInstUsesWith(I, ConstantBool::False);
2551 return ReplaceInstUsesWith(I, ConstantBool::True);
2552 case Instruction::SetGT:
2553 case Instruction::SetGE:
2554 if (DestTy->isSigned() && HasSignBit)
2555 return ReplaceInstUsesWith(I, ConstantBool::True);
2556 return ReplaceInstUsesWith(I, ConstantBool::False);
2557 }
2558 }
2559
2560 // Otherwise, we can replace the setcc with a setcc of the smaller
2561 // operand value.
2562 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2563 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2564 }
2565 }
2566 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002567 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002568}
2569
Reid Spencer279fa252004-11-28 21:31:15 +00002570// visitSetCondInstWithCastAndConstant - this method is part of the
2571// visitSetCondInst method. It handles the situation where we have:
2572// (setcc (cast X to larger), CI)
2573// It tries to remove the cast and even the setcc if the CI value
2574// and range of the cast allow it.
2575Instruction *
2576InstCombiner::visitSetCondInstWithCastAndConstant(BinaryOperator&I,
2577 CastInst* LHSI,
2578 ConstantInt* CI) {
2579 const Type *SrcTy = LHSI->getOperand(0)->getType();
2580 const Type *DestTy = LHSI->getType();
2581 if (SrcTy->isIntegral() && DestTy->isIntegral()) {
2582 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
2583 unsigned DestBits = DestTy->getPrimitiveSize()*8;
2584 if (SrcTy == Type::BoolTy)
2585 SrcBits = 1;
2586 if (DestTy == Type::BoolTy)
2587 DestBits = 1;
2588 if (SrcBits < DestBits) {
2589 // There are fewer bits in the source of the cast than in the result
2590 // of the cast. Any other case doesn't matter because the constant
2591 // value won't have changed due to sign extension.
2592 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
2593 if (ConstantExpr::getCast(NewCst, DestTy) == CI) {
2594 // The constant value operand of the setCC before and after a
2595 // cast to the source type of the cast instruction is the same
2596 // value, so we just replace with the same setcc opcode, but
2597 // using the source value compared to the constant casted to the
2598 // source type.
2599 if (SrcTy->isSigned() && DestTy->isUnsigned()) {
2600 CastInst* Cst = new CastInst(LHSI->getOperand(0),
2601 SrcTy->getUnsignedVersion(), LHSI->getName());
2602 InsertNewInstBefore(Cst,I);
2603 return new SetCondInst(I.getOpcode(), Cst,
2604 ConstantExpr::getCast(CI, SrcTy->getUnsignedVersion()));
2605 }
2606 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),NewCst);
2607 }
2608 // The constant value before and after a cast to the source type
2609 // is different, so various cases are possible depending on the
2610 // opcode and the signs of the types involved in the cast.
2611 switch (I.getOpcode()) {
2612 case Instruction::SetLT: {
2613 Constant* Max = ConstantIntegral::getMaxValue(SrcTy);
2614 Max = ConstantExpr::getCast(Max, DestTy);
2615 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
2616 }
2617 case Instruction::SetGT: {
2618 Constant* Min = ConstantIntegral::getMinValue(SrcTy);
2619 Min = ConstantExpr::getCast(Min, DestTy);
2620 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
2621 }
2622 case Instruction::SetEQ:
2623 // We're looking for equality, and we know the values are not
2624 // equal so replace with constant False.
2625 return ReplaceInstUsesWith(I, ConstantBool::False);
2626 case Instruction::SetNE:
2627 // We're testing for inequality, and we know the values are not
2628 // equal so replace with constant True.
2629 return ReplaceInstUsesWith(I, ConstantBool::True);
2630 case Instruction::SetLE:
2631 case Instruction::SetGE:
2632 assert(!"SetLE and SetGE should be handled elsewhere");
2633 default:
2634 assert(!"unknown integer comparison");
2635 }
2636 }
2637 }
2638 return 0;
2639}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002640
2641
Chris Lattnere8d6c602003-03-10 19:16:08 +00002642Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002643 assert(I.getOperand(1)->getType() == Type::UByteTy);
2644 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002645 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002646
2647 // shl X, 0 == X and shr X, 0 == X
2648 // shl 0, X == 0 and shr 0, X == 0
2649 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00002650 Op0 == Constant::getNullValue(Op0->getType()))
2651 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002652
Chris Lattner81a7a232004-10-16 18:11:37 +00002653 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
2654 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00002655 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00002656 else // undef << X -> 0 AND undef >>u X -> 0
2657 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2658 }
2659 if (isa<UndefValue>(Op1)) {
2660 if (isLeftShift || I.getType()->isUnsigned())
2661 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2662 else
2663 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
2664 }
2665
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002666 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2667 if (!isLeftShift)
2668 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2669 if (CSI->isAllOnesValue())
2670 return ReplaceInstUsesWith(I, CSI);
2671
Chris Lattner183b3362004-04-09 19:05:30 +00002672 // Try to fold constant and into select arguments.
2673 if (isa<Constant>(Op0))
2674 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2675 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2676 return R;
2677
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002678 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002679 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2680 // of a signed value.
2681 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00002682 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002683 if (CUI->getValue() >= TypeBits) {
2684 if (!Op0->getType()->isSigned() || isLeftShift)
2685 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2686 else {
2687 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2688 return &I;
2689 }
2690 }
Chris Lattner55f3d942002-09-10 23:04:09 +00002691
Chris Lattnerede3fe02003-08-13 04:18:28 +00002692 // ((X*C1) << C2) == (X * (C1 << C2))
2693 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2694 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2695 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002696 return BinaryOperator::createMul(BO->getOperand(0),
2697 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00002698
Chris Lattner183b3362004-04-09 19:05:30 +00002699 // Try to fold constant and into select arguments.
2700 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2701 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2702 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002703 if (isa<PHINode>(Op0))
2704 if (Instruction *NV = FoldOpIntoPhi(I))
2705 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00002706
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002707 // If the operand is an bitwise operator with a constant RHS, and the
2708 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002709 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002710 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2711 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2712 bool isValid = true; // Valid only for And, Or, Xor
2713 bool highBitSet = false; // Transform if high bit of constant set?
2714
2715 switch (Op0BO->getOpcode()) {
2716 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00002717 case Instruction::Add:
2718 isValid = isLeftShift;
2719 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002720 case Instruction::Or:
2721 case Instruction::Xor:
2722 highBitSet = false;
2723 break;
2724 case Instruction::And:
2725 highBitSet = true;
2726 break;
2727 }
2728
2729 // If this is a signed shift right, and the high bit is modified
2730 // by the logical operation, do not perform the transformation.
2731 // The highBitSet boolean indicates the value of the high bit of
2732 // the constant which would cause it to be modified for this
2733 // operation.
2734 //
2735 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2736 uint64_t Val = Op0C->getRawValue();
2737 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2738 }
2739
2740 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002741 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002742
2743 Instruction *NewShift =
2744 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2745 Op0BO->getName());
2746 Op0BO->setName("");
2747 InsertNewInstBefore(NewShift, I);
2748
2749 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2750 NewRHS);
2751 }
2752 }
2753
Chris Lattner3204d4e2003-07-24 17:52:58 +00002754 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002755 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00002756 if (ConstantUInt *ShiftAmt1C =
2757 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002758 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2759 unsigned ShiftAmt2 = CUI->getValue();
2760
2761 // Check for (A << c1) << c2 and (A >> c1) >> c2
2762 if (I.getOpcode() == Op0SI->getOpcode()) {
2763 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002764 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2765 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00002766 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2767 ConstantUInt::get(Type::UByteTy, Amt));
2768 }
2769
Chris Lattnerab780df2003-07-24 18:38:56 +00002770 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2771 // signed types, we can only support the (A >> c1) << c2 configuration,
2772 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002773 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002774 // Calculate bitmask for what gets shifted off the edge...
2775 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002776 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002777 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002778 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002779 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00002780
2781 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002782 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2783 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00002784 InsertNewInstBefore(Mask, I);
2785
2786 // Figure out what flavor of shift we should use...
2787 if (ShiftAmt1 == ShiftAmt2)
2788 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2789 else if (ShiftAmt1 < ShiftAmt2) {
2790 return new ShiftInst(I.getOpcode(), Mask,
2791 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2792 } else {
2793 return new ShiftInst(Op0SI->getOpcode(), Mask,
2794 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2795 }
2796 }
2797 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002798 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00002799
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002800 return 0;
2801}
2802
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002803enum CastType {
2804 Noop = 0,
2805 Truncate = 1,
2806 Signext = 2,
2807 Zeroext = 3
2808};
2809
2810/// getCastType - In the future, we will split the cast instruction into these
2811/// various types. Until then, we have to do the analysis here.
2812static CastType getCastType(const Type *Src, const Type *Dest) {
2813 assert(Src->isIntegral() && Dest->isIntegral() &&
2814 "Only works on integral types!");
2815 unsigned SrcSize = Src->getPrimitiveSize()*8;
2816 if (Src == Type::BoolTy) SrcSize = 1;
2817 unsigned DestSize = Dest->getPrimitiveSize()*8;
2818 if (Dest == Type::BoolTy) DestSize = 1;
2819
2820 if (SrcSize == DestSize) return Noop;
2821 if (SrcSize > DestSize) return Truncate;
2822 if (Src->isSigned()) return Signext;
2823 return Zeroext;
2824}
2825
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002826
Chris Lattner48a44f72002-05-02 17:06:02 +00002827// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2828// instruction.
2829//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002830static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00002831 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002832
Chris Lattner650b6da2002-08-02 20:00:25 +00002833 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2834 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00002835 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00002836 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00002837 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00002838
Chris Lattner4fbad962004-07-21 04:27:24 +00002839 // If we are casting between pointer and integer types, treat pointers as
2840 // integers of the appropriate size for the code below.
2841 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2842 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2843 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00002844
Chris Lattner48a44f72002-05-02 17:06:02 +00002845 // Allow free casting and conversion of sizes as long as the sign doesn't
2846 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002847 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002848 CastType FirstCast = getCastType(SrcTy, MidTy);
2849 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00002850
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002851 // Capture the effect of these two casts. If the result is a legal cast,
2852 // the CastType is stored here, otherwise a special code is used.
2853 static const unsigned CastResult[] = {
2854 // First cast is noop
2855 0, 1, 2, 3,
2856 // First cast is a truncate
2857 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2858 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00002859 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002860 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00002861 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002862 };
2863
2864 unsigned Result = CastResult[FirstCast*4+SecondCast];
2865 switch (Result) {
2866 default: assert(0 && "Illegal table value!");
2867 case 0:
2868 case 1:
2869 case 2:
2870 case 3:
2871 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2872 // truncates, we could eliminate more casts.
2873 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2874 case 4:
2875 return false; // Not possible to eliminate this here.
2876 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00002877 // Sign or zero extend followed by truncate is always ok if the result
2878 // is a truncate or noop.
2879 CastType ResultCast = getCastType(SrcTy, DstTy);
2880 if (ResultCast == Noop || ResultCast == Truncate)
2881 return true;
2882 // Otherwise we are still growing the value, we are only safe if the
2883 // result will match the sign/zeroextendness of the result.
2884 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00002885 }
Chris Lattner650b6da2002-08-02 20:00:25 +00002886 }
Chris Lattner48a44f72002-05-02 17:06:02 +00002887 return false;
2888}
2889
Chris Lattner11ffd592004-07-20 05:21:00 +00002890static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002891 if (V->getType() == Ty || isa<Constant>(V)) return false;
2892 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00002893 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2894 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002895 return false;
2896 return true;
2897}
2898
2899/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2900/// InsertBefore instruction. This is specialized a bit to avoid inserting
2901/// casts that are known to not do anything...
2902///
2903Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2904 Instruction *InsertBefore) {
2905 if (V->getType() == DestTy) return V;
2906 if (Constant *C = dyn_cast<Constant>(V))
2907 return ConstantExpr::getCast(C, DestTy);
2908
2909 CastInst *CI = new CastInst(V, DestTy, V->getName());
2910 InsertNewInstBefore(CI, *InsertBefore);
2911 return CI;
2912}
Chris Lattner48a44f72002-05-02 17:06:02 +00002913
2914// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002915//
Chris Lattner113f4f42002-06-25 16:13:24 +00002916Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002917 Value *Src = CI.getOperand(0);
2918
Chris Lattner48a44f72002-05-02 17:06:02 +00002919 // If the user is casting a value to the same type, eliminate this cast
2920 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002921 if (CI.getType() == Src->getType())
2922 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002923
Chris Lattner81a7a232004-10-16 18:11:37 +00002924 if (isa<UndefValue>(Src)) // cast undef -> undef
2925 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
2926
Chris Lattner48a44f72002-05-02 17:06:02 +00002927 // If casting the result of another cast instruction, try to eliminate this
2928 // one!
2929 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002930 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002931 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner11ffd592004-07-20 05:21:00 +00002932 CSrc->getType(), CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002933 // This instruction now refers directly to the cast's src operand. This
2934 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002935 CI.setOperand(0, CSrc->getOperand(0));
2936 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002937 }
2938
Chris Lattner650b6da2002-08-02 20:00:25 +00002939 // If this is an A->B->A cast, and we are dealing with integral types, try
2940 // to convert this into a logical 'and' instruction.
2941 //
2942 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002943 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002944 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2945 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2946 assert(CSrc->getType() != Type::ULongTy &&
2947 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002948 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002949 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002950 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002951 }
2952 }
2953
Chris Lattner03841652004-05-25 04:29:21 +00002954 // If this is a cast to bool, turn it into the appropriate setne instruction.
2955 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002956 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002957 Constant::getNullValue(CI.getOperand(0)->getType()));
2958
Chris Lattnerd0d51602003-06-21 23:12:02 +00002959 // If casting the result of a getelementptr instruction with no offset, turn
2960 // this into a cast of the original pointer!
2961 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002962 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002963 bool AllZeroOperands = true;
2964 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2965 if (!isa<Constant>(GEP->getOperand(i)) ||
2966 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2967 AllZeroOperands = false;
2968 break;
2969 }
2970 if (AllZeroOperands) {
2971 CI.setOperand(0, GEP->getOperand(0));
2972 return &CI;
2973 }
2974 }
2975
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002976 // If we are casting a malloc or alloca to a pointer to a type of the same
2977 // size, rewrite the allocation instruction to allocate the "right" type.
2978 //
2979 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002980 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002981 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2982 // Get the type really allocated and the type casted to...
2983 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002984 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002985 if (AllocElTy->isSized() && CastElTy->isSized()) {
2986 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2987 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002988
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002989 // If the allocation is for an even multiple of the cast type size
2990 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2991 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002992 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002993 std::string Name = AI->getName(); AI->setName("");
2994 AllocationInst *New;
2995 if (isa<MallocInst>(AI))
2996 New = new MallocInst(CastElTy, Amt, Name);
2997 else
2998 New = new AllocaInst(CastElTy, Amt, Name);
2999 InsertNewInstBefore(New, *AI);
3000 return ReplaceInstUsesWith(CI, New);
3001 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003002 }
3003 }
3004
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003005 if (isa<PHINode>(Src))
3006 if (Instruction *NV = FoldOpIntoPhi(CI))
3007 return NV;
3008
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003009 // If the source value is an instruction with only this use, we can attempt to
3010 // propagate the cast into the instruction. Also, only handle integral types
3011 // for now.
3012 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003013 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003014 CI.getType()->isInteger()) { // Don't mess with casts to bool here
3015 const Type *DestTy = CI.getType();
3016 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
3017 unsigned DestBitSize = getTypeSizeInBits(DestTy);
3018
3019 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3020 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3021
3022 switch (SrcI->getOpcode()) {
3023 case Instruction::Add:
3024 case Instruction::Mul:
3025 case Instruction::And:
3026 case Instruction::Or:
3027 case Instruction::Xor:
3028 // If we are discarding information, or just changing the sign, rewrite.
3029 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3030 // Don't insert two casts if they cannot be eliminated. We allow two
3031 // casts to be inserted if the sizes are the same. This could only be
3032 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00003033 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3034 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003035 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3036 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3037 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3038 ->getOpcode(), Op0c, Op1c);
3039 }
3040 }
3041 break;
3042 case Instruction::Shl:
3043 // Allow changing the sign of the source operand. Do not allow changing
3044 // the size of the shift, UNLESS the shift amount is a constant. We
3045 // mush not change variable sized shifts to a smaller size, because it
3046 // is undefined to shift more bits out than exist in the value.
3047 if (DestBitSize == SrcBitSize ||
3048 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3049 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3050 return new ShiftInst(Instruction::Shl, Op0c, Op1);
3051 }
3052 break;
3053 }
3054 }
3055
Chris Lattner260ab202002-04-18 17:39:14 +00003056 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00003057}
3058
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003059/// GetSelectFoldableOperands - We want to turn code that looks like this:
3060/// %C = or %A, %B
3061/// %D = select %cond, %C, %A
3062/// into:
3063/// %C = select %cond, %B, 0
3064/// %D = or %A, %C
3065///
3066/// Assuming that the specified instruction is an operand to the select, return
3067/// a bitmask indicating which operands of this instruction are foldable if they
3068/// equal the other incoming value of the select.
3069///
3070static unsigned GetSelectFoldableOperands(Instruction *I) {
3071 switch (I->getOpcode()) {
3072 case Instruction::Add:
3073 case Instruction::Mul:
3074 case Instruction::And:
3075 case Instruction::Or:
3076 case Instruction::Xor:
3077 return 3; // Can fold through either operand.
3078 case Instruction::Sub: // Can only fold on the amount subtracted.
3079 case Instruction::Shl: // Can only fold on the shift amount.
3080 case Instruction::Shr:
3081 return 1;
3082 default:
3083 return 0; // Cannot fold
3084 }
3085}
3086
3087/// GetSelectFoldableConstant - For the same transformation as the previous
3088/// function, return the identity constant that goes into the select.
3089static Constant *GetSelectFoldableConstant(Instruction *I) {
3090 switch (I->getOpcode()) {
3091 default: assert(0 && "This cannot happen!"); abort();
3092 case Instruction::Add:
3093 case Instruction::Sub:
3094 case Instruction::Or:
3095 case Instruction::Xor:
3096 return Constant::getNullValue(I->getType());
3097 case Instruction::Shl:
3098 case Instruction::Shr:
3099 return Constant::getNullValue(Type::UByteTy);
3100 case Instruction::And:
3101 return ConstantInt::getAllOnesValue(I->getType());
3102 case Instruction::Mul:
3103 return ConstantInt::get(I->getType(), 1);
3104 }
3105}
3106
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003107Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00003108 Value *CondVal = SI.getCondition();
3109 Value *TrueVal = SI.getTrueValue();
3110 Value *FalseVal = SI.getFalseValue();
3111
3112 // select true, X, Y -> X
3113 // select false, X, Y -> Y
3114 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003115 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00003116 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003117 else {
3118 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00003119 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003120 }
Chris Lattner533bc492004-03-30 19:37:13 +00003121
3122 // select C, X, X -> X
3123 if (TrueVal == FalseVal)
3124 return ReplaceInstUsesWith(SI, TrueVal);
3125
Chris Lattner81a7a232004-10-16 18:11:37 +00003126 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3127 return ReplaceInstUsesWith(SI, FalseVal);
3128 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3129 return ReplaceInstUsesWith(SI, TrueVal);
3130 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3131 if (isa<Constant>(TrueVal))
3132 return ReplaceInstUsesWith(SI, TrueVal);
3133 else
3134 return ReplaceInstUsesWith(SI, FalseVal);
3135 }
3136
Chris Lattner1c631e82004-04-08 04:43:23 +00003137 if (SI.getType() == Type::BoolTy)
3138 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3139 if (C == ConstantBool::True) {
3140 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003141 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003142 } else {
3143 // Change: A = select B, false, C --> A = and !B, C
3144 Value *NotCond =
3145 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3146 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003147 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003148 }
3149 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3150 if (C == ConstantBool::False) {
3151 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003152 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003153 } else {
3154 // Change: A = select B, C, true --> A = or !B, C
3155 Value *NotCond =
3156 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3157 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003158 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003159 }
3160 }
3161
Chris Lattner183b3362004-04-09 19:05:30 +00003162 // Selecting between two integer constants?
3163 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3164 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3165 // select C, 1, 0 -> cast C to int
3166 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3167 return new CastInst(CondVal, SI.getType());
3168 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3169 // select C, 0, 1 -> cast !C to int
3170 Value *NotCond =
3171 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00003172 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00003173 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00003174 }
Chris Lattner35167c32004-06-09 07:59:58 +00003175
3176 // If one of the constants is zero (we know they can't both be) and we
3177 // have a setcc instruction with zero, and we have an 'and' with the
3178 // non-constant value, eliminate this whole mess. This corresponds to
3179 // cases like this: ((X & 27) ? 27 : 0)
3180 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3181 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3182 if ((IC->getOpcode() == Instruction::SetEQ ||
3183 IC->getOpcode() == Instruction::SetNE) &&
3184 isa<ConstantInt>(IC->getOperand(1)) &&
3185 cast<Constant>(IC->getOperand(1))->isNullValue())
3186 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3187 if (ICA->getOpcode() == Instruction::And &&
3188 isa<ConstantInt>(ICA->getOperand(1)) &&
3189 (ICA->getOperand(1) == TrueValC ||
3190 ICA->getOperand(1) == FalseValC) &&
3191 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3192 // Okay, now we know that everything is set up, we just don't
3193 // know whether we have a setne or seteq and whether the true or
3194 // false val is the zero.
3195 bool ShouldNotVal = !TrueValC->isNullValue();
3196 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3197 Value *V = ICA;
3198 if (ShouldNotVal)
3199 V = InsertNewInstBefore(BinaryOperator::create(
3200 Instruction::Xor, V, ICA->getOperand(1)), SI);
3201 return ReplaceInstUsesWith(SI, V);
3202 }
Chris Lattner533bc492004-03-30 19:37:13 +00003203 }
Chris Lattner623fba12004-04-10 22:21:27 +00003204
3205 // See if we are selecting two values based on a comparison of the two values.
3206 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3207 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3208 // Transform (X == Y) ? X : Y -> Y
3209 if (SCI->getOpcode() == Instruction::SetEQ)
3210 return ReplaceInstUsesWith(SI, FalseVal);
3211 // Transform (X != Y) ? X : Y -> X
3212 if (SCI->getOpcode() == Instruction::SetNE)
3213 return ReplaceInstUsesWith(SI, TrueVal);
3214 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3215
3216 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3217 // Transform (X == Y) ? Y : X -> X
3218 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003219 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003220 // Transform (X != Y) ? Y : X -> Y
3221 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003222 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003223 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3224 }
3225 }
Chris Lattner1c631e82004-04-08 04:43:23 +00003226
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003227 // See if we can fold the select into one of our operands.
3228 if (SI.getType()->isInteger()) {
3229 // See the comment above GetSelectFoldableOperands for a description of the
3230 // transformation we are doing here.
3231 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3232 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3233 !isa<Constant>(FalseVal))
3234 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3235 unsigned OpToFold = 0;
3236 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3237 OpToFold = 1;
3238 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3239 OpToFold = 2;
3240 }
3241
3242 if (OpToFold) {
3243 Constant *C = GetSelectFoldableConstant(TVI);
3244 std::string Name = TVI->getName(); TVI->setName("");
3245 Instruction *NewSel =
3246 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3247 Name);
3248 InsertNewInstBefore(NewSel, SI);
3249 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3250 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3251 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3252 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3253 else {
3254 assert(0 && "Unknown instruction!!");
3255 }
3256 }
3257 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003258
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003259 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3260 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3261 !isa<Constant>(TrueVal))
3262 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3263 unsigned OpToFold = 0;
3264 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3265 OpToFold = 1;
3266 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3267 OpToFold = 2;
3268 }
3269
3270 if (OpToFold) {
3271 Constant *C = GetSelectFoldableConstant(FVI);
3272 std::string Name = FVI->getName(); FVI->setName("");
3273 Instruction *NewSel =
3274 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3275 Name);
3276 InsertNewInstBefore(NewSel, SI);
3277 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3278 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3279 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3280 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3281 else {
3282 assert(0 && "Unknown instruction!!");
3283 }
3284 }
3285 }
3286 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003287 return 0;
3288}
3289
3290
Chris Lattner970c33a2003-06-19 17:00:31 +00003291// CallInst simplification
3292//
3293Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003294 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3295 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00003296 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3297 bool Changed = false;
3298
3299 // memmove/cpy/set of zero bytes is a noop.
3300 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3301 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3302
3303 // FIXME: Increase alignment here.
3304
3305 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3306 if (CI->getRawValue() == 1) {
3307 // Replace the instruction with just byte operations. We would
3308 // transform other cases to loads/stores, but we don't know if
3309 // alignment is sufficient.
3310 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003311 }
3312
Chris Lattner00648e12004-10-12 04:52:52 +00003313 // If we have a memmove and the source operation is a constant global,
3314 // then the source and dest pointers can't alias, so we can change this
3315 // into a call to memcpy.
3316 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3317 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3318 if (GVSrc->isConstant()) {
3319 Module *M = CI.getParent()->getParent()->getParent();
3320 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3321 CI.getCalledFunction()->getFunctionType());
3322 CI.setOperand(0, MemCpy);
3323 Changed = true;
3324 }
3325
3326 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00003327 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
3328 // If this stoppoint is at the same source location as the previous
3329 // stoppoint in the chain, it is not needed.
3330 if (DbgStopPointInst *PrevSPI =
3331 dyn_cast<DbgStopPointInst>(SPI->getChain()))
3332 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
3333 SPI->getColNo() == PrevSPI->getColNo()) {
3334 SPI->replaceAllUsesWith(PrevSPI);
3335 return EraseInstFromFunction(CI);
3336 }
Chris Lattner00648e12004-10-12 04:52:52 +00003337 }
3338
Chris Lattneraec3d942003-10-07 22:32:43 +00003339 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003340}
3341
3342// InvokeInst simplification
3343//
3344Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003345 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003346}
3347
Chris Lattneraec3d942003-10-07 22:32:43 +00003348// visitCallSite - Improvements for call and invoke instructions.
3349//
3350Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003351 bool Changed = false;
3352
3353 // If the callee is a constexpr cast of a function, attempt to move the cast
3354 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003355 if (transformConstExprCastCall(CS)) return 0;
3356
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003357 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00003358
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003359 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3360 // This instruction is not reachable, just remove it. We insert a store to
3361 // undef so that we know that this code is not reachable, despite the fact
3362 // that we can't modify the CFG here.
3363 new StoreInst(ConstantBool::True,
3364 UndefValue::get(PointerType::get(Type::BoolTy)),
3365 CS.getInstruction());
3366
3367 if (!CS.getInstruction()->use_empty())
3368 CS.getInstruction()->
3369 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3370
3371 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3372 // Don't break the CFG, insert a dummy cond branch.
3373 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3374 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00003375 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003376 return EraseInstFromFunction(*CS.getInstruction());
3377 }
Chris Lattner81a7a232004-10-16 18:11:37 +00003378
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003379 const PointerType *PTy = cast<PointerType>(Callee->getType());
3380 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3381 if (FTy->isVarArg()) {
3382 // See if we can optimize any arguments passed through the varargs area of
3383 // the call.
3384 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3385 E = CS.arg_end(); I != E; ++I)
3386 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3387 // If this cast does not effect the value passed through the varargs
3388 // area, we can eliminate the use of the cast.
3389 Value *Op = CI->getOperand(0);
3390 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3391 *I = Op;
3392 Changed = true;
3393 }
3394 }
3395 }
Chris Lattneraec3d942003-10-07 22:32:43 +00003396
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003397 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00003398}
3399
Chris Lattner970c33a2003-06-19 17:00:31 +00003400// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3401// attempt to move the cast to the arguments of the call/invoke.
3402//
3403bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3404 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3405 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00003406 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00003407 return false;
Reid Spencer87436872004-07-18 00:38:32 +00003408 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00003409 Instruction *Caller = CS.getInstruction();
3410
3411 // Okay, this is a cast from a function to a different type. Unless doing so
3412 // would cause a type conversion of one of our arguments, change this call to
3413 // be a direct call with arguments casted to the appropriate types.
3414 //
3415 const FunctionType *FT = Callee->getFunctionType();
3416 const Type *OldRetTy = Caller->getType();
3417
Chris Lattner1f7942f2004-01-14 06:06:08 +00003418 // Check to see if we are changing the return type...
3419 if (OldRetTy != FT->getReturnType()) {
3420 if (Callee->isExternal() &&
3421 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3422 !Caller->use_empty())
3423 return false; // Cannot transform this return value...
3424
3425 // If the callsite is an invoke instruction, and the return value is used by
3426 // a PHI node in a successor, we cannot change the return type of the call
3427 // because there is no place to put the cast instruction (without breaking
3428 // the critical edge). Bail out in this case.
3429 if (!Caller->use_empty())
3430 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3431 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3432 UI != E; ++UI)
3433 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3434 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003435 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00003436 return false;
3437 }
Chris Lattner970c33a2003-06-19 17:00:31 +00003438
3439 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3440 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3441
3442 CallSite::arg_iterator AI = CS.arg_begin();
3443 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3444 const Type *ParamTy = FT->getParamType(i);
3445 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3446 if (Callee->isExternal() && !isConvertible) return false;
3447 }
3448
3449 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3450 Callee->isExternal())
3451 return false; // Do not delete arguments unless we have a function body...
3452
3453 // Okay, we decided that this is a safe thing to do: go ahead and start
3454 // inserting cast instructions as necessary...
3455 std::vector<Value*> Args;
3456 Args.reserve(NumActualArgs);
3457
3458 AI = CS.arg_begin();
3459 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3460 const Type *ParamTy = FT->getParamType(i);
3461 if ((*AI)->getType() == ParamTy) {
3462 Args.push_back(*AI);
3463 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00003464 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3465 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00003466 }
3467 }
3468
3469 // If the function takes more arguments than the call was taking, add them
3470 // now...
3471 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3472 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3473
3474 // If we are removing arguments to the function, emit an obnoxious warning...
3475 if (FT->getNumParams() < NumActualArgs)
3476 if (!FT->isVarArg()) {
3477 std::cerr << "WARNING: While resolving call to function '"
3478 << Callee->getName() << "' arguments were dropped!\n";
3479 } else {
3480 // Add all of the arguments in their promoted form to the arg list...
3481 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3482 const Type *PTy = getPromotedType((*AI)->getType());
3483 if (PTy != (*AI)->getType()) {
3484 // Must promote to pass through va_arg area!
3485 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3486 InsertNewInstBefore(Cast, *Caller);
3487 Args.push_back(Cast);
3488 } else {
3489 Args.push_back(*AI);
3490 }
3491 }
3492 }
3493
3494 if (FT->getReturnType() == Type::VoidTy)
3495 Caller->setName(""); // Void type should not have a name...
3496
3497 Instruction *NC;
3498 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003499 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00003500 Args, Caller->getName(), Caller);
3501 } else {
3502 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3503 }
3504
3505 // Insert a cast of the return type as necessary...
3506 Value *NV = NC;
3507 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3508 if (NV->getType() != Type::VoidTy) {
3509 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00003510
3511 // If this is an invoke instruction, we should insert it after the first
3512 // non-phi, instruction in the normal successor block.
3513 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3514 BasicBlock::iterator I = II->getNormalDest()->begin();
3515 while (isa<PHINode>(I)) ++I;
3516 InsertNewInstBefore(NC, *I);
3517 } else {
3518 // Otherwise, it's a call, just insert cast right after the call instr
3519 InsertNewInstBefore(NC, *Caller);
3520 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003521 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00003522 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00003523 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00003524 }
3525 }
3526
3527 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3528 Caller->replaceAllUsesWith(NV);
3529 Caller->getParent()->getInstList().erase(Caller);
3530 removeFromWorkList(Caller);
3531 return true;
3532}
3533
3534
Chris Lattner7515cab2004-11-14 19:13:23 +00003535// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
3536// operator and they all are only used by the PHI, PHI together their
3537// inputs, and do the operation once, to the result of the PHI.
3538Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
3539 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
3540
3541 // Scan the instruction, looking for input operations that can be folded away.
3542 // If all input operands to the phi are the same instruction (e.g. a cast from
3543 // the same type or "+42") we can pull the operation through the PHI, reducing
3544 // code size and simplifying code.
3545 Constant *ConstantOp = 0;
3546 const Type *CastSrcTy = 0;
3547 if (isa<CastInst>(FirstInst)) {
3548 CastSrcTy = FirstInst->getOperand(0)->getType();
3549 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
3550 // Can fold binop or shift if the RHS is a constant.
3551 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
3552 if (ConstantOp == 0) return 0;
3553 } else {
3554 return 0; // Cannot fold this operation.
3555 }
3556
3557 // Check to see if all arguments are the same operation.
3558 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
3559 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
3560 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
3561 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
3562 return 0;
3563 if (CastSrcTy) {
3564 if (I->getOperand(0)->getType() != CastSrcTy)
3565 return 0; // Cast operation must match.
3566 } else if (I->getOperand(1) != ConstantOp) {
3567 return 0;
3568 }
3569 }
3570
3571 // Okay, they are all the same operation. Create a new PHI node of the
3572 // correct type, and PHI together all of the LHS's of the instructions.
3573 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
3574 PN.getName()+".in");
3575 NewPN->op_reserve(PN.getNumOperands());
Chris Lattner46dd5a62004-11-14 19:29:34 +00003576
3577 Value *InVal = FirstInst->getOperand(0);
3578 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00003579
3580 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00003581 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
3582 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
3583 if (NewInVal != InVal)
3584 InVal = 0;
3585 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
3586 }
3587
3588 Value *PhiVal;
3589 if (InVal) {
3590 // The new PHI unions all of the same values together. This is really
3591 // common, so we handle it intelligently here for compile-time speed.
3592 PhiVal = InVal;
3593 delete NewPN;
3594 } else {
3595 InsertNewInstBefore(NewPN, PN);
3596 PhiVal = NewPN;
3597 }
Chris Lattner7515cab2004-11-14 19:13:23 +00003598
3599 // Insert and return the new operation.
3600 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00003601 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00003602 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00003603 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00003604 else
3605 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00003606 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00003607}
Chris Lattner48a44f72002-05-02 17:06:02 +00003608
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003609// PHINode simplification
3610//
Chris Lattner113f4f42002-06-25 16:13:24 +00003611Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnere29d6342004-10-17 21:22:38 +00003612 if (Value *V = hasConstantValue(&PN)) {
3613 // If V is an instruction, we have to be certain that it dominates PN.
3614 // However, because we don't have dom info, we can't do a perfect job.
3615 if (Instruction *I = dyn_cast<Instruction>(V)) {
3616 // We know that the instruction dominates the PHI if there are no undef
3617 // values coming in.
Chris Lattner3b92f172004-10-18 01:48:31 +00003618 if (I->getParent() != &I->getParent()->getParent()->front() ||
3619 isa<InvokeInst>(I))
Chris Lattner107c15c2004-10-17 21:31:34 +00003620 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3621 if (isa<UndefValue>(PN.getIncomingValue(i))) {
3622 V = 0;
3623 break;
3624 }
Chris Lattnere29d6342004-10-17 21:22:38 +00003625 }
3626
3627 if (V)
3628 return ReplaceInstUsesWith(PN, V);
3629 }
Chris Lattner4db2d222004-02-16 05:07:08 +00003630
3631 // If the only user of this instruction is a cast instruction, and all of the
3632 // incoming values are constants, change this PHI to merge together the casted
3633 // constants.
3634 if (PN.hasOneUse())
3635 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3636 if (CI->getType() != PN.getType()) { // noop casts will be folded
3637 bool AllConstant = true;
3638 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3639 if (!isa<Constant>(PN.getIncomingValue(i))) {
3640 AllConstant = false;
3641 break;
3642 }
3643 if (AllConstant) {
3644 // Make a new PHI with all casted values.
3645 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3646 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3647 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3648 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3649 PN.getIncomingBlock(i));
3650 }
3651
3652 // Update the cast instruction.
3653 CI->setOperand(0, New);
3654 WorkList.push_back(CI); // revisit the cast instruction to fold.
3655 WorkList.push_back(New); // Make sure to revisit the new Phi
3656 return &PN; // PN is now dead!
3657 }
3658 }
Chris Lattner7515cab2004-11-14 19:13:23 +00003659
3660 // If all PHI operands are the same operation, pull them through the PHI,
3661 // reducing code size.
3662 if (isa<Instruction>(PN.getIncomingValue(0)) &&
3663 PN.getIncomingValue(0)->hasOneUse())
3664 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
3665 return Result;
3666
3667
Chris Lattner91daeb52003-12-19 05:58:40 +00003668 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003669}
3670
Chris Lattner69193f92004-04-05 01:30:19 +00003671static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3672 Instruction *InsertPoint,
3673 InstCombiner *IC) {
3674 unsigned PS = IC->getTargetData().getPointerSize();
3675 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00003676 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3677 // We must insert a cast to ensure we sign-extend.
3678 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3679 V->getName()), *InsertPoint);
3680 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3681 *InsertPoint);
3682}
3683
Chris Lattner48a44f72002-05-02 17:06:02 +00003684
Chris Lattner113f4f42002-06-25 16:13:24 +00003685Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003686 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00003687 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00003688 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003689 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00003690 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003691
Chris Lattner81a7a232004-10-16 18:11:37 +00003692 if (isa<UndefValue>(GEP.getOperand(0)))
3693 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
3694
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003695 bool HasZeroPointerIndex = false;
3696 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3697 HasZeroPointerIndex = C->isNullValue();
3698
3699 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00003700 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00003701
Chris Lattner69193f92004-04-05 01:30:19 +00003702 // Eliminate unneeded casts for indices.
3703 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00003704 gep_type_iterator GTI = gep_type_begin(GEP);
3705 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3706 if (isa<SequentialType>(*GTI)) {
3707 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3708 Value *Src = CI->getOperand(0);
3709 const Type *SrcTy = Src->getType();
3710 const Type *DestTy = CI->getType();
3711 if (Src->getType()->isInteger()) {
3712 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3713 // We can always eliminate a cast from ulong or long to the other.
3714 // We can always eliminate a cast from uint to int or the other on
3715 // 32-bit pointer platforms.
3716 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3717 MadeChange = true;
3718 GEP.setOperand(i, Src);
3719 }
3720 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3721 SrcTy->getPrimitiveSize() == 4) {
3722 // We can always eliminate a cast from int to [u]long. We can
3723 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3724 // pointer target.
3725 if (SrcTy->isSigned() ||
3726 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3727 MadeChange = true;
3728 GEP.setOperand(i, Src);
3729 }
Chris Lattner69193f92004-04-05 01:30:19 +00003730 }
3731 }
3732 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00003733 // If we are using a wider index than needed for this platform, shrink it
3734 // to what we need. If the incoming value needs a cast instruction,
3735 // insert it. This explicit cast can make subsequent optimizations more
3736 // obvious.
3737 Value *Op = GEP.getOperand(i);
3738 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003739 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00003740 GEP.setOperand(i, ConstantExpr::getCast(C,
3741 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003742 MadeChange = true;
3743 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00003744 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3745 Op->getName()), GEP);
3746 GEP.setOperand(i, Op);
3747 MadeChange = true;
3748 }
Chris Lattner44d0b952004-07-20 01:48:15 +00003749
3750 // If this is a constant idx, make sure to canonicalize it to be a signed
3751 // operand, otherwise CSE and other optimizations are pessimized.
3752 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3753 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3754 CUI->getType()->getSignedVersion()));
3755 MadeChange = true;
3756 }
Chris Lattner69193f92004-04-05 01:30:19 +00003757 }
3758 if (MadeChange) return &GEP;
3759
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003760 // Combine Indices - If the source pointer to this getelementptr instruction
3761 // is a getelementptr instruction, combine the indices of the two
3762 // getelementptr instructions into a single instruction.
3763 //
Chris Lattner57c67b02004-03-25 22:59:29 +00003764 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00003765 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003766 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00003767 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003768 if (CE->getOpcode() == Instruction::GetElementPtr)
3769 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3770 }
3771
3772 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003773 // Note that if our source is a gep chain itself that we wait for that
3774 // chain to be resolved before we perform this transformation. This
3775 // avoids us creating a TON of code in some cases.
3776 //
3777 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3778 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3779 return 0; // Wait until our source is folded to completion.
3780
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003781 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00003782
3783 // Find out whether the last index in the source GEP is a sequential idx.
3784 bool EndsWithSequential = false;
3785 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3786 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00003787 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00003788
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003789 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00003790 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00003791 // Replace: gep (gep %P, long B), long A, ...
3792 // With: T = long A+B; gep %P, T, ...
3793 //
Chris Lattner5f667a62004-05-07 22:09:22 +00003794 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00003795 if (SO1 == Constant::getNullValue(SO1->getType())) {
3796 Sum = GO1;
3797 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3798 Sum = SO1;
3799 } else {
3800 // If they aren't the same type, convert both to an integer of the
3801 // target's pointer size.
3802 if (SO1->getType() != GO1->getType()) {
3803 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3804 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3805 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3806 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3807 } else {
3808 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00003809 if (SO1->getType()->getPrimitiveSize() == PS) {
3810 // Convert GO1 to SO1's type.
3811 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3812
3813 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3814 // Convert SO1 to GO1's type.
3815 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3816 } else {
3817 const Type *PT = TD->getIntPtrType();
3818 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3819 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3820 }
3821 }
3822 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003823 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3824 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3825 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003826 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3827 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00003828 }
Chris Lattner69193f92004-04-05 01:30:19 +00003829 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003830
3831 // Recycle the GEP we already have if possible.
3832 if (SrcGEPOperands.size() == 2) {
3833 GEP.setOperand(0, SrcGEPOperands[0]);
3834 GEP.setOperand(1, Sum);
3835 return &GEP;
3836 } else {
3837 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3838 SrcGEPOperands.end()-1);
3839 Indices.push_back(Sum);
3840 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3841 }
Chris Lattner69193f92004-04-05 01:30:19 +00003842 } else if (isa<Constant>(*GEP.idx_begin()) &&
3843 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00003844 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003845 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00003846 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3847 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003848 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3849 }
3850
3851 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00003852 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003853
Chris Lattner5f667a62004-05-07 22:09:22 +00003854 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003855 // GEP of global variable. If all of the indices for this GEP are
3856 // constants, we can promote this to a constexpr instead of an instruction.
3857
3858 // Scan for nonconstants...
3859 std::vector<Constant*> Indices;
3860 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3861 for (; I != E && isa<Constant>(*I); ++I)
3862 Indices.push_back(cast<Constant>(*I));
3863
3864 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00003865 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003866
3867 // Replace all uses of the GEP with the new constexpr...
3868 return ReplaceInstUsesWith(GEP, CE);
3869 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003870 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003871 if (CE->getOpcode() == Instruction::Cast) {
3872 if (HasZeroPointerIndex) {
3873 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3874 // into : GEP [10 x ubyte]* X, long 0, ...
3875 //
3876 // This occurs when the program declares an array extern like "int X[];"
3877 //
3878 Constant *X = CE->getOperand(0);
3879 const PointerType *CPTy = cast<PointerType>(CE->getType());
3880 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3881 if (const ArrayType *XATy =
3882 dyn_cast<ArrayType>(XTy->getElementType()))
3883 if (const ArrayType *CATy =
3884 dyn_cast<ArrayType>(CPTy->getElementType()))
3885 if (CATy->getElementType() == XATy->getElementType()) {
3886 // At this point, we know that the cast source type is a pointer
3887 // to an array of the same type as the destination pointer
3888 // array. Because the array type is never stepped over (there
3889 // is a leading zero) we can fold the cast into this GEP.
3890 GEP.setOperand(0, X);
3891 return &GEP;
3892 }
Chris Lattner14f3cdc2004-11-27 17:55:46 +00003893 } else if (GEP.getNumOperands() == 2) {
3894 // Transform things like:
3895 // %t = getelementptr ubyte* cast ([2 x sbyte]* %str to ubyte*), uint %V
3896 // into: %t1 = getelementptr [2 x sbyte*]* %str, int 0, uint %V; cast
3897 Constant *X = CE->getOperand(0);
3898 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
3899 const Type *ResElTy =cast<PointerType>(CE->getType())->getElementType();
3900 if (isa<ArrayType>(SrcElTy) &&
3901 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
3902 TD->getTypeSize(ResElTy)) {
3903 Value *V = InsertNewInstBefore(
3904 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
3905 GEP.getOperand(1), GEP.getName()), GEP);
3906 return new CastInst(V, GEP.getType());
3907 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003908 }
3909 }
Chris Lattnerca081252001-12-14 16:52:21 +00003910 }
3911
Chris Lattnerca081252001-12-14 16:52:21 +00003912 return 0;
3913}
3914
Chris Lattner1085bdf2002-11-04 16:18:53 +00003915Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3916 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3917 if (AI.isArrayAllocation()) // Check C != 1
3918 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3919 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003920 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00003921
3922 // Create and insert the replacement instruction...
3923 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00003924 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003925 else {
3926 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00003927 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003928 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003929
3930 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003931
3932 // Scan to the end of the allocation instructions, to skip over a block of
3933 // allocas if possible...
3934 //
3935 BasicBlock::iterator It = New;
3936 while (isa<AllocationInst>(*It)) ++It;
3937
3938 // Now that I is pointing to the first non-allocation-inst in the block,
3939 // insert our getelementptr instruction...
3940 //
Chris Lattner69193f92004-04-05 01:30:19 +00003941 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003942 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3943
3944 // Now make everything use the getelementptr instead of the original
3945 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00003946 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00003947 } else if (isa<UndefValue>(AI.getArraySize())) {
3948 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003949 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003950
3951 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3952 // Note that we only do this for alloca's, because malloc should allocate and
3953 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00003954 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3955 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00003956 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3957
Chris Lattner1085bdf2002-11-04 16:18:53 +00003958 return 0;
3959}
3960
Chris Lattner8427bff2003-12-07 01:24:23 +00003961Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3962 Value *Op = FI.getOperand(0);
3963
3964 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3965 if (CastInst *CI = dyn_cast<CastInst>(Op))
3966 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3967 FI.setOperand(0, CI->getOperand(0));
3968 return &FI;
3969 }
3970
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003971 // free undef -> unreachable.
3972 if (isa<UndefValue>(Op)) {
3973 // Insert a new store to null because we cannot modify the CFG here.
3974 new StoreInst(ConstantBool::True,
3975 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
3976 return EraseInstFromFunction(FI);
3977 }
3978
Chris Lattnerf3a36602004-02-28 04:57:37 +00003979 // If we have 'free null' delete the instruction. This can happen in stl code
3980 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003981 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00003982 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00003983
Chris Lattner8427bff2003-12-07 01:24:23 +00003984 return 0;
3985}
3986
3987
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003988/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3989/// constantexpr, return the constant value being addressed by the constant
3990/// expression, or null if something is funny.
3991///
3992static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00003993 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003994 return 0; // Do not allow stepping over the value!
3995
3996 // Loop over all of the operands, tracking down which value we are
3997 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00003998 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3999 for (++I; I != E; ++I)
4000 if (const StructType *STy = dyn_cast<StructType>(*I)) {
4001 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
4002 assert(CU->getValue() < STy->getNumElements() &&
4003 "Struct index out of range!");
4004 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos83243722004-08-04 08:44:43 +00004005 C = CS->getOperand(CU->getValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004006 } else if (isa<ConstantAggregateZero>(C)) {
4007 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
Chris Lattner81a7a232004-10-16 18:11:37 +00004008 } else if (isa<UndefValue>(C)) {
4009 C = UndefValue::get(STy->getElementType(CU->getValue()));
Chris Lattnered79d8a2004-05-27 17:30:27 +00004010 } else {
4011 return 0;
4012 }
4013 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
4014 const ArrayType *ATy = cast<ArrayType>(*I);
4015 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
4016 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos83243722004-08-04 08:44:43 +00004017 C = CA->getOperand(CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004018 else if (isa<ConstantAggregateZero>(C))
4019 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00004020 else if (isa<UndefValue>(C))
4021 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004022 else
4023 return 0;
4024 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004025 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00004026 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004027 return C;
4028}
4029
Chris Lattner35e24772004-07-13 01:49:43 +00004030static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
4031 User *CI = cast<User>(LI.getOperand(0));
4032
4033 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
4034 if (const PointerType *SrcTy =
4035 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
4036 const Type *SrcPTy = SrcTy->getElementType();
4037 if (SrcPTy->isSized() && DestPTy->isSized() &&
4038 IC.getTargetData().getTypeSize(SrcPTy) ==
4039 IC.getTargetData().getTypeSize(DestPTy) &&
4040 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
4041 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
4042 // Okay, we are casting from one integer or pointer type to another of
4043 // the same size. Instead of casting the pointer before the load, cast
4044 // the result of the loaded value.
4045 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004046 CI->getName(),
4047 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00004048 // Now cast the result of the load.
4049 return new CastInst(NewLoad, LI.getType());
4050 }
4051 }
4052 return 0;
4053}
4054
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004055/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00004056/// from this value cannot trap. If it is not obviously safe to load from the
4057/// specified pointer, we do a quick local scan of the basic block containing
4058/// ScanFrom, to determine if the address is already accessed.
4059static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
4060 // If it is an alloca or global variable, it is always safe to load from.
4061 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
4062
4063 // Otherwise, be a little bit agressive by scanning the local block where we
4064 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004065 // from/to. If so, the previous load or store would have already trapped,
4066 // so there is no harm doing an extra load (also, CSE will later eliminate
4067 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00004068 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
4069
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004070 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00004071 --BBI;
4072
4073 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
4074 if (LI->getOperand(0) == V) return true;
4075 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
4076 if (SI->getOperand(1) == V) return true;
4077
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004078 }
Chris Lattnere6f13092004-09-19 19:18:10 +00004079 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004080}
4081
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004082Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
4083 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00004084
Chris Lattner81a7a232004-10-16 18:11:37 +00004085 if (Constant *C = dyn_cast<Constant>(Op)) {
4086 if ((C->isNullValue() || isa<UndefValue>(C)) &&
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004087 !LI.isVolatile()) { // load null/undef -> undef
4088 // Insert a new store to null instruction before the load to indicate that
4089 // this code is not reachable. We do this instead of inserting an
4090 // unreachable instruction directly because we cannot modify the CFG.
4091 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00004092 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004093 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004094
Chris Lattner81a7a232004-10-16 18:11:37 +00004095 // Instcombine load (constant global) into the value loaded.
4096 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
4097 if (GV->isConstant() && !GV->isExternal())
4098 return ReplaceInstUsesWith(LI, GV->getInitializer());
4099
4100 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
4101 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
4102 if (CE->getOpcode() == Instruction::GetElementPtr) {
4103 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
4104 if (GV->isConstant() && !GV->isExternal())
4105 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
4106 return ReplaceInstUsesWith(LI, V);
4107 } else if (CE->getOpcode() == Instruction::Cast) {
4108 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4109 return Res;
4110 }
4111 }
Chris Lattnere228ee52004-04-08 20:39:49 +00004112
4113 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00004114 if (CastInst *CI = dyn_cast<CastInst>(Op))
4115 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4116 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00004117
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004118 if (!LI.isVolatile() && Op->hasOneUse()) {
4119 // Change select and PHI nodes to select values instead of addresses: this
4120 // helps alias analysis out a lot, allows many others simplifications, and
4121 // exposes redundancy in the code.
4122 //
4123 // Note that we cannot do the transformation unless we know that the
4124 // introduced loads cannot trap! Something like this is valid as long as
4125 // the condition is always false: load (select bool %C, int* null, int* %G),
4126 // but it would not be valid if we transformed it to load from null
4127 // unconditionally.
4128 //
4129 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
4130 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00004131 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
4132 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004133 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00004134 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004135 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00004136 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004137 return new SelectInst(SI->getCondition(), V1, V2);
4138 }
4139
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00004140 // load (select (cond, null, P)) -> load P
4141 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
4142 if (C->isNullValue()) {
4143 LI.setOperand(0, SI->getOperand(2));
4144 return &LI;
4145 }
4146
4147 // load (select (cond, P, null)) -> load P
4148 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
4149 if (C->isNullValue()) {
4150 LI.setOperand(0, SI->getOperand(1));
4151 return &LI;
4152 }
4153
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004154 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
4155 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00004156 bool Safe = PN->getParent() == LI.getParent();
4157
4158 // Scan all of the instructions between the PHI and the load to make
4159 // sure there are no instructions that might possibly alter the value
4160 // loaded from the PHI.
4161 if (Safe) {
4162 BasicBlock::iterator I = &LI;
4163 for (--I; !isa<PHINode>(I); --I)
4164 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
4165 Safe = false;
4166 break;
4167 }
4168 }
4169
4170 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00004171 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00004172 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004173 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00004174
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004175 if (Safe) {
4176 // Create the PHI.
4177 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
4178 InsertNewInstBefore(NewPN, *PN);
4179 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
4180
4181 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4182 BasicBlock *BB = PN->getIncomingBlock(i);
4183 Value *&TheLoad = LoadMap[BB];
4184 if (TheLoad == 0) {
4185 Value *InVal = PN->getIncomingValue(i);
4186 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
4187 InVal->getName()+".val"),
4188 *BB->getTerminator());
4189 }
4190 NewPN->addIncoming(TheLoad, BB);
4191 }
4192 return ReplaceInstUsesWith(LI, NewPN);
4193 }
4194 }
4195 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004196 return 0;
4197}
4198
Chris Lattner9eef8a72003-06-04 04:46:00 +00004199Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
4200 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00004201 Value *X;
4202 BasicBlock *TrueDest;
4203 BasicBlock *FalseDest;
4204 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
4205 !isa<Constant>(X)) {
4206 // Swap Destinations and condition...
4207 BI.setCondition(X);
4208 BI.setSuccessor(0, FalseDest);
4209 BI.setSuccessor(1, TrueDest);
4210 return &BI;
4211 }
4212
4213 // Cannonicalize setne -> seteq
4214 Instruction::BinaryOps Op; Value *Y;
4215 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
4216 TrueDest, FalseDest)))
4217 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
4218 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
4219 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
4220 std::string Name = I->getName(); I->setName("");
4221 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
4222 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00004223 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00004224 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00004225 BI.setSuccessor(0, FalseDest);
4226 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004227 removeFromWorkList(I);
4228 I->getParent()->getInstList().erase(I);
4229 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00004230 return &BI;
4231 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00004232
Chris Lattner9eef8a72003-06-04 04:46:00 +00004233 return 0;
4234}
Chris Lattner1085bdf2002-11-04 16:18:53 +00004235
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004236Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4237 Value *Cond = SI.getCondition();
4238 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4239 if (I->getOpcode() == Instruction::Add)
4240 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4241 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4242 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00004243 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004244 AddRHS));
4245 SI.setOperand(0, I->getOperand(0));
4246 WorkList.push_back(I);
4247 return &SI;
4248 }
4249 }
4250 return 0;
4251}
4252
Chris Lattnerca081252001-12-14 16:52:21 +00004253
Chris Lattner99f48c62002-09-02 04:59:56 +00004254void InstCombiner::removeFromWorkList(Instruction *I) {
4255 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4256 WorkList.end());
4257}
4258
Chris Lattner39c98bb2004-12-08 23:43:58 +00004259
4260/// TryToSinkInstruction - Try to move the specified instruction from its
4261/// current block into the beginning of DestBlock, which can only happen if it's
4262/// safe to move the instruction past all of the instructions between it and the
4263/// end of its block.
4264static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
4265 assert(I->hasOneUse() && "Invariants didn't hold!");
4266
4267 // Cannot move control-flow-involving instructions.
4268 if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
4269
4270 // Do not sink alloca instructions out of the entry block.
4271 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
4272 return false;
4273
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00004274 // We can only sink load instructions if there is nothing between the load and
4275 // the end of block that could change the value.
4276 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4277 if (LI->isVolatile()) return false; // Don't sink volatile loads.
4278
4279 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
4280 Scan != E; ++Scan)
4281 if (Scan->mayWriteToMemory())
4282 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00004283 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00004284
4285 BasicBlock::iterator InsertPos = DestBlock->begin();
4286 while (isa<PHINode>(InsertPos)) ++InsertPos;
4287
4288 BasicBlock *SrcBlock = I->getParent();
4289 DestBlock->getInstList().splice(InsertPos, SrcBlock->getInstList(), I);
4290 ++NumSunkInst;
4291 return true;
4292}
4293
Chris Lattner113f4f42002-06-25 16:13:24 +00004294bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00004295 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004296 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00004297
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004298 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
4299 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00004300
Chris Lattnerca081252001-12-14 16:52:21 +00004301
4302 while (!WorkList.empty()) {
4303 Instruction *I = WorkList.back(); // Get an instruction from the worklist
4304 WorkList.pop_back();
4305
Misha Brukman632df282002-10-29 23:06:16 +00004306 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00004307 // Check to see if we can DIE the instruction...
4308 if (isInstructionTriviallyDead(I)) {
4309 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004310 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00004311 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00004312 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004313
4314 I->getParent()->getInstList().erase(I);
4315 removeFromWorkList(I);
4316 continue;
4317 }
Chris Lattner99f48c62002-09-02 04:59:56 +00004318
Misha Brukman632df282002-10-29 23:06:16 +00004319 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00004320 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00004321 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00004322 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00004323 cast<Constant>(Ptr)->isNullValue() &&
4324 !isa<ConstantPointerNull>(C) &&
4325 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00004326 // If this is a constant expr gep that is effectively computing an
4327 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
4328 bool isFoldableGEP = true;
4329 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
4330 if (!isa<ConstantInt>(I->getOperand(i)))
4331 isFoldableGEP = false;
4332 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00004333 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00004334 std::vector<Value*>(I->op_begin()+1, I->op_end()));
4335 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00004336 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00004337 C = ConstantExpr::getCast(C, I->getType());
4338 }
4339 }
4340
Chris Lattner99f48c62002-09-02 04:59:56 +00004341 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00004342 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00004343 ReplaceInstUsesWith(*I, C);
4344
Chris Lattner99f48c62002-09-02 04:59:56 +00004345 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004346 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00004347 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004348 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00004349 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004350
Chris Lattner39c98bb2004-12-08 23:43:58 +00004351 // See if we can trivially sink this instruction to a successor basic block.
4352 if (I->hasOneUse()) {
4353 BasicBlock *BB = I->getParent();
4354 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
4355 if (UserParent != BB) {
4356 bool UserIsSuccessor = false;
4357 // See if the user is one of our successors.
4358 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
4359 if (*SI == UserParent) {
4360 UserIsSuccessor = true;
4361 break;
4362 }
4363
4364 // If the user is one of our immediate successors, and if that successor
4365 // only has us as a predecessors (we'd have to split the critical edge
4366 // otherwise), we can keep going.
4367 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
4368 next(pred_begin(UserParent)) == pred_end(UserParent))
4369 // Okay, the CFG is simple enough, try to sink this instruction.
4370 Changed |= TryToSinkInstruction(I, UserParent);
4371 }
4372 }
4373
Chris Lattnerca081252001-12-14 16:52:21 +00004374 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004375 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00004376 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00004377 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00004378 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004379 DEBUG(std::cerr << "IC: Old = " << *I
4380 << " New = " << *Result);
4381
Chris Lattner396dbfe2004-06-09 05:08:07 +00004382 // Everything uses the new instruction now.
4383 I->replaceAllUsesWith(Result);
4384
4385 // Push the new instruction and any users onto the worklist.
4386 WorkList.push_back(Result);
4387 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004388
4389 // Move the name to the new instruction first...
4390 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00004391 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004392
4393 // Insert the new instruction into the basic block...
4394 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00004395 BasicBlock::iterator InsertPos = I;
4396
4397 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
4398 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
4399 ++InsertPos;
4400
4401 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004402
Chris Lattner63d75af2004-05-01 23:27:23 +00004403 // Make sure that we reprocess all operands now that we reduced their
4404 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004405 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4406 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4407 WorkList.push_back(OpI);
4408
Chris Lattner396dbfe2004-06-09 05:08:07 +00004409 // Instructions can end up on the worklist more than once. Make sure
4410 // we do not process an instruction that has been deleted.
4411 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004412
4413 // Erase the old instruction.
4414 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004415 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004416 DEBUG(std::cerr << "IC: MOD = " << *I);
4417
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004418 // If the instruction was modified, it's possible that it is now dead.
4419 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00004420 if (isInstructionTriviallyDead(I)) {
4421 // Make sure we process all operands now that we are reducing their
4422 // use counts.
4423 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4424 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4425 WorkList.push_back(OpI);
4426
4427 // Instructions may end up in the worklist more than once. Erase all
4428 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00004429 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00004430 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00004431 } else {
4432 WorkList.push_back(Result);
4433 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004434 }
Chris Lattner053c0932002-05-14 15:24:07 +00004435 }
Chris Lattner260ab202002-04-18 17:39:14 +00004436 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00004437 }
4438 }
4439
Chris Lattner260ab202002-04-18 17:39:14 +00004440 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00004441}
4442
Brian Gaeke38b79e82004-07-27 17:43:21 +00004443FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00004444 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00004445}
Brian Gaeke960707c2003-11-11 22:41:34 +00004446