blob: 2a54366728a7dec0cb0e24f31ad1d5bcf747bf86 [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 Lattner0798af32005-01-13 20:14:25 +0000119 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
120 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000121 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000122 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000123 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
124 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000125 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000126 Instruction *visitCallInst(CallInst &CI);
127 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000128 Instruction *visitPHINode(PHINode &PN);
129 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000130 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000131 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000132 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000133 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000134 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000135 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000136
137 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000138 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000139
Chris Lattner970c33a2003-06-19 17:00:31 +0000140 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000141 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000142 bool transformConstExprCastCall(CallSite CS);
143
Chris Lattner69193f92004-04-05 01:30:19 +0000144 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000145 // InsertNewInstBefore - insert an instruction New before instruction Old
146 // in the program. Add the new instruction to the worklist.
147 //
Chris Lattner623826c2004-09-28 21:48:02 +0000148 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000149 assert(New && New->getParent() == 0 &&
150 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000151 BasicBlock *BB = Old.getParent();
152 BB->getInstList().insert(&Old, New); // Insert inst
153 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000154 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000155 }
156
Chris Lattner7e794272004-09-24 15:21:34 +0000157 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
158 /// This also adds the cast to the worklist. Finally, this returns the
159 /// cast.
160 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
161 if (V->getType() == Ty) return V;
162
163 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
164 WorkList.push_back(C);
165 return C;
166 }
167
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000168 // ReplaceInstUsesWith - This method is to be used when an instruction is
169 // found to be dead, replacable with another preexisting expression. Here
170 // we add all uses of I to the worklist, replace all uses of I with the new
171 // value, then return I, so that the inst combiner will know that I was
172 // modified.
173 //
174 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000175 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000176 if (&I != V) {
177 I.replaceAllUsesWith(V);
178 return &I;
179 } else {
180 // If we are replacing the instruction with itself, this must be in a
181 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000182 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000183 return &I;
184 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000185 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000186
187 // EraseInstFromFunction - When dealing with an instruction that has side
188 // effects or produces a void value, we can't rely on DCE to delete the
189 // instruction. Instead, visit methods should return the value returned by
190 // this function.
191 Instruction *EraseInstFromFunction(Instruction &I) {
192 assert(I.use_empty() && "Cannot erase instruction that is used!");
193 AddUsesToWorkList(I);
194 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000195 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000196 return 0; // Don't do anything with FI
197 }
198
199
Chris Lattner3ac7c262003-08-13 20:16:26 +0000200 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000201 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
202 /// InsertBefore instruction. This is specialized a bit to avoid inserting
203 /// casts that are known to not do anything...
204 ///
205 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
206 Instruction *InsertBefore);
207
Chris Lattner7fb29e12003-03-11 00:12:48 +0000208 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000209 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000210 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000211
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000212
213 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
214 // PHI node as operand #0, see if we can fold the instruction into the PHI
215 // (which is only possible if all operands to the PHI are constants).
216 Instruction *FoldOpIntoPhi(Instruction &I);
217
Chris Lattner7515cab2004-11-14 19:13:23 +0000218 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
219 // operator and they all are only used by the PHI, PHI together their
220 // inputs, and do the operation once, to the result of the PHI.
221 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
222
Chris Lattnerba1cb382003-09-19 17:17:26 +0000223 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
224 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000225
226 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
227 bool Inside, Instruction &IB);
Chris Lattner260ab202002-04-18 17:39:14 +0000228 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000229
Chris Lattnerc8b70922002-07-26 21:12:46 +0000230 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000231}
232
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000233// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000234// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000235static unsigned getComplexity(Value *V) {
236 if (isa<Instruction>(V)) {
237 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000238 return 3;
239 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000240 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000241 if (isa<Argument>(V)) return 3;
242 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000243}
Chris Lattner260ab202002-04-18 17:39:14 +0000244
Chris Lattner7fb29e12003-03-11 00:12:48 +0000245// isOnlyUse - Return true if this instruction will be deleted if we stop using
246// it.
247static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000248 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000249}
250
Chris Lattnere79e8542004-02-23 06:38:22 +0000251// getPromotedType - Return the specified type promoted as it would be to pass
252// though a va_arg area...
253static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000254 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000255 case Type::SByteTyID:
256 case Type::ShortTyID: return Type::IntTy;
257 case Type::UByteTyID:
258 case Type::UShortTyID: return Type::UIntTy;
259 case Type::FloatTyID: return Type::DoubleTy;
260 default: return Ty;
261 }
262}
263
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000264// SimplifyCommutative - This performs a few simplifications for commutative
265// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000266//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000267// 1. Order operands such that they are listed from right (least complex) to
268// left (most complex). This puts constants before unary operators before
269// binary operators.
270//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000271// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
272// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000273//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000274bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000275 bool Changed = false;
276 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
277 Changed = !I.swapOperands();
278
279 if (!I.isAssociative()) return Changed;
280 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000281 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
282 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
283 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000284 Constant *Folded = ConstantExpr::get(I.getOpcode(),
285 cast<Constant>(I.getOperand(1)),
286 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000287 I.setOperand(0, Op->getOperand(0));
288 I.setOperand(1, Folded);
289 return true;
290 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
291 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
292 isOnlyUse(Op) && isOnlyUse(Op1)) {
293 Constant *C1 = cast<Constant>(Op->getOperand(1));
294 Constant *C2 = cast<Constant>(Op1->getOperand(1));
295
296 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000297 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000298 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
299 Op1->getOperand(0),
300 Op1->getName(), &I);
301 WorkList.push_back(New);
302 I.setOperand(0, New);
303 I.setOperand(1, Folded);
304 return true;
305 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000306 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000307 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000308}
Chris Lattnerca081252001-12-14 16:52:21 +0000309
Chris Lattnerbb74e222003-03-10 23:06:50 +0000310// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
311// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000312//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000313static inline Value *dyn_castNegVal(Value *V) {
314 if (BinaryOperator::isNeg(V))
315 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
316
Chris Lattner9ad0d552004-12-14 20:08:06 +0000317 // Constants can be considered to be negated values if they can be folded.
318 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
319 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000320 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000321}
322
Chris Lattnerbb74e222003-03-10 23:06:50 +0000323static inline Value *dyn_castNotVal(Value *V) {
324 if (BinaryOperator::isNot(V))
325 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
326
327 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000328 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000329 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000330 return 0;
331}
332
Chris Lattner7fb29e12003-03-11 00:12:48 +0000333// dyn_castFoldableMul - If this value is a multiply that can be folded into
334// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000335// non-constant operand of the multiply, and set CST to point to the multiplier.
336// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000337//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000338static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000339 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000340 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000341 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000342 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000343 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000344 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000345 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000346 // The multiplier is really 1 << CST.
347 Constant *One = ConstantInt::get(V->getType(), 1);
348 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
349 return I->getOperand(0);
350 }
351 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000352 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000353}
Chris Lattner31ae8632002-08-14 17:51:49 +0000354
Chris Lattner0798af32005-01-13 20:14:25 +0000355/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
356/// expression, return it.
357static User *dyn_castGetElementPtr(Value *V) {
358 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
359 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
360 if (CE->getOpcode() == Instruction::GetElementPtr)
361 return cast<User>(V);
362 return false;
363}
364
Chris Lattner3082c5a2003-02-18 19:28:33 +0000365// Log2 - Calculate the log base 2 for the specified value if it is exactly a
366// power of 2.
367static unsigned Log2(uint64_t Val) {
368 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
369 unsigned Count = 0;
370 while (Val != 1) {
371 if (Val & 1) return 0; // Multiple bits set?
372 Val >>= 1;
373 ++Count;
374 }
375 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000376}
377
Chris Lattner623826c2004-09-28 21:48:02 +0000378// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000379static ConstantInt *AddOne(ConstantInt *C) {
380 return cast<ConstantInt>(ConstantExpr::getAdd(C,
381 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000382}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000383static ConstantInt *SubOne(ConstantInt *C) {
384 return cast<ConstantInt>(ConstantExpr::getSub(C,
385 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000386}
387
388// isTrueWhenEqual - Return true if the specified setcondinst instruction is
389// true when both operands are equal...
390//
391static bool isTrueWhenEqual(Instruction &I) {
392 return I.getOpcode() == Instruction::SetEQ ||
393 I.getOpcode() == Instruction::SetGE ||
394 I.getOpcode() == Instruction::SetLE;
395}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000396
397/// AssociativeOpt - Perform an optimization on an associative operator. This
398/// function is designed to check a chain of associative operators for a
399/// potential to apply a certain optimization. Since the optimization may be
400/// applicable if the expression was reassociated, this checks the chain, then
401/// reassociates the expression as necessary to expose the optimization
402/// opportunity. This makes use of a special Functor, which must define
403/// 'shouldApply' and 'apply' methods.
404///
405template<typename Functor>
406Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
407 unsigned Opcode = Root.getOpcode();
408 Value *LHS = Root.getOperand(0);
409
410 // Quick check, see if the immediate LHS matches...
411 if (F.shouldApply(LHS))
412 return F.apply(Root);
413
414 // Otherwise, if the LHS is not of the same opcode as the root, return.
415 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000416 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000417 // Should we apply this transform to the RHS?
418 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
419
420 // If not to the RHS, check to see if we should apply to the LHS...
421 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
422 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
423 ShouldApply = true;
424 }
425
426 // If the functor wants to apply the optimization to the RHS of LHSI,
427 // reassociate the expression from ((? op A) op B) to (? op (A op B))
428 if (ShouldApply) {
429 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000430
431 // Now all of the instructions are in the current basic block, go ahead
432 // and perform the reassociation.
433 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
434
435 // First move the selected RHS to the LHS of the root...
436 Root.setOperand(0, LHSI->getOperand(1));
437
438 // Make what used to be the LHS of the root be the user of the root...
439 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000440 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000441 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
442 return 0;
443 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000444 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000445 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000446 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
447 BasicBlock::iterator ARI = &Root; ++ARI;
448 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
449 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000450
451 // Now propagate the ExtraOperand down the chain of instructions until we
452 // get to LHSI.
453 while (TmpLHSI != LHSI) {
454 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000455 // Move the instruction to immediately before the chain we are
456 // constructing to avoid breaking dominance properties.
457 NextLHSI->getParent()->getInstList().remove(NextLHSI);
458 BB->getInstList().insert(ARI, NextLHSI);
459 ARI = NextLHSI;
460
Chris Lattnerb8b97502003-08-13 19:01:45 +0000461 Value *NextOp = NextLHSI->getOperand(1);
462 NextLHSI->setOperand(1, ExtraOperand);
463 TmpLHSI = NextLHSI;
464 ExtraOperand = NextOp;
465 }
466
467 // Now that the instructions are reassociated, have the functor perform
468 // the transformation...
469 return F.apply(Root);
470 }
471
472 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
473 }
474 return 0;
475}
476
477
478// AddRHS - Implements: X + X --> X << 1
479struct AddRHS {
480 Value *RHS;
481 AddRHS(Value *rhs) : RHS(rhs) {}
482 bool shouldApply(Value *LHS) const { return LHS == RHS; }
483 Instruction *apply(BinaryOperator &Add) const {
484 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
485 ConstantInt::get(Type::UByteTy, 1));
486 }
487};
488
489// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
490// iff C1&C2 == 0
491struct AddMaskingAnd {
492 Constant *C2;
493 AddMaskingAnd(Constant *c) : C2(c) {}
494 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000495 ConstantInt *C1;
496 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
497 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000498 }
499 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000500 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000501 }
502};
503
Chris Lattner86102b82005-01-01 16:22:27 +0000504static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000505 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +0000506 if (isa<CastInst>(I)) {
507 if (Constant *SOC = dyn_cast<Constant>(SO))
508 return ConstantExpr::getCast(SOC, I.getType());
509
510 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
511 SO->getName() + ".cast"), I);
512 }
513
Chris Lattner183b3362004-04-09 19:05:30 +0000514 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000515 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
516 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000517
Chris Lattner183b3362004-04-09 19:05:30 +0000518 if (Constant *SOC = dyn_cast<Constant>(SO)) {
519 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +0000520 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
521 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000522 }
523
524 Value *Op0 = SO, *Op1 = ConstOperand;
525 if (!ConstIsRHS)
526 std::swap(Op0, Op1);
527 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +0000528 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
529 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
530 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
531 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000532 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000533 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000534 abort();
535 }
Chris Lattner86102b82005-01-01 16:22:27 +0000536 return IC->InsertNewInstBefore(New, I);
537}
538
539// FoldOpIntoSelect - Given an instruction with a select as one operand and a
540// constant as the other operand, try to fold the binary operator into the
541// select arguments. This also works for Cast instructions, which obviously do
542// not have a second operand.
543static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
544 InstCombiner *IC) {
545 // Don't modify shared select instructions
546 if (!SI->hasOneUse()) return 0;
547 Value *TV = SI->getOperand(1);
548 Value *FV = SI->getOperand(2);
549
550 if (isa<Constant>(TV) || isa<Constant>(FV)) {
551 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
552 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
553
554 return new SelectInst(SI->getCondition(), SelectTrueVal,
555 SelectFalseVal);
556 }
557 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +0000558}
559
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000560
561/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
562/// node as operand #0, see if we can fold the instruction into the PHI (which
563/// is only possible if all operands to the PHI are constants).
564Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
565 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000566 unsigned NumPHIValues = PN->getNumIncomingValues();
567 if (!PN->hasOneUse() || NumPHIValues == 0 ||
568 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000569
570 // Check to see if all of the operands of the PHI are constants. If not, we
571 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000572 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000573 if (!isa<Constant>(PN->getIncomingValue(i)))
574 return 0;
575
576 // Okay, we can do the transformation: create the new PHI node.
577 PHINode *NewPN = new PHINode(I.getType(), I.getName());
578 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +0000579 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000580 InsertNewInstBefore(NewPN, *PN);
581
582 // Next, add all of the operands to the PHI.
583 if (I.getNumOperands() == 2) {
584 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000585 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000586 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
587 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
588 PN->getIncomingBlock(i));
589 }
590 } else {
591 assert(isa<CastInst>(I) && "Unary op should be a cast!");
592 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000593 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000594 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
595 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
596 PN->getIncomingBlock(i));
597 }
598 }
599 return ReplaceInstUsesWith(I, NewPN);
600}
601
Chris Lattner113f4f42002-06-25 16:13:24 +0000602Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000603 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000604 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000605
Chris Lattnercf4a9962004-04-10 22:01:55 +0000606 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000607 // X + undef -> undef
608 if (isa<UndefValue>(RHS))
609 return ReplaceInstUsesWith(I, RHS);
610
Chris Lattnercf4a9962004-04-10 22:01:55 +0000611 // X + 0 --> X
612 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
613 RHSC->isNullValue())
614 return ReplaceInstUsesWith(I, LHS);
615
616 // X + (signbit) --> X ^ signbit
617 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
618 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
619 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattner33eb9092004-11-05 04:45:43 +0000620 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000621 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000622 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000623
624 if (isa<PHINode>(LHS))
625 if (Instruction *NV = FoldOpIntoPhi(I))
626 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000627 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000628
Chris Lattnerb8b97502003-08-13 19:01:45 +0000629 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000630 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000631 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +0000632
633 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
634 if (RHSI->getOpcode() == Instruction::Sub)
635 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
636 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
637 }
638 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
639 if (LHSI->getOpcode() == Instruction::Sub)
640 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
641 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
642 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000643 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000644
Chris Lattner147e9752002-05-08 22:46:53 +0000645 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000646 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000647 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000648
649 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000650 if (!isa<Constant>(RHS))
651 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000652 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000653
Chris Lattner47060462005-04-07 17:14:51 +0000654
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000655 ConstantInt *C2;
656 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
657 if (X == RHS) // X*C + X --> X * (C+1)
658 return BinaryOperator::createMul(RHS, AddOne(C2));
659
660 // X*C1 + X*C2 --> X * (C1+C2)
661 ConstantInt *C1;
662 if (X == dyn_castFoldableMul(RHS, C1))
663 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000664 }
665
666 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000667 if (dyn_castFoldableMul(RHS, C2) == LHS)
668 return BinaryOperator::createMul(LHS, AddOne(C2));
669
Chris Lattner57c8d992003-02-18 19:57:07 +0000670
Chris Lattnerb8b97502003-08-13 19:01:45 +0000671 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000672 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000673 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000674
Chris Lattnerb9cde762003-10-02 15:11:26 +0000675 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000676 Value *X;
677 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
678 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
679 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000680 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000681
Chris Lattnerbff91d92004-10-08 05:07:56 +0000682 // (X & FF00) + xx00 -> (X+xx00) & FF00
683 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
684 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
685 if (Anded == CRHS) {
686 // See if all bits from the first bit set in the Add RHS up are included
687 // in the mask. First, get the rightmost bit.
688 uint64_t AddRHSV = CRHS->getRawValue();
689
690 // Form a mask of all bits from the lowest bit added through the top.
691 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
692 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
693
694 // See if the and mask includes all of these bits.
695 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
696
697 if (AddRHSHighBits == AddRHSHighBitsAnd) {
698 // Okay, the xform is safe. Insert the new add pronto.
699 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
700 LHS->getName()), I);
701 return BinaryOperator::createAnd(NewAdd, C2);
702 }
703 }
704 }
705
Chris Lattnerd4252a72004-07-30 07:50:03 +0000706 // Try to fold constant add into select arguments.
707 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +0000708 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +0000709 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000710 }
711
Chris Lattner113f4f42002-06-25 16:13:24 +0000712 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000713}
714
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000715// isSignBit - Return true if the value represented by the constant only has the
716// highest order bit set.
717static bool isSignBit(ConstantInt *CI) {
718 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
719 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
720}
721
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000722static unsigned getTypeSizeInBits(const Type *Ty) {
723 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
724}
725
Chris Lattner022167f2004-03-13 00:11:49 +0000726/// RemoveNoopCast - Strip off nonconverting casts from the value.
727///
728static Value *RemoveNoopCast(Value *V) {
729 if (CastInst *CI = dyn_cast<CastInst>(V)) {
730 const Type *CTy = CI->getType();
731 const Type *OpTy = CI->getOperand(0)->getType();
732 if (CTy->isInteger() && OpTy->isInteger()) {
733 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
734 return RemoveNoopCast(CI->getOperand(0));
735 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
736 return RemoveNoopCast(CI->getOperand(0));
737 }
738 return V;
739}
740
Chris Lattner113f4f42002-06-25 16:13:24 +0000741Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000742 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000743
Chris Lattnere6794492002-08-12 21:17:25 +0000744 if (Op0 == Op1) // sub X, X -> 0
745 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000746
Chris Lattnere6794492002-08-12 21:17:25 +0000747 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000748 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000749 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000750
Chris Lattner81a7a232004-10-16 18:11:37 +0000751 if (isa<UndefValue>(Op0))
752 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
753 if (isa<UndefValue>(Op1))
754 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
755
Chris Lattner8f2f5982003-11-05 01:06:05 +0000756 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
757 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000758 if (C->isAllOnesValue())
759 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000760
Chris Lattner8f2f5982003-11-05 01:06:05 +0000761 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000762 Value *X;
763 if (match(Op1, m_Not(m_Value(X))))
764 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000765 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000766 // -((uint)X >> 31) -> ((int)X >> 31)
767 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000768 if (C->isNullValue()) {
769 Value *NoopCastedRHS = RemoveNoopCast(Op1);
770 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000771 if (SI->getOpcode() == Instruction::Shr)
772 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
773 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000774 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000775 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000776 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000777 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000778 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000779 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000780 // Ok, the transformation is safe. Insert a cast of the incoming
781 // value, then the new shift, then the new cast.
782 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
783 SI->getOperand(0)->getName());
784 Value *InV = InsertNewInstBefore(FirstCast, I);
785 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
786 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000787 if (NewShift->getType() == I.getType())
788 return NewShift;
789 else {
790 InV = InsertNewInstBefore(NewShift, I);
791 return new CastInst(NewShift, I.getType());
792 }
Chris Lattner92295c52004-03-12 23:53:13 +0000793 }
794 }
Chris Lattner022167f2004-03-13 00:11:49 +0000795 }
Chris Lattner183b3362004-04-09 19:05:30 +0000796
797 // Try to fold constant sub into select arguments.
798 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +0000799 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000800 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000801
802 if (isa<PHINode>(Op0))
803 if (Instruction *NV = FoldOpIntoPhi(I))
804 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000805 }
806
Chris Lattnera9be4492005-04-07 16:15:25 +0000807 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
808 if (Op1I->getOpcode() == Instruction::Add &&
809 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000810 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000811 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000812 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000813 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000814 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
815 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
816 // C1-(X+C2) --> (C1-C2)-X
817 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
818 Op1I->getOperand(0));
819 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000820 }
821
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000822 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000823 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
824 // is not used by anyone else...
825 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000826 if (Op1I->getOpcode() == Instruction::Sub &&
827 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000828 // Swap the two operands of the subexpr...
829 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
830 Op1I->setOperand(0, IIOp1);
831 Op1I->setOperand(1, IIOp0);
832
833 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000834 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000835 }
836
837 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
838 //
839 if (Op1I->getOpcode() == Instruction::And &&
840 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
841 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
842
Chris Lattner396dbfe2004-06-09 05:08:07 +0000843 Value *NewNot =
844 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000845 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000846 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000847
Chris Lattner0aee4b72004-10-06 15:08:25 +0000848 // -(X sdiv C) -> (X sdiv -C)
849 if (Op1I->getOpcode() == Instruction::Div)
850 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +0000851 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +0000852 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
853 return BinaryOperator::createDiv(Op1I->getOperand(0),
854 ConstantExpr::getNeg(DivRHS));
855
Chris Lattner57c8d992003-02-18 19:57:07 +0000856 // X - X*C --> X * (1-C)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000857 ConstantInt *C2;
858 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
859 Constant *CP1 =
860 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000861 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000862 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000863 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000864 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000865
Chris Lattner47060462005-04-07 17:14:51 +0000866 if (!Op0->getType()->isFloatingPoint())
867 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
868 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +0000869 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
870 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
871 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
872 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +0000873 } else if (Op0I->getOpcode() == Instruction::Sub) {
874 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
875 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +0000876 }
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000877
878 ConstantInt *C1;
879 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
880 if (X == Op1) { // X*C - X --> X * (C-1)
881 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
882 return BinaryOperator::createMul(Op1, CP1);
883 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000884
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000885 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
886 if (X == dyn_castFoldableMul(Op1, C2))
887 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
888 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000889 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000890}
891
Chris Lattnere79e8542004-02-23 06:38:22 +0000892/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
893/// really just returns true if the most significant (sign) bit is set.
894static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
895 if (RHS->getType()->isSigned()) {
896 // True if source is LHS < 0 or LHS <= -1
897 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
898 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
899 } else {
900 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
901 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
902 // the size of the integer type.
903 if (Opcode == Instruction::SetGE)
904 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
905 if (Opcode == Instruction::SetGT)
906 return RHSC->getValue() ==
907 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
908 }
909 return false;
910}
911
Chris Lattner113f4f42002-06-25 16:13:24 +0000912Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000913 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000914 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000915
Chris Lattner81a7a232004-10-16 18:11:37 +0000916 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
917 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
918
Chris Lattnere6794492002-08-12 21:17:25 +0000919 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000920 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
921 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000922
923 // ((X << C1)*C2) == (X * (C2 << C1))
924 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
925 if (SI->getOpcode() == Instruction::Shl)
926 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000927 return BinaryOperator::createMul(SI->getOperand(0),
928 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000929
Chris Lattnercce81be2003-09-11 22:24:54 +0000930 if (CI->isNullValue())
931 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
932 if (CI->equalsInt(1)) // X * 1 == X
933 return ReplaceInstUsesWith(I, Op0);
934 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000935 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000936
Chris Lattnercce81be2003-09-11 22:24:54 +0000937 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000938 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
939 return new ShiftInst(Instruction::Shl, Op0,
940 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000941 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000942 if (Op1F->isNullValue())
943 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000944
Chris Lattner3082c5a2003-02-18 19:28:33 +0000945 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
946 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
947 if (Op1F->getValue() == 1.0)
948 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
949 }
Chris Lattner183b3362004-04-09 19:05:30 +0000950
951 // Try to fold constant mul into select arguments.
952 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +0000953 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000954 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000955
956 if (isa<PHINode>(Op0))
957 if (Instruction *NV = FoldOpIntoPhi(I))
958 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000959 }
960
Chris Lattner934a64cf2003-03-10 23:23:04 +0000961 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
962 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000963 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000964
Chris Lattner2635b522004-02-23 05:39:21 +0000965 // If one of the operands of the multiply is a cast from a boolean value, then
966 // we know the bool is either zero or one, so this is a 'masking' multiply.
967 // See if we can simplify things based on how the boolean was originally
968 // formed.
969 CastInst *BoolCast = 0;
970 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
971 if (CI->getOperand(0)->getType() == Type::BoolTy)
972 BoolCast = CI;
973 if (!BoolCast)
974 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
975 if (CI->getOperand(0)->getType() == Type::BoolTy)
976 BoolCast = CI;
977 if (BoolCast) {
978 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
979 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
980 const Type *SCOpTy = SCIOp0->getType();
981
Chris Lattnere79e8542004-02-23 06:38:22 +0000982 // If the setcc is true iff the sign bit of X is set, then convert this
983 // multiply into a shift/and combination.
984 if (isa<ConstantInt>(SCIOp1) &&
985 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000986 // Shift the X value right to turn it into "all signbits".
987 Constant *Amt = ConstantUInt::get(Type::UByteTy,
988 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000989 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000990 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000991 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
992 SCIOp0->getName()), I);
993 }
994
995 Value *V =
996 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
997 BoolCast->getOperand(0)->getName()+
998 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000999
1000 // If the multiply type is not the same as the source type, sign extend
1001 // or truncate to the multiply type.
1002 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001003 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +00001004
1005 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001006 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001007 }
1008 }
1009 }
1010
Chris Lattner113f4f42002-06-25 16:13:24 +00001011 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001012}
1013
Chris Lattner113f4f42002-06-25 16:13:24 +00001014Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001015 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001016
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001017 if (isa<UndefValue>(Op0)) // undef / X -> 0
1018 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1019 if (isa<UndefValue>(Op1))
1020 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1021
1022 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001023 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001024 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001025 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001026
Chris Lattnere20c3342004-04-26 14:01:59 +00001027 // div X, -1 == -X
1028 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001029 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001030
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001031 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001032 if (LHS->getOpcode() == Instruction::Div)
1033 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001034 // (X / C1) / C2 -> X / (C1*C2)
1035 return BinaryOperator::createDiv(LHS->getOperand(0),
1036 ConstantExpr::getMul(RHS, LHSRHS));
1037 }
1038
Chris Lattner3082c5a2003-02-18 19:28:33 +00001039 // Check to see if this is an unsigned division with an exact power of 2,
1040 // if so, convert to a right shift.
1041 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1042 if (uint64_t Val = C->getValue()) // Don't break X / 0
1043 if (uint64_t C = Log2(Val))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001044 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001045 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001046
Chris Lattner4ad08352004-10-09 02:50:40 +00001047 // -X/C -> X/-C
1048 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001049 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001050 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1051
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001052 if (!RHS->isNullValue()) {
1053 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001054 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001055 return R;
1056 if (isa<PHINode>(Op0))
1057 if (Instruction *NV = FoldOpIntoPhi(I))
1058 return NV;
1059 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001060 }
1061
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001062 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1063 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1064 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1065 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1066 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1067 if (STO->getValue() == 0) { // Couldn't be this argument.
1068 I.setOperand(1, SFO);
1069 return &I;
1070 } else if (SFO->getValue() == 0) {
1071 I.setOperand(1, STO);
1072 return &I;
1073 }
1074
1075 if (uint64_t TSA = Log2(STO->getValue()))
1076 if (uint64_t FSA = Log2(SFO->getValue())) {
1077 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1078 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1079 TC, SI->getName()+".t");
1080 TSI = InsertNewInstBefore(TSI, I);
1081
1082 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1083 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1084 FC, SI->getName()+".f");
1085 FSI = InsertNewInstBefore(FSI, I);
1086 return new SelectInst(SI->getOperand(0), TSI, FSI);
1087 }
1088 }
1089
Chris Lattner3082c5a2003-02-18 19:28:33 +00001090 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001091 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001092 if (LHS->equalsInt(0))
1093 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1094
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001095 return 0;
1096}
1097
1098
Chris Lattner113f4f42002-06-25 16:13:24 +00001099Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001100 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner7fd5f072004-07-06 07:01:22 +00001101 if (I.getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001102 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001103 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001104 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001105 // X % -Y -> X % Y
1106 AddUsesToWorkList(I);
1107 I.setOperand(1, RHSNeg);
1108 return &I;
1109 }
1110
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001111 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001112 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001113 if (isa<UndefValue>(Op1))
1114 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001115
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001116 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001117 if (RHS->equalsInt(1)) // X % 1 == 0
1118 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1119
1120 // Check to see if this is an unsigned remainder with an exact power of 2,
1121 // if so, convert to a bitwise and.
1122 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1123 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001124 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001125 return BinaryOperator::createAnd(Op0,
1126 ConstantUInt::get(I.getType(), Val-1));
1127
1128 if (!RHS->isNullValue()) {
1129 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001130 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001131 return R;
1132 if (isa<PHINode>(Op0))
1133 if (Instruction *NV = FoldOpIntoPhi(I))
1134 return NV;
1135 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001136 }
1137
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001138 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1139 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1140 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1141 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1142 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1143 if (STO->getValue() == 0) { // Couldn't be this argument.
1144 I.setOperand(1, SFO);
1145 return &I;
1146 } else if (SFO->getValue() == 0) {
1147 I.setOperand(1, STO);
1148 return &I;
1149 }
1150
1151 if (!(STO->getValue() & (STO->getValue()-1)) &&
1152 !(SFO->getValue() & (SFO->getValue()-1))) {
1153 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1154 SubOne(STO), SI->getName()+".t"), I);
1155 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1156 SubOne(SFO), SI->getName()+".f"), I);
1157 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1158 }
1159 }
1160
Chris Lattner3082c5a2003-02-18 19:28:33 +00001161 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001162 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001163 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001164 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1165
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001166 return 0;
1167}
1168
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001169// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001170static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001171 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1172 // Calculate -1 casted to the right type...
1173 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1174 uint64_t Val = ~0ULL; // All ones
1175 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1176 return CU->getValue() == Val-1;
1177 }
1178
1179 const ConstantSInt *CS = cast<ConstantSInt>(C);
1180
1181 // Calculate 0111111111..11111
1182 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1183 int64_t Val = INT64_MAX; // All ones
1184 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1185 return CS->getValue() == Val-1;
1186}
1187
1188// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001189static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001190 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1191 return CU->getValue() == 1;
1192
1193 const ConstantSInt *CS = cast<ConstantSInt>(C);
1194
1195 // Calculate 1111111111000000000000
1196 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1197 int64_t Val = -1; // All ones
1198 Val <<= TypeBits-1; // Shift over to the right spot
1199 return CS->getValue() == Val+1;
1200}
1201
Chris Lattner35167c32004-06-09 07:59:58 +00001202// isOneBitSet - Return true if there is exactly one bit set in the specified
1203// constant.
1204static bool isOneBitSet(const ConstantInt *CI) {
1205 uint64_t V = CI->getRawValue();
1206 return V && (V & (V-1)) == 0;
1207}
1208
Chris Lattner8fc5af42004-09-23 21:46:38 +00001209#if 0 // Currently unused
1210// isLowOnes - Return true if the constant is of the form 0+1+.
1211static bool isLowOnes(const ConstantInt *CI) {
1212 uint64_t V = CI->getRawValue();
1213
1214 // There won't be bits set in parts that the type doesn't contain.
1215 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1216
1217 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1218 return U && V && (U & V) == 0;
1219}
1220#endif
1221
1222// isHighOnes - Return true if the constant is of the form 1+0+.
1223// This is the same as lowones(~X).
1224static bool isHighOnes(const ConstantInt *CI) {
1225 uint64_t V = ~CI->getRawValue();
1226
1227 // There won't be bits set in parts that the type doesn't contain.
1228 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1229
1230 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1231 return U && V && (U & V) == 0;
1232}
1233
1234
Chris Lattner3ac7c262003-08-13 20:16:26 +00001235/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1236/// are carefully arranged to allow folding of expressions such as:
1237///
1238/// (A < B) | (A > B) --> (A != B)
1239///
1240/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1241/// represents that the comparison is true if A == B, and bit value '1' is true
1242/// if A < B.
1243///
1244static unsigned getSetCondCode(const SetCondInst *SCI) {
1245 switch (SCI->getOpcode()) {
1246 // False -> 0
1247 case Instruction::SetGT: return 1;
1248 case Instruction::SetEQ: return 2;
1249 case Instruction::SetGE: return 3;
1250 case Instruction::SetLT: return 4;
1251 case Instruction::SetNE: return 5;
1252 case Instruction::SetLE: return 6;
1253 // True -> 7
1254 default:
1255 assert(0 && "Invalid SetCC opcode!");
1256 return 0;
1257 }
1258}
1259
1260/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1261/// opcode and two operands into either a constant true or false, or a brand new
1262/// SetCC instruction.
1263static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1264 switch (Opcode) {
1265 case 0: return ConstantBool::False;
1266 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1267 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1268 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1269 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1270 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1271 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1272 case 7: return ConstantBool::True;
1273 default: assert(0 && "Illegal SetCCCode!"); return 0;
1274 }
1275}
1276
1277// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1278struct FoldSetCCLogical {
1279 InstCombiner &IC;
1280 Value *LHS, *RHS;
1281 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1282 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1283 bool shouldApply(Value *V) const {
1284 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1285 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1286 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1287 return false;
1288 }
1289 Instruction *apply(BinaryOperator &Log) const {
1290 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1291 if (SCI->getOperand(0) != LHS) {
1292 assert(SCI->getOperand(1) == LHS);
1293 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1294 }
1295
1296 unsigned LHSCode = getSetCondCode(SCI);
1297 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1298 unsigned Code;
1299 switch (Log.getOpcode()) {
1300 case Instruction::And: Code = LHSCode & RHSCode; break;
1301 case Instruction::Or: Code = LHSCode | RHSCode; break;
1302 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001303 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001304 }
1305
1306 Value *RV = getSetCCValue(Code, LHS, RHS);
1307 if (Instruction *I = dyn_cast<Instruction>(RV))
1308 return I;
1309 // Otherwise, it's a constant boolean value...
1310 return IC.ReplaceInstUsesWith(Log, RV);
1311 }
1312};
1313
1314
Chris Lattner86102b82005-01-01 16:22:27 +00001315/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1316/// this predicate to simplify operations downstream. V and Mask are known to
1317/// be the same type.
1318static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
1319 if (isa<UndefValue>(V) || Mask->isNullValue())
1320 return true;
1321 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
1322 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
1323
1324 if (Instruction *I = dyn_cast<Instruction>(V)) {
1325 switch (I->getOpcode()) {
1326 case Instruction::And:
1327 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
1328 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
1329 if (ConstantExpr::getAnd(CI, Mask)->isNullValue())
1330 return true;
1331 break;
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001332 case Instruction::Or:
1333 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
1334 return MaskedValueIsZero(I->getOperand(1), Mask) &&
1335 MaskedValueIsZero(I->getOperand(0), Mask);
1336 case Instruction::Select:
1337 // If the T and F values are MaskedValueIsZero, the result is also zero.
1338 return MaskedValueIsZero(I->getOperand(2), Mask) &&
1339 MaskedValueIsZero(I->getOperand(1), Mask);
Chris Lattner86102b82005-01-01 16:22:27 +00001340 case Instruction::Cast: {
1341 const Type *SrcTy = I->getOperand(0)->getType();
1342 if (SrcTy->isIntegral()) {
1343 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
1344 if (SrcTy->isUnsigned() && // Only handle zero ext.
1345 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
1346 return true;
1347
1348 // If this is a noop cast, recurse.
1349 if (SrcTy != Type::BoolTy)
1350 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() ==I->getType()) ||
1351 SrcTy->getSignedVersion() == I->getType()) {
1352 Constant *NewMask =
1353 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
1354 return MaskedValueIsZero(I->getOperand(0),
1355 cast<ConstantIntegral>(NewMask));
1356 }
1357 }
1358 break;
1359 }
1360 case Instruction::Shl:
1361 // (shl X, C1) & C2 == 0 iff (-1 << C1) & C2 == 0
1362 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1363 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1364 C1 = ConstantExpr::getShl(C1, SA);
1365 C1 = ConstantExpr::getAnd(C1, Mask);
1366 if (C1->isNullValue())
1367 return true;
1368 }
1369 break;
1370 case Instruction::Shr:
1371 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1372 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1373 if (I->getType()->isUnsigned()) {
1374 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1375 C1 = ConstantExpr::getShr(C1, SA);
1376 C1 = ConstantExpr::getAnd(C1, Mask);
1377 if (C1->isNullValue())
1378 return true;
1379 }
1380 break;
1381 }
1382 }
1383
1384 return false;
1385}
1386
Chris Lattnerba1cb382003-09-19 17:17:26 +00001387// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1388// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1389// guaranteed to be either a shift instruction or a binary operator.
1390Instruction *InstCombiner::OptAndOp(Instruction *Op,
1391 ConstantIntegral *OpRHS,
1392 ConstantIntegral *AndRHS,
1393 BinaryOperator &TheAnd) {
1394 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001395 Constant *Together = 0;
1396 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001397 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001398
Chris Lattnerba1cb382003-09-19 17:17:26 +00001399 switch (Op->getOpcode()) {
1400 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001401 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001402 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1403 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001404 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001405 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001406 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001407 }
1408 break;
1409 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001410 if (Together == AndRHS) // (X | C) & C --> C
1411 return ReplaceInstUsesWith(TheAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001412
Chris Lattner86102b82005-01-01 16:22:27 +00001413 if (Op->hasOneUse() && Together != OpRHS) {
1414 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1415 std::string Op0Name = Op->getName(); Op->setName("");
1416 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1417 InsertNewInstBefore(Or, TheAnd);
1418 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001419 }
1420 break;
1421 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001422 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001423 // Adding a one to a single bit bit-field should be turned into an XOR
1424 // of the bit. First thing to check is to see if this AND is with a
1425 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001426 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001427
1428 // Clear bits that are not part of the constant.
1429 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1430
1431 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001432 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001433 // Ok, at this point, we know that we are masking the result of the
1434 // ADD down to exactly one bit. If the constant we are adding has
1435 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001436 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001437
1438 // Check to see if any bits below the one bit set in AndRHSV are set.
1439 if ((AddRHS & (AndRHSV-1)) == 0) {
1440 // If not, the only thing that can effect the output of the AND is
1441 // the bit specified by AndRHSV. If that bit is set, the effect of
1442 // the XOR is to toggle the bit. If it is clear, then the ADD has
1443 // no effect.
1444 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1445 TheAnd.setOperand(0, X);
1446 return &TheAnd;
1447 } else {
1448 std::string Name = Op->getName(); Op->setName("");
1449 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001450 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001451 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001452 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001453 }
1454 }
1455 }
1456 }
1457 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001458
1459 case Instruction::Shl: {
1460 // We know that the AND will not produce any of the bits shifted in, so if
1461 // the anded constant includes them, clear them now!
1462 //
1463 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001464 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1465 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1466
1467 if (CI == ShlMask) { // Masking out bits that the shift already masks
1468 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1469 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001470 TheAnd.setOperand(1, CI);
1471 return &TheAnd;
1472 }
1473 break;
1474 }
1475 case Instruction::Shr:
1476 // We know that the AND will not produce any of the bits shifted in, so if
1477 // the anded constant includes them, clear them now! This only applies to
1478 // unsigned shifts, because a signed shr may bring in set bits!
1479 //
1480 if (AndRHS->getType()->isUnsigned()) {
1481 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001482 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1483 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1484
1485 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1486 return ReplaceInstUsesWith(TheAnd, Op);
1487 } else if (CI != AndRHS) {
1488 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001489 return &TheAnd;
1490 }
Chris Lattner7e794272004-09-24 15:21:34 +00001491 } else { // Signed shr.
1492 // See if this is shifting in some sign extension, then masking it out
1493 // with an and.
1494 if (Op->hasOneUse()) {
1495 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1496 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1497 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001498 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001499 // Make the argument unsigned.
1500 Value *ShVal = Op->getOperand(0);
1501 ShVal = InsertCastBefore(ShVal,
1502 ShVal->getType()->getUnsignedVersion(),
1503 TheAnd);
1504 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1505 OpRHS, Op->getName()),
1506 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001507 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1508 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1509 TheAnd.getName()),
1510 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001511 return new CastInst(ShVal, Op->getType());
1512 }
1513 }
Chris Lattner2da29172003-09-19 19:05:02 +00001514 }
1515 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001516 }
1517 return 0;
1518}
1519
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001520
Chris Lattner6862fbd2004-09-29 17:40:11 +00001521/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1522/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1523/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1524/// insert new instructions.
1525Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1526 bool Inside, Instruction &IB) {
1527 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1528 "Lo is not <= Hi in range emission code!");
1529 if (Inside) {
1530 if (Lo == Hi) // Trivially false.
1531 return new SetCondInst(Instruction::SetNE, V, V);
1532 if (cast<ConstantIntegral>(Lo)->isMinValue())
1533 return new SetCondInst(Instruction::SetLT, V, Hi);
1534
1535 Constant *AddCST = ConstantExpr::getNeg(Lo);
1536 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1537 InsertNewInstBefore(Add, IB);
1538 // Convert to unsigned for the comparison.
1539 const Type *UnsType = Add->getType()->getUnsignedVersion();
1540 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1541 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1542 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1543 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1544 }
1545
1546 if (Lo == Hi) // Trivially true.
1547 return new SetCondInst(Instruction::SetEQ, V, V);
1548
1549 Hi = SubOne(cast<ConstantInt>(Hi));
1550 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1551 return new SetCondInst(Instruction::SetGT, V, Hi);
1552
1553 // Emit X-Lo > Hi-Lo-1
1554 Constant *AddCST = ConstantExpr::getNeg(Lo);
1555 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1556 InsertNewInstBefore(Add, IB);
1557 // Convert to unsigned for the comparison.
1558 const Type *UnsType = Add->getType()->getUnsignedVersion();
1559 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1560 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1561 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1562 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1563}
1564
1565
Chris Lattner113f4f42002-06-25 16:13:24 +00001566Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001567 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001568 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001569
Chris Lattner81a7a232004-10-16 18:11:37 +00001570 if (isa<UndefValue>(Op1)) // X & undef -> 0
1571 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1572
Chris Lattner86102b82005-01-01 16:22:27 +00001573 // and X, X = X
1574 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00001575 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001576
Chris Lattner86102b82005-01-01 16:22:27 +00001577 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001578 // and X, -1 == X
1579 if (AndRHS->isAllOnesValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001580 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001581
Chris Lattner86102b82005-01-01 16:22:27 +00001582 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1583 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1584
1585 // If the mask is not masking out any bits, there is no reason to do the
1586 // and in the first place.
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001587 ConstantIntegral *NotAndRHS =
1588 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
1589 if (MaskedValueIsZero(Op0, NotAndRHS))
1590 return ReplaceInstUsesWith(I, Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001591
Chris Lattnerba1cb382003-09-19 17:17:26 +00001592 // Optimize a variety of ((val OP C1) & C2) combinations...
1593 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1594 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001595 Value *Op0LHS = Op0I->getOperand(0);
1596 Value *Op0RHS = Op0I->getOperand(1);
1597 switch (Op0I->getOpcode()) {
1598 case Instruction::Xor:
1599 case Instruction::Or:
1600 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1601 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1602 if (MaskedValueIsZero(Op0LHS, AndRHS))
1603 return BinaryOperator::createAnd(Op0RHS, AndRHS);
1604 if (MaskedValueIsZero(Op0RHS, AndRHS))
1605 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001606
1607 // If the mask is only needed on one incoming arm, push it up.
1608 if (Op0I->hasOneUse()) {
1609 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1610 // Not masking anything out for the LHS, move to RHS.
1611 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1612 Op0RHS->getName()+".masked");
1613 InsertNewInstBefore(NewRHS, I);
1614 return BinaryOperator::create(
1615 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
1616 }
1617 if (!isa<Constant>(NotAndRHS) &&
1618 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1619 // Not masking anything out for the RHS, move to LHS.
1620 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1621 Op0LHS->getName()+".masked");
1622 InsertNewInstBefore(NewLHS, I);
1623 return BinaryOperator::create(
1624 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1625 }
1626 }
1627
Chris Lattner86102b82005-01-01 16:22:27 +00001628 break;
1629 case Instruction::And:
1630 // (X & V) & C2 --> 0 iff (V & C2) == 0
1631 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1632 MaskedValueIsZero(Op0RHS, AndRHS))
1633 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1634 break;
1635 }
1636
Chris Lattner16464b32003-07-23 19:25:52 +00001637 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00001638 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001639 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00001640 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1641 const Type *SrcTy = CI->getOperand(0)->getType();
1642
1643 // If this is an integer sign or zero extension instruction.
1644 if (SrcTy->isIntegral() &&
1645 SrcTy->getPrimitiveSize() < CI->getType()->getPrimitiveSize()) {
1646
1647 if (SrcTy->isUnsigned()) {
1648 // See if this and is clearing out bits that are known to be zero
1649 // anyway (due to the zero extension).
1650 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1651 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1652 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1653 if (Result == Mask) // The "and" isn't doing anything, remove it.
1654 return ReplaceInstUsesWith(I, CI);
1655 if (Result != AndRHS) { // Reduce the and RHS constant.
1656 I.setOperand(1, Result);
1657 return &I;
1658 }
1659
1660 } else {
1661 if (CI->hasOneUse() && SrcTy->isInteger()) {
1662 // We can only do this if all of the sign bits brought in are masked
1663 // out. Compute this by first getting 0000011111, then inverting
1664 // it.
1665 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1666 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1667 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1668 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1669 // If the and is clearing all of the sign bits, change this to a
1670 // zero extension cast. To do this, cast the cast input to
1671 // unsigned, then to the requested size.
1672 Value *CastOp = CI->getOperand(0);
1673 Instruction *NC =
1674 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1675 CI->getName()+".uns");
1676 NC = InsertNewInstBefore(NC, I);
1677 // Finally, insert a replacement for CI.
1678 NC = new CastInst(NC, CI->getType(), CI->getName());
1679 CI->setName("");
1680 NC = InsertNewInstBefore(NC, I);
1681 WorkList.push_back(CI); // Delete CI later.
1682 I.setOperand(0, NC);
1683 return &I; // The AND operand was modified.
1684 }
1685 }
1686 }
1687 }
Chris Lattner33217db2003-07-23 19:36:21 +00001688 }
Chris Lattner183b3362004-04-09 19:05:30 +00001689
1690 // Try to fold constant and into select arguments.
1691 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001692 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001693 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001694 if (isa<PHINode>(Op0))
1695 if (Instruction *NV = FoldOpIntoPhi(I))
1696 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001697 }
1698
Chris Lattnerbb74e222003-03-10 23:06:50 +00001699 Value *Op0NotVal = dyn_castNotVal(Op0);
1700 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001701
Chris Lattner023a4832004-06-18 06:07:51 +00001702 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1703 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1704
Misha Brukman9c003d82004-07-30 12:50:08 +00001705 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001706 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001707 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1708 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001709 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001710 return BinaryOperator::createNot(Or);
1711 }
1712
Chris Lattner623826c2004-09-28 21:48:02 +00001713 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1714 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001715 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1716 return R;
1717
Chris Lattner623826c2004-09-28 21:48:02 +00001718 Value *LHSVal, *RHSVal;
1719 ConstantInt *LHSCst, *RHSCst;
1720 Instruction::BinaryOps LHSCC, RHSCC;
1721 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1722 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1723 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1724 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1725 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1726 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1727 // Ensure that the larger constant is on the RHS.
1728 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1729 SetCondInst *LHS = cast<SetCondInst>(Op0);
1730 if (cast<ConstantBool>(Cmp)->getValue()) {
1731 std::swap(LHS, RHS);
1732 std::swap(LHSCst, RHSCst);
1733 std::swap(LHSCC, RHSCC);
1734 }
1735
1736 // At this point, we know we have have two setcc instructions
1737 // comparing a value against two constants and and'ing the result
1738 // together. Because of the above check, we know that we only have
1739 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1740 // FoldSetCCLogical check above), that the two constants are not
1741 // equal.
1742 assert(LHSCst != RHSCst && "Compares not folded above?");
1743
1744 switch (LHSCC) {
1745 default: assert(0 && "Unknown integer condition code!");
1746 case Instruction::SetEQ:
1747 switch (RHSCC) {
1748 default: assert(0 && "Unknown integer condition code!");
1749 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1750 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1751 return ReplaceInstUsesWith(I, ConstantBool::False);
1752 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1753 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1754 return ReplaceInstUsesWith(I, LHS);
1755 }
1756 case Instruction::SetNE:
1757 switch (RHSCC) {
1758 default: assert(0 && "Unknown integer condition code!");
1759 case Instruction::SetLT:
1760 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1761 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1762 break; // (X != 13 & X < 15) -> no change
1763 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1764 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1765 return ReplaceInstUsesWith(I, RHS);
1766 case Instruction::SetNE:
1767 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1768 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1769 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1770 LHSVal->getName()+".off");
1771 InsertNewInstBefore(Add, I);
1772 const Type *UnsType = Add->getType()->getUnsignedVersion();
1773 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1774 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1775 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1776 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1777 }
1778 break; // (X != 13 & X != 15) -> no change
1779 }
1780 break;
1781 case Instruction::SetLT:
1782 switch (RHSCC) {
1783 default: assert(0 && "Unknown integer condition code!");
1784 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1785 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1786 return ReplaceInstUsesWith(I, ConstantBool::False);
1787 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1788 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1789 return ReplaceInstUsesWith(I, LHS);
1790 }
1791 case Instruction::SetGT:
1792 switch (RHSCC) {
1793 default: assert(0 && "Unknown integer condition code!");
1794 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1795 return ReplaceInstUsesWith(I, LHS);
1796 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1797 return ReplaceInstUsesWith(I, RHS);
1798 case Instruction::SetNE:
1799 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1800 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1801 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001802 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1803 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001804 }
1805 }
1806 }
1807 }
1808
Chris Lattner113f4f42002-06-25 16:13:24 +00001809 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001810}
1811
Chris Lattner113f4f42002-06-25 16:13:24 +00001812Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001813 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001814 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001815
Chris Lattner81a7a232004-10-16 18:11:37 +00001816 if (isa<UndefValue>(Op1))
1817 return ReplaceInstUsesWith(I, // X | undef -> -1
1818 ConstantIntegral::getAllOnesValue(I.getType()));
1819
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001820 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001821 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1822 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001823
1824 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001825 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001826 // If X is known to only contain bits that already exist in RHS, just
1827 // replace this instruction with RHS directly.
1828 if (MaskedValueIsZero(Op0,
1829 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
1830 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001831
Chris Lattnerd4252a72004-07-30 07:50:03 +00001832 ConstantInt *C1; Value *X;
1833 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1834 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1835 std::string Op0Name = Op0->getName(); Op0->setName("");
1836 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1837 InsertNewInstBefore(Or, I);
1838 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1839 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001840
Chris Lattnerd4252a72004-07-30 07:50:03 +00001841 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1842 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1843 std::string Op0Name = Op0->getName(); Op0->setName("");
1844 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1845 InsertNewInstBefore(Or, I);
1846 return BinaryOperator::createXor(Or,
1847 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001848 }
Chris Lattner183b3362004-04-09 19:05:30 +00001849
1850 // Try to fold constant and into select arguments.
1851 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001852 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001853 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001854 if (isa<PHINode>(Op0))
1855 if (Instruction *NV = FoldOpIntoPhi(I))
1856 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001857 }
1858
Chris Lattner812aab72003-08-12 19:11:07 +00001859 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001860 Value *A, *B; ConstantInt *C1, *C2;
1861 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1862 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1863 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001864
Chris Lattnerd4252a72004-07-30 07:50:03 +00001865 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1866 if (A == Op1) // ~A | A == -1
1867 return ReplaceInstUsesWith(I,
1868 ConstantIntegral::getAllOnesValue(I.getType()));
1869 } else {
1870 A = 0;
1871 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001872
Chris Lattnerd4252a72004-07-30 07:50:03 +00001873 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1874 if (Op0 == B)
1875 return ReplaceInstUsesWith(I,
1876 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001877
Misha Brukman9c003d82004-07-30 12:50:08 +00001878 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001879 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1880 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1881 I.getName()+".demorgan"), I);
1882 return BinaryOperator::createNot(And);
1883 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001884 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001885
Chris Lattner3ac7c262003-08-13 20:16:26 +00001886 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001887 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001888 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1889 return R;
1890
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001891 Value *LHSVal, *RHSVal;
1892 ConstantInt *LHSCst, *RHSCst;
1893 Instruction::BinaryOps LHSCC, RHSCC;
1894 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1895 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1896 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1897 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1898 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1899 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1900 // Ensure that the larger constant is on the RHS.
1901 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1902 SetCondInst *LHS = cast<SetCondInst>(Op0);
1903 if (cast<ConstantBool>(Cmp)->getValue()) {
1904 std::swap(LHS, RHS);
1905 std::swap(LHSCst, RHSCst);
1906 std::swap(LHSCC, RHSCC);
1907 }
1908
1909 // At this point, we know we have have two setcc instructions
1910 // comparing a value against two constants and or'ing the result
1911 // together. Because of the above check, we know that we only have
1912 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1913 // FoldSetCCLogical check above), that the two constants are not
1914 // equal.
1915 assert(LHSCst != RHSCst && "Compares not folded above?");
1916
1917 switch (LHSCC) {
1918 default: assert(0 && "Unknown integer condition code!");
1919 case Instruction::SetEQ:
1920 switch (RHSCC) {
1921 default: assert(0 && "Unknown integer condition code!");
1922 case Instruction::SetEQ:
1923 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1924 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1925 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1926 LHSVal->getName()+".off");
1927 InsertNewInstBefore(Add, I);
1928 const Type *UnsType = Add->getType()->getUnsignedVersion();
1929 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1930 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1931 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1932 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1933 }
1934 break; // (X == 13 | X == 15) -> no change
1935
1936 case Instruction::SetGT:
1937 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1938 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1939 break; // (X == 13 | X > 15) -> no change
1940 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1941 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1942 return ReplaceInstUsesWith(I, RHS);
1943 }
1944 break;
1945 case Instruction::SetNE:
1946 switch (RHSCC) {
1947 default: assert(0 && "Unknown integer condition code!");
1948 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1949 return ReplaceInstUsesWith(I, RHS);
1950 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1951 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1952 return ReplaceInstUsesWith(I, LHS);
1953 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1954 return ReplaceInstUsesWith(I, ConstantBool::True);
1955 }
1956 break;
1957 case Instruction::SetLT:
1958 switch (RHSCC) {
1959 default: assert(0 && "Unknown integer condition code!");
1960 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1961 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001962 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1963 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001964 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1965 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1966 return ReplaceInstUsesWith(I, RHS);
1967 }
1968 break;
1969 case Instruction::SetGT:
1970 switch (RHSCC) {
1971 default: assert(0 && "Unknown integer condition code!");
1972 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1973 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1974 return ReplaceInstUsesWith(I, LHS);
1975 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1976 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1977 return ReplaceInstUsesWith(I, ConstantBool::True);
1978 }
1979 }
1980 }
1981 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001982 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001983}
1984
Chris Lattnerc2076352004-02-16 01:20:27 +00001985// XorSelf - Implements: X ^ X --> 0
1986struct XorSelf {
1987 Value *RHS;
1988 XorSelf(Value *rhs) : RHS(rhs) {}
1989 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1990 Instruction *apply(BinaryOperator &Xor) const {
1991 return &Xor;
1992 }
1993};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001994
1995
Chris Lattner113f4f42002-06-25 16:13:24 +00001996Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001997 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001998 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001999
Chris Lattner81a7a232004-10-16 18:11:37 +00002000 if (isa<UndefValue>(Op1))
2001 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2002
Chris Lattnerc2076352004-02-16 01:20:27 +00002003 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2004 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2005 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002006 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002007 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002008
Chris Lattner97638592003-07-23 21:37:07 +00002009 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002010 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00002011 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00002012 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002013
Chris Lattner97638592003-07-23 21:37:07 +00002014 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002015 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002016 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002017 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002018 return new SetCondInst(SCI->getInverseCondition(),
2019 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002020
Chris Lattner8f2f5982003-11-05 01:06:05 +00002021 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002022 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2023 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002024 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2025 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002026 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002027 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002028 }
Chris Lattner023a4832004-06-18 06:07:51 +00002029
2030 // ~(~X & Y) --> (X | ~Y)
2031 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2032 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2033 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2034 Instruction *NotY =
2035 BinaryOperator::createNot(Op0I->getOperand(1),
2036 Op0I->getOperand(1)->getName()+".not");
2037 InsertNewInstBefore(NotY, I);
2038 return BinaryOperator::createOr(Op0NotVal, NotY);
2039 }
2040 }
Chris Lattner97638592003-07-23 21:37:07 +00002041
2042 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002043 switch (Op0I->getOpcode()) {
2044 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002045 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002046 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002047 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2048 return BinaryOperator::createSub(
2049 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002050 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002051 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002052 }
Chris Lattnere5806662003-11-04 23:50:51 +00002053 break;
2054 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002055 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002056 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2057 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002058 break;
2059 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002060 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002061 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002062 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002063 break;
2064 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002065 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002066 }
Chris Lattner183b3362004-04-09 19:05:30 +00002067
2068 // Try to fold constant and into select arguments.
2069 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002070 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002071 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002072 if (isa<PHINode>(Op0))
2073 if (Instruction *NV = FoldOpIntoPhi(I))
2074 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002075 }
2076
Chris Lattnerbb74e222003-03-10 23:06:50 +00002077 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002078 if (X == Op1)
2079 return ReplaceInstUsesWith(I,
2080 ConstantIntegral::getAllOnesValue(I.getType()));
2081
Chris Lattnerbb74e222003-03-10 23:06:50 +00002082 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002083 if (X == Op0)
2084 return ReplaceInstUsesWith(I,
2085 ConstantIntegral::getAllOnesValue(I.getType()));
2086
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002087 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002088 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002089 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2090 cast<BinaryOperator>(Op1I)->swapOperands();
2091 I.swapOperands();
2092 std::swap(Op0, Op1);
2093 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2094 I.swapOperands();
2095 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00002096 }
2097 } else if (Op1I->getOpcode() == Instruction::Xor) {
2098 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2099 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2100 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2101 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2102 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002103
2104 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002105 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002106 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2107 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002108 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002109 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2110 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002111 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002112 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002113 } else if (Op0I->getOpcode() == Instruction::Xor) {
2114 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2115 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2116 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2117 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002118 }
2119
Chris Lattner7aa2d472004-08-01 19:42:59 +00002120 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002121 Value *A, *B; ConstantInt *C1, *C2;
2122 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2123 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002124 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002125 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002126
Chris Lattner3ac7c262003-08-13 20:16:26 +00002127 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2128 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2129 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2130 return R;
2131
Chris Lattner113f4f42002-06-25 16:13:24 +00002132 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002133}
2134
Chris Lattner6862fbd2004-09-29 17:40:11 +00002135/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2136/// overflowed for this type.
2137static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2138 ConstantInt *In2) {
2139 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2140 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2141}
2142
2143static bool isPositive(ConstantInt *C) {
2144 return cast<ConstantSInt>(C)->getValue() >= 0;
2145}
2146
2147/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2148/// overflowed for this type.
2149static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2150 ConstantInt *In2) {
2151 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2152
2153 if (In1->getType()->isUnsigned())
2154 return cast<ConstantUInt>(Result)->getValue() <
2155 cast<ConstantUInt>(In1)->getValue();
2156 if (isPositive(In1) != isPositive(In2))
2157 return false;
2158 if (isPositive(In1))
2159 return cast<ConstantSInt>(Result)->getValue() <
2160 cast<ConstantSInt>(In1)->getValue();
2161 return cast<ConstantSInt>(Result)->getValue() >
2162 cast<ConstantSInt>(In1)->getValue();
2163}
2164
Chris Lattner0798af32005-01-13 20:14:25 +00002165/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2166/// code necessary to compute the offset from the base pointer (without adding
2167/// in the base pointer). Return the result as a signed integer of intptr size.
2168static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2169 TargetData &TD = IC.getTargetData();
2170 gep_type_iterator GTI = gep_type_begin(GEP);
2171 const Type *UIntPtrTy = TD.getIntPtrType();
2172 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2173 Value *Result = Constant::getNullValue(SIntPtrTy);
2174
2175 // Build a mask for high order bits.
2176 uint64_t PtrSizeMask = ~0ULL;
2177 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2178
Chris Lattner0798af32005-01-13 20:14:25 +00002179 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2180 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002181 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002182 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2183 SIntPtrTy);
2184 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2185 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002186 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002187 Scale = ConstantExpr::getMul(OpC, Scale);
2188 if (Constant *RC = dyn_cast<Constant>(Result))
2189 Result = ConstantExpr::getAdd(RC, Scale);
2190 else {
2191 // Emit an add instruction.
2192 Result = IC.InsertNewInstBefore(
2193 BinaryOperator::createAdd(Result, Scale,
2194 GEP->getName()+".offs"), I);
2195 }
2196 }
2197 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002198 // Convert to correct type.
2199 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2200 Op->getName()+".c"), I);
2201 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002202 // We'll let instcombine(mul) convert this to a shl if possible.
2203 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2204 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002205
2206 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002207 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002208 GEP->getName()+".offs"), I);
2209 }
2210 }
2211 return Result;
2212}
2213
2214/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2215/// else. At this point we know that the GEP is on the LHS of the comparison.
2216Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2217 Instruction::BinaryOps Cond,
2218 Instruction &I) {
2219 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002220
2221 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2222 if (isa<PointerType>(CI->getOperand(0)->getType()))
2223 RHS = CI->getOperand(0);
2224
Chris Lattner0798af32005-01-13 20:14:25 +00002225 Value *PtrBase = GEPLHS->getOperand(0);
2226 if (PtrBase == RHS) {
2227 // As an optimization, we don't actually have to compute the actual value of
2228 // OFFSET if this is a seteq or setne comparison, just return whether each
2229 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002230 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2231 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002232 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2233 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00002234 bool EmitIt = true;
2235 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2236 if (isa<UndefValue>(C)) // undef index -> undef.
2237 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2238 if (C->isNullValue())
2239 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002240 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2241 EmitIt = false; // This is indexing into a zero sized array?
2242 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00002243 return ReplaceInstUsesWith(I, // No comparison is needed here.
2244 ConstantBool::get(Cond == Instruction::SetNE));
2245 }
2246
2247 if (EmitIt) {
2248 Instruction *Comp =
2249 new SetCondInst(Cond, GEPLHS->getOperand(i),
2250 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2251 if (InVal == 0)
2252 InVal = Comp;
2253 else {
2254 InVal = InsertNewInstBefore(InVal, I);
2255 InsertNewInstBefore(Comp, I);
2256 if (Cond == Instruction::SetNE) // True if any are unequal
2257 InVal = BinaryOperator::createOr(InVal, Comp);
2258 else // True if all are equal
2259 InVal = BinaryOperator::createAnd(InVal, Comp);
2260 }
2261 }
2262 }
2263
2264 if (InVal)
2265 return InVal;
2266 else
2267 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2268 ConstantBool::get(Cond == Instruction::SetEQ));
2269 }
Chris Lattner0798af32005-01-13 20:14:25 +00002270
2271 // Only lower this if the setcc is the only user of the GEP or if we expect
2272 // the result to fold to a constant!
2273 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2274 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2275 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2276 return new SetCondInst(Cond, Offset,
2277 Constant::getNullValue(Offset->getType()));
2278 }
2279 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
2280 if (PtrBase != GEPRHS->getOperand(0))
2281 return 0;
2282
Chris Lattner81e84172005-01-13 22:25:21 +00002283 // If one of the GEPs has all zero indices, recurse.
2284 bool AllZeros = true;
2285 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2286 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2287 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2288 AllZeros = false;
2289 break;
2290 }
2291 if (AllZeros)
2292 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2293 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00002294
2295 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00002296 AllZeros = true;
2297 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2298 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2299 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2300 AllZeros = false;
2301 break;
2302 }
2303 if (AllZeros)
2304 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2305
Chris Lattner4fa89822005-01-14 00:20:05 +00002306 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2307 // If the GEPs only differ by one index, compare it.
2308 unsigned NumDifferences = 0; // Keep track of # differences.
2309 unsigned DiffOperand = 0; // The operand that differs.
2310 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2311 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002312 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSize() !=
2313 GEPRHS->getOperand(i)->getType()->getPrimitiveSize()) {
2314 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00002315 NumDifferences = 2;
2316 break;
2317 } else {
2318 if (NumDifferences++) break;
2319 DiffOperand = i;
2320 }
2321 }
2322
2323 if (NumDifferences == 0) // SAME GEP?
2324 return ReplaceInstUsesWith(I, // No comparison is needed here.
2325 ConstantBool::get(Cond == Instruction::SetEQ));
2326 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002327 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2328 Value *RHSV = GEPRHS->getOperand(DiffOperand);
2329 if (LHSV->getType() != RHSV->getType())
2330 LHSV = InsertNewInstBefore(new CastInst(LHSV, RHSV->getType(),
2331 LHSV->getName()+".c"), I);
2332 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00002333 }
2334 }
2335
Chris Lattner0798af32005-01-13 20:14:25 +00002336 // Only lower this if the setcc is the only user of the GEP or if we expect
2337 // the result to fold to a constant!
2338 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2339 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2340 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2341 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2342 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2343 return new SetCondInst(Cond, L, R);
2344 }
2345 }
2346 return 0;
2347}
2348
2349
Chris Lattner113f4f42002-06-25 16:13:24 +00002350Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002351 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002352 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2353 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002354
2355 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002356 if (Op0 == Op1)
2357 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002358
Chris Lattner81a7a232004-10-16 18:11:37 +00002359 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2360 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2361
Chris Lattner15ff1e12004-11-14 07:33:16 +00002362 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2363 // addresses never equal each other! We already know that Op0 != Op1.
2364 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2365 isa<ConstantPointerNull>(Op0)) &&
2366 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
2367 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002368 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2369
2370 // setcc's with boolean values can always be turned into bitwise operations
2371 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002372 switch (I.getOpcode()) {
2373 default: assert(0 && "Invalid setcc instruction!");
2374 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002375 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002376 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002377 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002378 }
Chris Lattner4456da62004-08-11 00:50:51 +00002379 case Instruction::SetNE:
2380 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002381
Chris Lattner4456da62004-08-11 00:50:51 +00002382 case Instruction::SetGT:
2383 std::swap(Op0, Op1); // Change setgt -> setlt
2384 // FALL THROUGH
2385 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2386 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2387 InsertNewInstBefore(Not, I);
2388 return BinaryOperator::createAnd(Not, Op1);
2389 }
2390 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002391 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002392 // FALL THROUGH
2393 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2394 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2395 InsertNewInstBefore(Not, I);
2396 return BinaryOperator::createOr(Not, Op1);
2397 }
2398 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002399 }
2400
Chris Lattner2dd01742004-06-09 04:24:29 +00002401 // See if we are doing a comparison between a constant and an instruction that
2402 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002403 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002404 // Check to see if we are comparing against the minimum or maximum value...
2405 if (CI->isMinValue()) {
2406 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2407 return ReplaceInstUsesWith(I, ConstantBool::False);
2408 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2409 return ReplaceInstUsesWith(I, ConstantBool::True);
2410 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2411 return BinaryOperator::createSetEQ(Op0, Op1);
2412 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2413 return BinaryOperator::createSetNE(Op0, Op1);
2414
2415 } else if (CI->isMaxValue()) {
2416 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2417 return ReplaceInstUsesWith(I, ConstantBool::False);
2418 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2419 return ReplaceInstUsesWith(I, ConstantBool::True);
2420 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2421 return BinaryOperator::createSetEQ(Op0, Op1);
2422 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2423 return BinaryOperator::createSetNE(Op0, Op1);
2424
2425 // Comparing against a value really close to min or max?
2426 } else if (isMinValuePlusOne(CI)) {
2427 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2428 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2429 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2430 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2431
2432 } else if (isMaxValueMinusOne(CI)) {
2433 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2434 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2435 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2436 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2437 }
2438
2439 // If we still have a setle or setge instruction, turn it into the
2440 // appropriate setlt or setgt instruction. Since the border cases have
2441 // already been handled above, this requires little checking.
2442 //
2443 if (I.getOpcode() == Instruction::SetLE)
2444 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2445 if (I.getOpcode() == Instruction::SetGE)
2446 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2447
Chris Lattnere1e10e12004-05-25 06:32:08 +00002448 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002449 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002450 case Instruction::PHI:
2451 if (Instruction *NV = FoldOpIntoPhi(I))
2452 return NV;
2453 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002454 case Instruction::And:
2455 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2456 LHSI->getOperand(0)->hasOneUse()) {
2457 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2458 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2459 // happens a LOT in code produced by the C front-end, for bitfield
2460 // access.
2461 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2462 ConstantUInt *ShAmt;
2463 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2464 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2465 const Type *Ty = LHSI->getType();
2466
2467 // We can fold this as long as we can't shift unknown bits
2468 // into the mask. This can only happen with signed shift
2469 // rights, as they sign-extend.
2470 if (ShAmt) {
2471 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002472 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002473 if (!CanFold) {
2474 // To test for the bad case of the signed shr, see if any
2475 // of the bits shifted in could be tested after the mask.
2476 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00002477 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002478 Constant *ShVal =
2479 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2480 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2481 CanFold = true;
2482 }
2483
2484 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002485 Constant *NewCst;
2486 if (Shift->getOpcode() == Instruction::Shl)
2487 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2488 else
2489 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002490
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002491 // Check to see if we are shifting out any of the bits being
2492 // compared.
2493 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2494 // If we shifted bits out, the fold is not going to work out.
2495 // As a special case, check to see if this means that the
2496 // result is always true or false now.
2497 if (I.getOpcode() == Instruction::SetEQ)
2498 return ReplaceInstUsesWith(I, ConstantBool::False);
2499 if (I.getOpcode() == Instruction::SetNE)
2500 return ReplaceInstUsesWith(I, ConstantBool::True);
2501 } else {
2502 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002503 Constant *NewAndCST;
2504 if (Shift->getOpcode() == Instruction::Shl)
2505 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2506 else
2507 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2508 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002509 LHSI->setOperand(0, Shift->getOperand(0));
2510 WorkList.push_back(Shift); // Shift is dead.
2511 AddUsesToWorkList(I);
2512 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002513 }
2514 }
Chris Lattner35167c32004-06-09 07:59:58 +00002515 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002516 }
2517 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002518
Reid Spencer279fa252004-11-28 21:31:15 +00002519 // (setcc (cast X to larger), CI)
Chris Lattner03f06f12005-01-17 03:20:02 +00002520 case Instruction::Cast:
2521 if (Instruction *R =
2522 visitSetCondInstWithCastAndConstant(I,cast<CastInst>(LHSI),CI))
2523 return R;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002524 break;
Reid Spencer279fa252004-11-28 21:31:15 +00002525
Chris Lattner272d5ca2004-09-28 18:22:15 +00002526 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2527 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2528 switch (I.getOpcode()) {
2529 default: break;
2530 case Instruction::SetEQ:
2531 case Instruction::SetNE: {
2532 // If we are comparing against bits always shifted out, the
2533 // comparison cannot succeed.
2534 Constant *Comp =
2535 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2536 if (Comp != CI) {// Comparing against a bit that we know is zero.
2537 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2538 Constant *Cst = ConstantBool::get(IsSetNE);
2539 return ReplaceInstUsesWith(I, Cst);
2540 }
2541
2542 if (LHSI->hasOneUse()) {
2543 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002544 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002545 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2546 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2547
2548 Constant *Mask;
2549 if (CI->getType()->isUnsigned()) {
2550 Mask = ConstantUInt::get(CI->getType(), Val);
2551 } else if (ShAmtVal != 0) {
2552 Mask = ConstantSInt::get(CI->getType(), Val);
2553 } else {
2554 Mask = ConstantInt::getAllOnesValue(CI->getType());
2555 }
2556
2557 Instruction *AndI =
2558 BinaryOperator::createAnd(LHSI->getOperand(0),
2559 Mask, LHSI->getName()+".mask");
2560 Value *And = InsertNewInstBefore(AndI, I);
2561 return new SetCondInst(I.getOpcode(), And,
2562 ConstantExpr::getUShr(CI, ShAmt));
2563 }
2564 }
2565 }
2566 }
2567 break;
2568
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002569 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002570 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002571 switch (I.getOpcode()) {
2572 default: break;
2573 case Instruction::SetEQ:
2574 case Instruction::SetNE: {
2575 // If we are comparing against bits always shifted out, the
2576 // comparison cannot succeed.
2577 Constant *Comp =
2578 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2579
2580 if (Comp != CI) {// Comparing against a bit that we know is zero.
2581 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2582 Constant *Cst = ConstantBool::get(IsSetNE);
2583 return ReplaceInstUsesWith(I, Cst);
2584 }
2585
2586 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002587 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002588
Chris Lattner1023b872004-09-27 16:18:50 +00002589 // Otherwise strength reduce the shift into an and.
2590 uint64_t Val = ~0ULL; // All ones.
2591 Val <<= ShAmtVal; // Shift over to the right spot.
2592
2593 Constant *Mask;
2594 if (CI->getType()->isUnsigned()) {
2595 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
Chris Lattnercfe2822c2005-03-04 23:21:33 +00002596 if (TypeBits != 64)
2597 Val &= (1ULL << TypeBits)-1;
Chris Lattner1023b872004-09-27 16:18:50 +00002598 Mask = ConstantUInt::get(CI->getType(), Val);
2599 } else {
2600 Mask = ConstantSInt::get(CI->getType(), Val);
2601 }
2602
2603 Instruction *AndI =
2604 BinaryOperator::createAnd(LHSI->getOperand(0),
2605 Mask, LHSI->getName()+".mask");
2606 Value *And = InsertNewInstBefore(AndI, I);
2607 return new SetCondInst(I.getOpcode(), And,
2608 ConstantExpr::getShl(CI, ShAmt));
2609 }
2610 break;
2611 }
2612 }
2613 }
2614 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002615
Chris Lattner6862fbd2004-09-29 17:40:11 +00002616 case Instruction::Div:
2617 // Fold: (div X, C1) op C2 -> range check
2618 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2619 // Fold this div into the comparison, producing a range check.
2620 // Determine, based on the divide type, what the range is being
2621 // checked. If there is an overflow on the low or high side, remember
2622 // it, otherwise compute the range [low, hi) bounding the new value.
2623 bool LoOverflow = false, HiOverflow = 0;
2624 ConstantInt *LoBound = 0, *HiBound = 0;
2625
2626 ConstantInt *Prod;
2627 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2628
Chris Lattnera92af962004-10-11 19:40:04 +00002629 Instruction::BinaryOps Opcode = I.getOpcode();
2630
Chris Lattner6862fbd2004-09-29 17:40:11 +00002631 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2632 } else if (LHSI->getType()->isUnsigned()) { // udiv
2633 LoBound = Prod;
2634 LoOverflow = ProdOV;
2635 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2636 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2637 if (CI->isNullValue()) { // (X / pos) op 0
2638 // Can't overflow.
2639 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2640 HiBound = DivRHS;
2641 } else if (isPositive(CI)) { // (X / pos) op pos
2642 LoBound = Prod;
2643 LoOverflow = ProdOV;
2644 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2645 } else { // (X / pos) op neg
2646 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2647 LoOverflow = AddWithOverflow(LoBound, Prod,
2648 cast<ConstantInt>(DivRHSH));
2649 HiBound = Prod;
2650 HiOverflow = ProdOV;
2651 }
2652 } else { // Divisor is < 0.
2653 if (CI->isNullValue()) { // (X / neg) op 0
2654 LoBound = AddOne(DivRHS);
2655 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2656 } else if (isPositive(CI)) { // (X / neg) op pos
2657 HiOverflow = LoOverflow = ProdOV;
2658 if (!LoOverflow)
2659 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2660 HiBound = AddOne(Prod);
2661 } else { // (X / neg) op neg
2662 LoBound = Prod;
2663 LoOverflow = HiOverflow = ProdOV;
2664 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2665 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002666
Chris Lattnera92af962004-10-11 19:40:04 +00002667 // Dividing by a negate swaps the condition.
2668 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002669 }
2670
2671 if (LoBound) {
2672 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002673 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002674 default: assert(0 && "Unhandled setcc opcode!");
2675 case Instruction::SetEQ:
2676 if (LoOverflow && HiOverflow)
2677 return ReplaceInstUsesWith(I, ConstantBool::False);
2678 else if (HiOverflow)
2679 return new SetCondInst(Instruction::SetGE, X, LoBound);
2680 else if (LoOverflow)
2681 return new SetCondInst(Instruction::SetLT, X, HiBound);
2682 else
2683 return InsertRangeTest(X, LoBound, HiBound, true, I);
2684 case Instruction::SetNE:
2685 if (LoOverflow && HiOverflow)
2686 return ReplaceInstUsesWith(I, ConstantBool::True);
2687 else if (HiOverflow)
2688 return new SetCondInst(Instruction::SetLT, X, LoBound);
2689 else if (LoOverflow)
2690 return new SetCondInst(Instruction::SetGE, X, HiBound);
2691 else
2692 return InsertRangeTest(X, LoBound, HiBound, false, I);
2693 case Instruction::SetLT:
2694 if (LoOverflow)
2695 return ReplaceInstUsesWith(I, ConstantBool::False);
2696 return new SetCondInst(Instruction::SetLT, X, LoBound);
2697 case Instruction::SetGT:
2698 if (HiOverflow)
2699 return ReplaceInstUsesWith(I, ConstantBool::False);
2700 return new SetCondInst(Instruction::SetGE, X, HiBound);
2701 }
2702 }
2703 }
2704 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002705 case Instruction::Select:
2706 // If either operand of the select is a constant, we can fold the
2707 // comparison into the select arms, which will cause one to be
2708 // constant folded and the select turned into a bitwise or.
2709 Value *Op1 = 0, *Op2 = 0;
2710 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00002711 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002712 // Fold the known value into the constant operand.
2713 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2714 // Insert a new SetCC of the other select operand.
2715 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002716 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002717 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00002718 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002719 // Fold the known value into the constant operand.
2720 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2721 // Insert a new SetCC of the other select operand.
2722 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002723 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002724 I.getName()), I);
2725 }
Chris Lattner2dd01742004-06-09 04:24:29 +00002726 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002727
2728 if (Op1)
2729 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2730 break;
2731 }
2732
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002733 // Simplify seteq and setne instructions...
2734 if (I.getOpcode() == Instruction::SetEQ ||
2735 I.getOpcode() == Instruction::SetNE) {
2736 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2737
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002738 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002739 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002740 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2741 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002742 case Instruction::Rem:
2743 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2744 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2745 BO->hasOneUse() &&
2746 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2747 if (unsigned L2 =
2748 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2749 const Type *UTy = BO->getType()->getUnsignedVersion();
2750 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2751 UTy, "tmp"), I);
2752 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2753 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2754 RHSCst, BO->getName()), I);
2755 return BinaryOperator::create(I.getOpcode(), NewRem,
2756 Constant::getNullValue(UTy));
2757 }
2758 break;
2759
Chris Lattnerc992add2003-08-13 05:33:12 +00002760 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002761 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2762 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002763 if (BO->hasOneUse())
2764 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2765 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002766 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002767 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2768 // efficiently invertible, or if the add has just this one use.
2769 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00002770
Chris Lattnerc992add2003-08-13 05:33:12 +00002771 if (Value *NegVal = dyn_castNegVal(BOp1))
2772 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2773 else if (Value *NegVal = dyn_castNegVal(BOp0))
2774 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002775 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002776 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2777 BO->setName("");
2778 InsertNewInstBefore(Neg, I);
2779 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2780 }
2781 }
2782 break;
2783 case Instruction::Xor:
2784 // For the xor case, we can xor two constants together, eliminating
2785 // the explicit xor.
2786 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2787 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002788 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002789
2790 // FALLTHROUGH
2791 case Instruction::Sub:
2792 // Replace (([sub|xor] A, B) != 0) with (A != B)
2793 if (CI->isNullValue())
2794 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2795 BO->getOperand(1));
2796 break;
2797
2798 case Instruction::Or:
2799 // If bits are being or'd in that are not present in the constant we
2800 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002801 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002802 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002803 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002804 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002805 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002806 break;
2807
2808 case Instruction::And:
2809 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002810 // If bits are being compared against that are and'd out, then the
2811 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002812 if (!ConstantExpr::getAnd(CI,
2813 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002814 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002815
Chris Lattner35167c32004-06-09 07:59:58 +00002816 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002817 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002818 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2819 Instruction::SetNE, Op0,
2820 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002821
Chris Lattnerc992add2003-08-13 05:33:12 +00002822 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2823 // to be a signed value as appropriate.
2824 if (isSignBit(BOC)) {
2825 Value *X = BO->getOperand(0);
2826 // If 'X' is not signed, insert a cast now...
2827 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002828 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002829 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002830 }
2831 return new SetCondInst(isSetNE ? Instruction::SetLT :
2832 Instruction::SetGE, X,
2833 Constant::getNullValue(X->getType()));
2834 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002835
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002836 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002837 if (CI->isNullValue() && isHighOnes(BOC)) {
2838 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002839 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002840
2841 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002842 if (NegX->getType()->isSigned()) {
2843 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2844 X = InsertCastBefore(X, DestTy, I);
2845 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002846 }
2847
2848 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002849 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002850 }
2851
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002852 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002853 default: break;
2854 }
2855 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002856 } else { // Not a SetEQ/SetNE
2857 // If the LHS is a cast from an integral value of the same size,
2858 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2859 Value *CastOp = Cast->getOperand(0);
2860 const Type *SrcTy = CastOp->getType();
2861 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2862 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2863 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2864 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2865 "Source and destination signednesses should differ!");
2866 if (Cast->getType()->isSigned()) {
2867 // If this is a signed comparison, check for comparisons in the
2868 // vicinity of zero.
2869 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2870 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002871 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002872 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2873 else if (I.getOpcode() == Instruction::SetGT &&
2874 cast<ConstantSInt>(CI)->getValue() == -1)
2875 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002876 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002877 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2878 } else {
2879 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2880 if (I.getOpcode() == Instruction::SetLT &&
2881 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2882 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002883 return BinaryOperator::createSetGT(CastOp,
2884 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002885 else if (I.getOpcode() == Instruction::SetGT &&
2886 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2887 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002888 return BinaryOperator::createSetLT(CastOp,
2889 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002890 }
2891 }
2892 }
Chris Lattnere967b342003-06-04 05:10:11 +00002893 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002894 }
2895
Chris Lattner0798af32005-01-13 20:14:25 +00002896 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
2897 if (User *GEP = dyn_castGetElementPtr(Op0))
2898 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
2899 return NI;
2900 if (User *GEP = dyn_castGetElementPtr(Op1))
2901 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
2902 SetCondInst::getSwappedCondition(I.getOpcode()), I))
2903 return NI;
2904
Chris Lattner16930792003-11-03 04:25:02 +00002905 // Test to see if the operands of the setcc are casted versions of other
2906 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002907 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2908 Value *CastOp0 = CI->getOperand(0);
2909 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002910 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002911 (I.getOpcode() == Instruction::SetEQ ||
2912 I.getOpcode() == Instruction::SetNE)) {
2913 // We keep moving the cast from the left operand over to the right
2914 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002915 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002916
2917 // If operand #1 is a cast instruction, see if we can eliminate it as
2918 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002919 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2920 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002921 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002922 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002923
2924 // If Op1 is a constant, we can fold the cast into the constant.
2925 if (Op1->getType() != Op0->getType())
2926 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2927 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2928 } else {
2929 // Otherwise, cast the RHS right before the setcc
2930 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2931 InsertNewInstBefore(cast<Instruction>(Op1), I);
2932 }
2933 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2934 }
2935
Chris Lattner6444c372003-11-03 05:17:03 +00002936 // Handle the special case of: setcc (cast bool to X), <cst>
2937 // This comes up when you have code like
2938 // int X = A < B;
2939 // if (X) ...
2940 // For generality, we handle any zero-extension of any operand comparison
2941 // with a constant.
2942 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2943 const Type *SrcTy = CastOp0->getType();
2944 const Type *DestTy = Op0->getType();
2945 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2946 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2947 // Ok, we have an expansion of operand 0 into a new type. Get the
2948 // constant value, masink off bits which are not set in the RHS. These
2949 // could be set if the destination value is signed.
2950 uint64_t ConstVal = ConstantRHS->getRawValue();
2951 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2952
2953 // If the constant we are comparing it with has high bits set, which
2954 // don't exist in the original value, the values could never be equal,
2955 // because the source would be zero extended.
2956 unsigned SrcBits =
2957 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002958 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2959 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002960 switch (I.getOpcode()) {
2961 default: assert(0 && "Unknown comparison type!");
2962 case Instruction::SetEQ:
2963 return ReplaceInstUsesWith(I, ConstantBool::False);
2964 case Instruction::SetNE:
2965 return ReplaceInstUsesWith(I, ConstantBool::True);
2966 case Instruction::SetLT:
2967 case Instruction::SetLE:
2968 if (DestTy->isSigned() && HasSignBit)
2969 return ReplaceInstUsesWith(I, ConstantBool::False);
2970 return ReplaceInstUsesWith(I, ConstantBool::True);
2971 case Instruction::SetGT:
2972 case Instruction::SetGE:
2973 if (DestTy->isSigned() && HasSignBit)
2974 return ReplaceInstUsesWith(I, ConstantBool::True);
2975 return ReplaceInstUsesWith(I, ConstantBool::False);
2976 }
2977 }
2978
2979 // Otherwise, we can replace the setcc with a setcc of the smaller
2980 // operand value.
2981 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2982 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2983 }
2984 }
2985 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002986 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002987}
2988
Reid Spencer279fa252004-11-28 21:31:15 +00002989// visitSetCondInstWithCastAndConstant - this method is part of the
2990// visitSetCondInst method. It handles the situation where we have:
2991// (setcc (cast X to larger), CI)
2992// It tries to remove the cast and even the setcc if the CI value
2993// and range of the cast allow it.
2994Instruction *
2995InstCombiner::visitSetCondInstWithCastAndConstant(BinaryOperator&I,
2996 CastInst* LHSI,
2997 ConstantInt* CI) {
2998 const Type *SrcTy = LHSI->getOperand(0)->getType();
2999 const Type *DestTy = LHSI->getType();
Chris Lattner03f06f12005-01-17 03:20:02 +00003000 if (!SrcTy->isIntegral() || !DestTy->isIntegral())
3001 return 0;
3002
3003 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
3004 unsigned DestBits = DestTy->getPrimitiveSize()*8;
3005 if (SrcTy == Type::BoolTy)
3006 SrcBits = 1;
3007 if (DestTy == Type::BoolTy)
3008 DestBits = 1;
3009 if (SrcBits < DestBits) {
3010 // There are fewer bits in the source of the cast than in the result
3011 // of the cast. Any other case doesn't matter because the constant
3012 // value won't have changed due to sign extension.
3013 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
3014 if (ConstantExpr::getCast(NewCst, DestTy) == CI) {
3015 // The constant value operand of the setCC before and after a
3016 // cast to the source type of the cast instruction is the same
3017 // value, so we just replace with the same setcc opcode, but
3018 // using the source value compared to the constant casted to the
3019 // source type.
3020 if (SrcTy->isSigned() && DestTy->isUnsigned()) {
3021 CastInst* Cst = new CastInst(LHSI->getOperand(0),
3022 SrcTy->getUnsignedVersion(),
3023 LHSI->getName());
3024 InsertNewInstBefore(Cst,I);
3025 return new SetCondInst(I.getOpcode(), Cst,
3026 ConstantExpr::getCast(CI,
3027 SrcTy->getUnsignedVersion()));
Reid Spencer279fa252004-11-28 21:31:15 +00003028 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003029 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),NewCst);
3030 }
3031
3032 // The constant value before and after a cast to the source type
3033 // is different, so various cases are possible depending on the
3034 // opcode and the signs of the types involved in the cast.
3035 switch (I.getOpcode()) {
3036 case Instruction::SetLT: {
3037 return 0;
3038 Constant* Max = ConstantIntegral::getMaxValue(SrcTy);
3039 Max = ConstantExpr::getCast(Max, DestTy);
3040 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
3041 }
3042 case Instruction::SetGT: {
3043 return 0; // FIXME! RENABLE. This breaks for (cast sbyte to uint) > 255
3044 Constant* Min = ConstantIntegral::getMinValue(SrcTy);
3045 Min = ConstantExpr::getCast(Min, DestTy);
3046 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
3047 }
3048 case Instruction::SetEQ:
3049 // We're looking for equality, and we know the values are not
3050 // equal so replace with constant False.
3051 return ReplaceInstUsesWith(I, ConstantBool::False);
3052 case Instruction::SetNE:
3053 // We're testing for inequality, and we know the values are not
3054 // equal so replace with constant True.
3055 return ReplaceInstUsesWith(I, ConstantBool::True);
3056 case Instruction::SetLE:
3057 case Instruction::SetGE:
3058 assert(0 && "SetLE and SetGE should be handled elsewhere");
3059 default:
3060 assert(0 && "unknown integer comparison");
Reid Spencer279fa252004-11-28 21:31:15 +00003061 }
3062 }
3063 return 0;
3064}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003065
3066
Chris Lattnere8d6c602003-03-10 19:16:08 +00003067Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003068 assert(I.getOperand(1)->getType() == Type::UByteTy);
3069 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003070 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003071
3072 // shl X, 0 == X and shr X, 0 == X
3073 // shl 0, X == 0 and shr 0, X == 0
3074 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003075 Op0 == Constant::getNullValue(Op0->getType()))
3076 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003077
Chris Lattner81a7a232004-10-16 18:11:37 +00003078 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3079 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003080 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003081 else // undef << X -> 0 AND undef >>u X -> 0
3082 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3083 }
3084 if (isa<UndefValue>(Op1)) {
3085 if (isLeftShift || I.getType()->isUnsigned())
3086 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3087 else
3088 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3089 }
3090
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003091 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3092 if (!isLeftShift)
3093 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3094 if (CSI->isAllOnesValue())
3095 return ReplaceInstUsesWith(I, CSI);
3096
Chris Lattner183b3362004-04-09 19:05:30 +00003097 // Try to fold constant and into select arguments.
3098 if (isa<Constant>(Op0))
3099 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003100 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003101 return R;
3102
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003103 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003104 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3105 // of a signed value.
3106 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00003107 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003108 if (CUI->getValue() >= TypeBits) {
3109 if (!Op0->getType()->isSigned() || isLeftShift)
3110 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3111 else {
3112 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3113 return &I;
3114 }
3115 }
Chris Lattner55f3d942002-09-10 23:04:09 +00003116
Chris Lattnerede3fe02003-08-13 04:18:28 +00003117 // ((X*C1) << C2) == (X * (C1 << C2))
3118 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3119 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3120 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003121 return BinaryOperator::createMul(BO->getOperand(0),
3122 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00003123
Chris Lattner183b3362004-04-09 19:05:30 +00003124 // Try to fold constant and into select arguments.
3125 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003126 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003127 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003128 if (isa<PHINode>(Op0))
3129 if (Instruction *NV = FoldOpIntoPhi(I))
3130 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00003131
Chris Lattner86102b82005-01-01 16:22:27 +00003132 if (Op0->hasOneUse()) {
3133 // If this is a SHL of a sign-extending cast, see if we can turn the input
3134 // into a zero extending cast (a simple strength reduction).
3135 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3136 const Type *SrcTy = CI->getOperand(0)->getType();
3137 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3138 SrcTy->getPrimitiveSize() < CI->getType()->getPrimitiveSize()) {
3139 // We can change it to a zero extension if we are shifting out all of
3140 // the sign extended bits. To check this, form a mask of all of the
3141 // sign extend bits, then shift them left and see if we have anything
3142 // left.
3143 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3144 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3145 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3146 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3147 // If the shift is nuking all of the sign bits, change this to a
3148 // zero extension cast. To do this, cast the cast input to
3149 // unsigned, then to the requested size.
3150 Value *CastOp = CI->getOperand(0);
3151 Instruction *NC =
3152 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3153 CI->getName()+".uns");
3154 NC = InsertNewInstBefore(NC, I);
3155 // Finally, insert a replacement for CI.
3156 NC = new CastInst(NC, CI->getType(), CI->getName());
3157 CI->setName("");
3158 NC = InsertNewInstBefore(NC, I);
3159 WorkList.push_back(CI); // Delete CI later.
3160 I.setOperand(0, NC);
3161 return &I; // The SHL operand was modified.
3162 }
3163 }
3164 }
3165
3166 // If the operand is an bitwise operator with a constant RHS, and the
3167 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003168 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
3169 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3170 bool isValid = true; // Valid only for And, Or, Xor
3171 bool highBitSet = false; // Transform if high bit of constant set?
3172
3173 switch (Op0BO->getOpcode()) {
3174 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003175 case Instruction::Add:
3176 isValid = isLeftShift;
3177 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003178 case Instruction::Or:
3179 case Instruction::Xor:
3180 highBitSet = false;
3181 break;
3182 case Instruction::And:
3183 highBitSet = true;
3184 break;
3185 }
3186
3187 // If this is a signed shift right, and the high bit is modified
3188 // by the logical operation, do not perform the transformation.
3189 // The highBitSet boolean indicates the value of the high bit of
3190 // the constant which would cause it to be modified for this
3191 // operation.
3192 //
3193 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3194 uint64_t Val = Op0C->getRawValue();
3195 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3196 }
3197
3198 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003199 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003200
3201 Instruction *NewShift =
3202 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3203 Op0BO->getName());
3204 Op0BO->setName("");
3205 InsertNewInstBefore(NewShift, I);
3206
3207 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3208 NewRHS);
3209 }
3210 }
Chris Lattner86102b82005-01-01 16:22:27 +00003211 }
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003212
Chris Lattner3204d4e2003-07-24 17:52:58 +00003213 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003214 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00003215 if (ConstantUInt *ShiftAmt1C =
3216 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003217 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3218 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
Chris Lattner3204d4e2003-07-24 17:52:58 +00003219
3220 // Check for (A << c1) << c2 and (A >> c1) >> c2
3221 if (I.getOpcode() == Op0SI->getOpcode()) {
3222 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003223 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
3224 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00003225 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3226 ConstantUInt::get(Type::UByteTy, Amt));
3227 }
3228
Chris Lattnerab780df2003-07-24 18:38:56 +00003229 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3230 // signed types, we can only support the (A >> c1) << c2 configuration,
3231 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003232 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003233 // Calculate bitmask for what gets shifted off the edge...
3234 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003235 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003236 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003237 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003238 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00003239
3240 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003241 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3242 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00003243 InsertNewInstBefore(Mask, I);
3244
3245 // Figure out what flavor of shift we should use...
3246 if (ShiftAmt1 == ShiftAmt2)
3247 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3248 else if (ShiftAmt1 < ShiftAmt2) {
3249 return new ShiftInst(I.getOpcode(), Mask,
3250 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3251 } else {
3252 return new ShiftInst(Op0SI->getOpcode(), Mask,
3253 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3254 }
3255 }
3256 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003257 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00003258
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003259 return 0;
3260}
3261
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003262enum CastType {
3263 Noop = 0,
3264 Truncate = 1,
3265 Signext = 2,
3266 Zeroext = 3
3267};
3268
3269/// getCastType - In the future, we will split the cast instruction into these
3270/// various types. Until then, we have to do the analysis here.
3271static CastType getCastType(const Type *Src, const Type *Dest) {
3272 assert(Src->isIntegral() && Dest->isIntegral() &&
3273 "Only works on integral types!");
3274 unsigned SrcSize = Src->getPrimitiveSize()*8;
3275 if (Src == Type::BoolTy) SrcSize = 1;
3276 unsigned DestSize = Dest->getPrimitiveSize()*8;
3277 if (Dest == Type::BoolTy) DestSize = 1;
3278
3279 if (SrcSize == DestSize) return Noop;
3280 if (SrcSize > DestSize) return Truncate;
3281 if (Src->isSigned()) return Signext;
3282 return Zeroext;
3283}
3284
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003285
Chris Lattner48a44f72002-05-02 17:06:02 +00003286// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3287// instruction.
3288//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003289static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00003290 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003291
Chris Lattner650b6da2002-08-02 20:00:25 +00003292 // It is legal to eliminate the instruction if casting A->B->A if the sizes
3293 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003294 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003295 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003296 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003297
Chris Lattner4fbad962004-07-21 04:27:24 +00003298 // If we are casting between pointer and integer types, treat pointers as
3299 // integers of the appropriate size for the code below.
3300 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3301 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3302 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003303
Chris Lattner48a44f72002-05-02 17:06:02 +00003304 // Allow free casting and conversion of sizes as long as the sign doesn't
3305 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003306 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003307 CastType FirstCast = getCastType(SrcTy, MidTy);
3308 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003309
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003310 // Capture the effect of these two casts. If the result is a legal cast,
3311 // the CastType is stored here, otherwise a special code is used.
3312 static const unsigned CastResult[] = {
3313 // First cast is noop
3314 0, 1, 2, 3,
3315 // First cast is a truncate
3316 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3317 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003318 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003319 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003320 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003321 };
3322
3323 unsigned Result = CastResult[FirstCast*4+SecondCast];
3324 switch (Result) {
3325 default: assert(0 && "Illegal table value!");
3326 case 0:
3327 case 1:
3328 case 2:
3329 case 3:
3330 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3331 // truncates, we could eliminate more casts.
3332 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3333 case 4:
3334 return false; // Not possible to eliminate this here.
3335 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00003336 // Sign or zero extend followed by truncate is always ok if the result
3337 // is a truncate or noop.
3338 CastType ResultCast = getCastType(SrcTy, DstTy);
3339 if (ResultCast == Noop || ResultCast == Truncate)
3340 return true;
3341 // Otherwise we are still growing the value, we are only safe if the
3342 // result will match the sign/zeroextendness of the result.
3343 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00003344 }
Chris Lattner650b6da2002-08-02 20:00:25 +00003345 }
Chris Lattner48a44f72002-05-02 17:06:02 +00003346 return false;
3347}
3348
Chris Lattner11ffd592004-07-20 05:21:00 +00003349static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003350 if (V->getType() == Ty || isa<Constant>(V)) return false;
3351 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00003352 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3353 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003354 return false;
3355 return true;
3356}
3357
3358/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3359/// InsertBefore instruction. This is specialized a bit to avoid inserting
3360/// casts that are known to not do anything...
3361///
3362Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3363 Instruction *InsertBefore) {
3364 if (V->getType() == DestTy) return V;
3365 if (Constant *C = dyn_cast<Constant>(V))
3366 return ConstantExpr::getCast(C, DestTy);
3367
3368 CastInst *CI = new CastInst(V, DestTy, V->getName());
3369 InsertNewInstBefore(CI, *InsertBefore);
3370 return CI;
3371}
Chris Lattner48a44f72002-05-02 17:06:02 +00003372
3373// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00003374//
Chris Lattner113f4f42002-06-25 16:13:24 +00003375Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00003376 Value *Src = CI.getOperand(0);
3377
Chris Lattner48a44f72002-05-02 17:06:02 +00003378 // If the user is casting a value to the same type, eliminate this cast
3379 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00003380 if (CI.getType() == Src->getType())
3381 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00003382
Chris Lattner81a7a232004-10-16 18:11:37 +00003383 if (isa<UndefValue>(Src)) // cast undef -> undef
3384 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3385
Chris Lattner48a44f72002-05-02 17:06:02 +00003386 // If casting the result of another cast instruction, try to eliminate this
3387 // one!
3388 //
Chris Lattner86102b82005-01-01 16:22:27 +00003389 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3390 Value *A = CSrc->getOperand(0);
3391 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3392 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003393 // This instruction now refers directly to the cast's src operand. This
3394 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00003395 CI.setOperand(0, CSrc->getOperand(0));
3396 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00003397 }
3398
Chris Lattner650b6da2002-08-02 20:00:25 +00003399 // If this is an A->B->A cast, and we are dealing with integral types, try
3400 // to convert this into a logical 'and' instruction.
3401 //
Chris Lattner86102b82005-01-01 16:22:27 +00003402 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003403 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00003404 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
3405 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()&&
3406 A->getType()->getPrimitiveSize() == CI.getType()->getPrimitiveSize()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00003407 assert(CSrc->getType() != Type::ULongTy &&
3408 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00003409 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner86102b82005-01-01 16:22:27 +00003410 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3411 AndValue);
3412 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3413 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3414 if (And->getType() != CI.getType()) {
3415 And->setName(CSrc->getName()+".mask");
3416 InsertNewInstBefore(And, CI);
3417 And = new CastInst(And, CI.getType());
3418 }
3419 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00003420 }
3421 }
Chris Lattner86102b82005-01-01 16:22:27 +00003422
Chris Lattner03841652004-05-25 04:29:21 +00003423 // If this is a cast to bool, turn it into the appropriate setne instruction.
3424 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003425 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00003426 Constant::getNullValue(CI.getOperand(0)->getType()));
3427
Chris Lattnerd0d51602003-06-21 23:12:02 +00003428 // If casting the result of a getelementptr instruction with no offset, turn
3429 // this into a cast of the original pointer!
3430 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00003431 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00003432 bool AllZeroOperands = true;
3433 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3434 if (!isa<Constant>(GEP->getOperand(i)) ||
3435 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3436 AllZeroOperands = false;
3437 break;
3438 }
3439 if (AllZeroOperands) {
3440 CI.setOperand(0, GEP->getOperand(0));
3441 return &CI;
3442 }
3443 }
3444
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003445 // If we are casting a malloc or alloca to a pointer to a type of the same
3446 // size, rewrite the allocation instruction to allocate the "right" type.
3447 //
3448 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00003449 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003450 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
3451 // Get the type really allocated and the type casted to...
3452 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003453 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003454 if (AllocElTy->isSized() && CastElTy->isSized()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003455 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3456 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00003457
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003458 // If the allocation is for an even multiple of the cast type size
3459 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
3460 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003461 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003462 std::string Name = AI->getName(); AI->setName("");
3463 AllocationInst *New;
3464 if (isa<MallocInst>(AI))
3465 New = new MallocInst(CastElTy, Amt, Name);
3466 else
3467 New = new AllocaInst(CastElTy, Amt, Name);
3468 InsertNewInstBefore(New, *AI);
3469 return ReplaceInstUsesWith(CI, New);
3470 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003471 }
3472 }
3473
Chris Lattner86102b82005-01-01 16:22:27 +00003474 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
3475 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
3476 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003477 if (isa<PHINode>(Src))
3478 if (Instruction *NV = FoldOpIntoPhi(CI))
3479 return NV;
3480
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003481 // If the source value is an instruction with only this use, we can attempt to
3482 // propagate the cast into the instruction. Also, only handle integral types
3483 // for now.
3484 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003485 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003486 CI.getType()->isInteger()) { // Don't mess with casts to bool here
3487 const Type *DestTy = CI.getType();
3488 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
3489 unsigned DestBitSize = getTypeSizeInBits(DestTy);
3490
3491 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3492 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3493
3494 switch (SrcI->getOpcode()) {
3495 case Instruction::Add:
3496 case Instruction::Mul:
3497 case Instruction::And:
3498 case Instruction::Or:
3499 case Instruction::Xor:
3500 // If we are discarding information, or just changing the sign, rewrite.
3501 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3502 // Don't insert two casts if they cannot be eliminated. We allow two
3503 // casts to be inserted if the sizes are the same. This could only be
3504 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00003505 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3506 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003507 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3508 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3509 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3510 ->getOpcode(), Op0c, Op1c);
3511 }
3512 }
3513 break;
3514 case Instruction::Shl:
3515 // Allow changing the sign of the source operand. Do not allow changing
3516 // the size of the shift, UNLESS the shift amount is a constant. We
3517 // mush not change variable sized shifts to a smaller size, because it
3518 // is undefined to shift more bits out than exist in the value.
3519 if (DestBitSize == SrcBitSize ||
3520 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3521 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3522 return new ShiftInst(Instruction::Shl, Op0c, Op1);
3523 }
3524 break;
3525 }
3526 }
3527
Chris Lattner260ab202002-04-18 17:39:14 +00003528 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00003529}
3530
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003531/// GetSelectFoldableOperands - We want to turn code that looks like this:
3532/// %C = or %A, %B
3533/// %D = select %cond, %C, %A
3534/// into:
3535/// %C = select %cond, %B, 0
3536/// %D = or %A, %C
3537///
3538/// Assuming that the specified instruction is an operand to the select, return
3539/// a bitmask indicating which operands of this instruction are foldable if they
3540/// equal the other incoming value of the select.
3541///
3542static unsigned GetSelectFoldableOperands(Instruction *I) {
3543 switch (I->getOpcode()) {
3544 case Instruction::Add:
3545 case Instruction::Mul:
3546 case Instruction::And:
3547 case Instruction::Or:
3548 case Instruction::Xor:
3549 return 3; // Can fold through either operand.
3550 case Instruction::Sub: // Can only fold on the amount subtracted.
3551 case Instruction::Shl: // Can only fold on the shift amount.
3552 case Instruction::Shr:
3553 return 1;
3554 default:
3555 return 0; // Cannot fold
3556 }
3557}
3558
3559/// GetSelectFoldableConstant - For the same transformation as the previous
3560/// function, return the identity constant that goes into the select.
3561static Constant *GetSelectFoldableConstant(Instruction *I) {
3562 switch (I->getOpcode()) {
3563 default: assert(0 && "This cannot happen!"); abort();
3564 case Instruction::Add:
3565 case Instruction::Sub:
3566 case Instruction::Or:
3567 case Instruction::Xor:
3568 return Constant::getNullValue(I->getType());
3569 case Instruction::Shl:
3570 case Instruction::Shr:
3571 return Constant::getNullValue(Type::UByteTy);
3572 case Instruction::And:
3573 return ConstantInt::getAllOnesValue(I->getType());
3574 case Instruction::Mul:
3575 return ConstantInt::get(I->getType(), 1);
3576 }
3577}
3578
Chris Lattner411336f2005-01-19 21:50:18 +00003579/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
3580/// have the same opcode and only one use each. Try to simplify this.
3581Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
3582 Instruction *FI) {
3583 if (TI->getNumOperands() == 1) {
3584 // If this is a non-volatile load or a cast from the same type,
3585 // merge.
3586 if (TI->getOpcode() == Instruction::Cast) {
3587 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
3588 return 0;
3589 } else {
3590 return 0; // unknown unary op.
3591 }
3592
3593 // Fold this by inserting a select from the input values.
3594 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
3595 FI->getOperand(0), SI.getName()+".v");
3596 InsertNewInstBefore(NewSI, SI);
3597 return new CastInst(NewSI, TI->getType());
3598 }
3599
3600 // Only handle binary operators here.
3601 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
3602 return 0;
3603
3604 // Figure out if the operations have any operands in common.
3605 Value *MatchOp, *OtherOpT, *OtherOpF;
3606 bool MatchIsOpZero;
3607 if (TI->getOperand(0) == FI->getOperand(0)) {
3608 MatchOp = TI->getOperand(0);
3609 OtherOpT = TI->getOperand(1);
3610 OtherOpF = FI->getOperand(1);
3611 MatchIsOpZero = true;
3612 } else if (TI->getOperand(1) == FI->getOperand(1)) {
3613 MatchOp = TI->getOperand(1);
3614 OtherOpT = TI->getOperand(0);
3615 OtherOpF = FI->getOperand(0);
3616 MatchIsOpZero = false;
3617 } else if (!TI->isCommutative()) {
3618 return 0;
3619 } else if (TI->getOperand(0) == FI->getOperand(1)) {
3620 MatchOp = TI->getOperand(0);
3621 OtherOpT = TI->getOperand(1);
3622 OtherOpF = FI->getOperand(0);
3623 MatchIsOpZero = true;
3624 } else if (TI->getOperand(1) == FI->getOperand(0)) {
3625 MatchOp = TI->getOperand(1);
3626 OtherOpT = TI->getOperand(0);
3627 OtherOpF = FI->getOperand(1);
3628 MatchIsOpZero = true;
3629 } else {
3630 return 0;
3631 }
3632
3633 // If we reach here, they do have operations in common.
3634 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
3635 OtherOpF, SI.getName()+".v");
3636 InsertNewInstBefore(NewSI, SI);
3637
3638 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
3639 if (MatchIsOpZero)
3640 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
3641 else
3642 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
3643 } else {
3644 if (MatchIsOpZero)
3645 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
3646 else
3647 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
3648 }
3649}
3650
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003651Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00003652 Value *CondVal = SI.getCondition();
3653 Value *TrueVal = SI.getTrueValue();
3654 Value *FalseVal = SI.getFalseValue();
3655
3656 // select true, X, Y -> X
3657 // select false, X, Y -> Y
3658 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003659 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00003660 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003661 else {
3662 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00003663 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003664 }
Chris Lattner533bc492004-03-30 19:37:13 +00003665
3666 // select C, X, X -> X
3667 if (TrueVal == FalseVal)
3668 return ReplaceInstUsesWith(SI, TrueVal);
3669
Chris Lattner81a7a232004-10-16 18:11:37 +00003670 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3671 return ReplaceInstUsesWith(SI, FalseVal);
3672 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3673 return ReplaceInstUsesWith(SI, TrueVal);
3674 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3675 if (isa<Constant>(TrueVal))
3676 return ReplaceInstUsesWith(SI, TrueVal);
3677 else
3678 return ReplaceInstUsesWith(SI, FalseVal);
3679 }
3680
Chris Lattner1c631e82004-04-08 04:43:23 +00003681 if (SI.getType() == Type::BoolTy)
3682 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3683 if (C == ConstantBool::True) {
3684 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003685 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003686 } else {
3687 // Change: A = select B, false, C --> A = and !B, C
3688 Value *NotCond =
3689 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3690 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003691 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003692 }
3693 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3694 if (C == ConstantBool::False) {
3695 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003696 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003697 } else {
3698 // Change: A = select B, C, true --> A = or !B, C
3699 Value *NotCond =
3700 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3701 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003702 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003703 }
3704 }
3705
Chris Lattner183b3362004-04-09 19:05:30 +00003706 // Selecting between two integer constants?
3707 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3708 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3709 // select C, 1, 0 -> cast C to int
3710 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3711 return new CastInst(CondVal, SI.getType());
3712 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3713 // select C, 0, 1 -> cast !C to int
3714 Value *NotCond =
3715 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00003716 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00003717 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00003718 }
Chris Lattner35167c32004-06-09 07:59:58 +00003719
3720 // If one of the constants is zero (we know they can't both be) and we
3721 // have a setcc instruction with zero, and we have an 'and' with the
3722 // non-constant value, eliminate this whole mess. This corresponds to
3723 // cases like this: ((X & 27) ? 27 : 0)
3724 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3725 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3726 if ((IC->getOpcode() == Instruction::SetEQ ||
3727 IC->getOpcode() == Instruction::SetNE) &&
3728 isa<ConstantInt>(IC->getOperand(1)) &&
3729 cast<Constant>(IC->getOperand(1))->isNullValue())
3730 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3731 if (ICA->getOpcode() == Instruction::And &&
3732 isa<ConstantInt>(ICA->getOperand(1)) &&
3733 (ICA->getOperand(1) == TrueValC ||
3734 ICA->getOperand(1) == FalseValC) &&
3735 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3736 // Okay, now we know that everything is set up, we just don't
3737 // know whether we have a setne or seteq and whether the true or
3738 // false val is the zero.
3739 bool ShouldNotVal = !TrueValC->isNullValue();
3740 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3741 Value *V = ICA;
3742 if (ShouldNotVal)
3743 V = InsertNewInstBefore(BinaryOperator::create(
3744 Instruction::Xor, V, ICA->getOperand(1)), SI);
3745 return ReplaceInstUsesWith(SI, V);
3746 }
Chris Lattner533bc492004-03-30 19:37:13 +00003747 }
Chris Lattner623fba12004-04-10 22:21:27 +00003748
3749 // See if we are selecting two values based on a comparison of the two values.
3750 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3751 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3752 // Transform (X == Y) ? X : Y -> Y
3753 if (SCI->getOpcode() == Instruction::SetEQ)
3754 return ReplaceInstUsesWith(SI, FalseVal);
3755 // Transform (X != Y) ? X : Y -> X
3756 if (SCI->getOpcode() == Instruction::SetNE)
3757 return ReplaceInstUsesWith(SI, TrueVal);
3758 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3759
3760 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3761 // Transform (X == Y) ? Y : X -> X
3762 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003763 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003764 // Transform (X != Y) ? Y : X -> Y
3765 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003766 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003767 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3768 }
3769 }
Chris Lattner1c631e82004-04-08 04:43:23 +00003770
Chris Lattnera04c9042005-01-13 22:52:24 +00003771 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
3772 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
3773 if (TI->hasOneUse() && FI->hasOneUse()) {
3774 bool isInverse = false;
3775 Instruction *AddOp = 0, *SubOp = 0;
3776
Chris Lattner411336f2005-01-19 21:50:18 +00003777 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
3778 if (TI->getOpcode() == FI->getOpcode())
3779 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
3780 return IV;
3781
3782 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
3783 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00003784 if (TI->getOpcode() == Instruction::Sub &&
3785 FI->getOpcode() == Instruction::Add) {
3786 AddOp = FI; SubOp = TI;
3787 } else if (FI->getOpcode() == Instruction::Sub &&
3788 TI->getOpcode() == Instruction::Add) {
3789 AddOp = TI; SubOp = FI;
3790 }
3791
3792 if (AddOp) {
3793 Value *OtherAddOp = 0;
3794 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
3795 OtherAddOp = AddOp->getOperand(1);
3796 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
3797 OtherAddOp = AddOp->getOperand(0);
3798 }
3799
3800 if (OtherAddOp) {
3801 // So at this point we know we have:
3802 // select C, (add X, Y), (sub X, ?)
3803 // We can do the transform profitably if either 'Y' = '?' or '?' is
3804 // a constant.
3805 if (SubOp->getOperand(1) == AddOp ||
3806 isa<Constant>(SubOp->getOperand(1))) {
3807 Value *NegVal;
3808 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
3809 NegVal = ConstantExpr::getNeg(C);
3810 } else {
3811 NegVal = InsertNewInstBefore(
3812 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
3813 }
3814
Chris Lattner51726c42005-01-14 17:35:12 +00003815 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00003816 Value *NewFalseOp = NegVal;
3817 if (AddOp != TI)
3818 std::swap(NewTrueOp, NewFalseOp);
3819 Instruction *NewSel =
3820 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
3821
3822 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00003823 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00003824 }
3825 }
3826 }
3827 }
3828
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003829 // See if we can fold the select into one of our operands.
3830 if (SI.getType()->isInteger()) {
3831 // See the comment above GetSelectFoldableOperands for a description of the
3832 // transformation we are doing here.
3833 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3834 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3835 !isa<Constant>(FalseVal))
3836 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3837 unsigned OpToFold = 0;
3838 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3839 OpToFold = 1;
3840 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3841 OpToFold = 2;
3842 }
3843
3844 if (OpToFold) {
3845 Constant *C = GetSelectFoldableConstant(TVI);
3846 std::string Name = TVI->getName(); TVI->setName("");
3847 Instruction *NewSel =
3848 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3849 Name);
3850 InsertNewInstBefore(NewSel, SI);
3851 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3852 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3853 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3854 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3855 else {
3856 assert(0 && "Unknown instruction!!");
3857 }
3858 }
3859 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003860
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003861 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3862 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3863 !isa<Constant>(TrueVal))
3864 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3865 unsigned OpToFold = 0;
3866 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3867 OpToFold = 1;
3868 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3869 OpToFold = 2;
3870 }
3871
3872 if (OpToFold) {
3873 Constant *C = GetSelectFoldableConstant(FVI);
3874 std::string Name = FVI->getName(); FVI->setName("");
3875 Instruction *NewSel =
3876 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3877 Name);
3878 InsertNewInstBefore(NewSel, SI);
3879 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3880 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3881 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3882 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3883 else {
3884 assert(0 && "Unknown instruction!!");
3885 }
3886 }
3887 }
3888 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003889 return 0;
3890}
3891
3892
Chris Lattner970c33a2003-06-19 17:00:31 +00003893// CallInst simplification
3894//
3895Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003896 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3897 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00003898 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3899 bool Changed = false;
3900
3901 // memmove/cpy/set of zero bytes is a noop.
3902 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3903 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3904
3905 // FIXME: Increase alignment here.
3906
3907 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3908 if (CI->getRawValue() == 1) {
3909 // Replace the instruction with just byte operations. We would
3910 // transform other cases to loads/stores, but we don't know if
3911 // alignment is sufficient.
3912 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003913 }
3914
Chris Lattner00648e12004-10-12 04:52:52 +00003915 // If we have a memmove and the source operation is a constant global,
3916 // then the source and dest pointers can't alias, so we can change this
3917 // into a call to memcpy.
3918 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3919 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3920 if (GVSrc->isConstant()) {
3921 Module *M = CI.getParent()->getParent()->getParent();
3922 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3923 CI.getCalledFunction()->getFunctionType());
3924 CI.setOperand(0, MemCpy);
3925 Changed = true;
3926 }
3927
3928 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00003929 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
3930 // If this stoppoint is at the same source location as the previous
3931 // stoppoint in the chain, it is not needed.
3932 if (DbgStopPointInst *PrevSPI =
3933 dyn_cast<DbgStopPointInst>(SPI->getChain()))
3934 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
3935 SPI->getColNo() == PrevSPI->getColNo()) {
3936 SPI->replaceAllUsesWith(PrevSPI);
3937 return EraseInstFromFunction(CI);
3938 }
Chris Lattner00648e12004-10-12 04:52:52 +00003939 }
3940
Chris Lattneraec3d942003-10-07 22:32:43 +00003941 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003942}
3943
3944// InvokeInst simplification
3945//
3946Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003947 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003948}
3949
Chris Lattneraec3d942003-10-07 22:32:43 +00003950// visitCallSite - Improvements for call and invoke instructions.
3951//
3952Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003953 bool Changed = false;
3954
3955 // If the callee is a constexpr cast of a function, attempt to move the cast
3956 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003957 if (transformConstExprCastCall(CS)) return 0;
3958
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003959 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00003960
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003961 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3962 // This instruction is not reachable, just remove it. We insert a store to
3963 // undef so that we know that this code is not reachable, despite the fact
3964 // that we can't modify the CFG here.
3965 new StoreInst(ConstantBool::True,
3966 UndefValue::get(PointerType::get(Type::BoolTy)),
3967 CS.getInstruction());
3968
3969 if (!CS.getInstruction()->use_empty())
3970 CS.getInstruction()->
3971 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3972
3973 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3974 // Don't break the CFG, insert a dummy cond branch.
3975 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3976 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00003977 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003978 return EraseInstFromFunction(*CS.getInstruction());
3979 }
Chris Lattner81a7a232004-10-16 18:11:37 +00003980
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003981 const PointerType *PTy = cast<PointerType>(Callee->getType());
3982 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3983 if (FTy->isVarArg()) {
3984 // See if we can optimize any arguments passed through the varargs area of
3985 // the call.
3986 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3987 E = CS.arg_end(); I != E; ++I)
3988 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3989 // If this cast does not effect the value passed through the varargs
3990 // area, we can eliminate the use of the cast.
3991 Value *Op = CI->getOperand(0);
3992 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3993 *I = Op;
3994 Changed = true;
3995 }
3996 }
3997 }
Chris Lattneraec3d942003-10-07 22:32:43 +00003998
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003999 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00004000}
4001
Chris Lattner970c33a2003-06-19 17:00:31 +00004002// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4003// attempt to move the cast to the arguments of the call/invoke.
4004//
4005bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4006 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4007 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00004008 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00004009 return false;
Reid Spencer87436872004-07-18 00:38:32 +00004010 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00004011 Instruction *Caller = CS.getInstruction();
4012
4013 // Okay, this is a cast from a function to a different type. Unless doing so
4014 // would cause a type conversion of one of our arguments, change this call to
4015 // be a direct call with arguments casted to the appropriate types.
4016 //
4017 const FunctionType *FT = Callee->getFunctionType();
4018 const Type *OldRetTy = Caller->getType();
4019
Chris Lattner1f7942f2004-01-14 06:06:08 +00004020 // Check to see if we are changing the return type...
4021 if (OldRetTy != FT->getReturnType()) {
4022 if (Callee->isExternal() &&
4023 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4024 !Caller->use_empty())
4025 return false; // Cannot transform this return value...
4026
4027 // If the callsite is an invoke instruction, and the return value is used by
4028 // a PHI node in a successor, we cannot change the return type of the call
4029 // because there is no place to put the cast instruction (without breaking
4030 // the critical edge). Bail out in this case.
4031 if (!Caller->use_empty())
4032 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4033 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4034 UI != E; ++UI)
4035 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4036 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004037 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00004038 return false;
4039 }
Chris Lattner970c33a2003-06-19 17:00:31 +00004040
4041 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4042 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4043
4044 CallSite::arg_iterator AI = CS.arg_begin();
4045 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4046 const Type *ParamTy = FT->getParamType(i);
4047 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
4048 if (Callee->isExternal() && !isConvertible) return false;
4049 }
4050
4051 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4052 Callee->isExternal())
4053 return false; // Do not delete arguments unless we have a function body...
4054
4055 // Okay, we decided that this is a safe thing to do: go ahead and start
4056 // inserting cast instructions as necessary...
4057 std::vector<Value*> Args;
4058 Args.reserve(NumActualArgs);
4059
4060 AI = CS.arg_begin();
4061 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4062 const Type *ParamTy = FT->getParamType(i);
4063 if ((*AI)->getType() == ParamTy) {
4064 Args.push_back(*AI);
4065 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00004066 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4067 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00004068 }
4069 }
4070
4071 // If the function takes more arguments than the call was taking, add them
4072 // now...
4073 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4074 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4075
4076 // If we are removing arguments to the function, emit an obnoxious warning...
4077 if (FT->getNumParams() < NumActualArgs)
4078 if (!FT->isVarArg()) {
4079 std::cerr << "WARNING: While resolving call to function '"
4080 << Callee->getName() << "' arguments were dropped!\n";
4081 } else {
4082 // Add all of the arguments in their promoted form to the arg list...
4083 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4084 const Type *PTy = getPromotedType((*AI)->getType());
4085 if (PTy != (*AI)->getType()) {
4086 // Must promote to pass through va_arg area!
4087 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4088 InsertNewInstBefore(Cast, *Caller);
4089 Args.push_back(Cast);
4090 } else {
4091 Args.push_back(*AI);
4092 }
4093 }
4094 }
4095
4096 if (FT->getReturnType() == Type::VoidTy)
4097 Caller->setName(""); // Void type should not have a name...
4098
4099 Instruction *NC;
4100 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004101 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00004102 Args, Caller->getName(), Caller);
4103 } else {
4104 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
4105 }
4106
4107 // Insert a cast of the return type as necessary...
4108 Value *NV = NC;
4109 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4110 if (NV->getType() != Type::VoidTy) {
4111 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00004112
4113 // If this is an invoke instruction, we should insert it after the first
4114 // non-phi, instruction in the normal successor block.
4115 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4116 BasicBlock::iterator I = II->getNormalDest()->begin();
4117 while (isa<PHINode>(I)) ++I;
4118 InsertNewInstBefore(NC, *I);
4119 } else {
4120 // Otherwise, it's a call, just insert cast right after the call instr
4121 InsertNewInstBefore(NC, *Caller);
4122 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004123 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00004124 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00004125 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00004126 }
4127 }
4128
4129 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4130 Caller->replaceAllUsesWith(NV);
4131 Caller->getParent()->getInstList().erase(Caller);
4132 removeFromWorkList(Caller);
4133 return true;
4134}
4135
4136
Chris Lattner7515cab2004-11-14 19:13:23 +00004137// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4138// operator and they all are only used by the PHI, PHI together their
4139// inputs, and do the operation once, to the result of the PHI.
4140Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4141 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4142
4143 // Scan the instruction, looking for input operations that can be folded away.
4144 // If all input operands to the phi are the same instruction (e.g. a cast from
4145 // the same type or "+42") we can pull the operation through the PHI, reducing
4146 // code size and simplifying code.
4147 Constant *ConstantOp = 0;
4148 const Type *CastSrcTy = 0;
4149 if (isa<CastInst>(FirstInst)) {
4150 CastSrcTy = FirstInst->getOperand(0)->getType();
4151 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4152 // Can fold binop or shift if the RHS is a constant.
4153 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4154 if (ConstantOp == 0) return 0;
4155 } else {
4156 return 0; // Cannot fold this operation.
4157 }
4158
4159 // Check to see if all arguments are the same operation.
4160 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4161 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4162 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4163 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4164 return 0;
4165 if (CastSrcTy) {
4166 if (I->getOperand(0)->getType() != CastSrcTy)
4167 return 0; // Cast operation must match.
4168 } else if (I->getOperand(1) != ConstantOp) {
4169 return 0;
4170 }
4171 }
4172
4173 // Okay, they are all the same operation. Create a new PHI node of the
4174 // correct type, and PHI together all of the LHS's of the instructions.
4175 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4176 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00004177 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00004178
4179 Value *InVal = FirstInst->getOperand(0);
4180 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00004181
4182 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00004183 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4184 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4185 if (NewInVal != InVal)
4186 InVal = 0;
4187 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4188 }
4189
4190 Value *PhiVal;
4191 if (InVal) {
4192 // The new PHI unions all of the same values together. This is really
4193 // common, so we handle it intelligently here for compile-time speed.
4194 PhiVal = InVal;
4195 delete NewPN;
4196 } else {
4197 InsertNewInstBefore(NewPN, PN);
4198 PhiVal = NewPN;
4199 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004200
4201 // Insert and return the new operation.
4202 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004203 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00004204 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004205 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004206 else
4207 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00004208 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004209}
Chris Lattner48a44f72002-05-02 17:06:02 +00004210
Chris Lattner71536432005-01-17 05:10:15 +00004211/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4212/// that is dead.
4213static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4214 if (PN->use_empty()) return true;
4215 if (!PN->hasOneUse()) return false;
4216
4217 // Remember this node, and if we find the cycle, return.
4218 if (!PotentiallyDeadPHIs.insert(PN).second)
4219 return true;
4220
4221 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4222 return DeadPHICycle(PU, PotentiallyDeadPHIs);
4223
4224 return false;
4225}
4226
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004227// PHINode simplification
4228//
Chris Lattner113f4f42002-06-25 16:13:24 +00004229Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnere29d6342004-10-17 21:22:38 +00004230 if (Value *V = hasConstantValue(&PN)) {
4231 // If V is an instruction, we have to be certain that it dominates PN.
4232 // However, because we don't have dom info, we can't do a perfect job.
4233 if (Instruction *I = dyn_cast<Instruction>(V)) {
4234 // We know that the instruction dominates the PHI if there are no undef
4235 // values coming in.
Chris Lattner3b92f172004-10-18 01:48:31 +00004236 if (I->getParent() != &I->getParent()->getParent()->front() ||
4237 isa<InvokeInst>(I))
Chris Lattner107c15c2004-10-17 21:31:34 +00004238 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4239 if (isa<UndefValue>(PN.getIncomingValue(i))) {
4240 V = 0;
4241 break;
4242 }
Chris Lattnere29d6342004-10-17 21:22:38 +00004243 }
4244
4245 if (V)
4246 return ReplaceInstUsesWith(PN, V);
4247 }
Chris Lattner4db2d222004-02-16 05:07:08 +00004248
4249 // If the only user of this instruction is a cast instruction, and all of the
4250 // incoming values are constants, change this PHI to merge together the casted
4251 // constants.
4252 if (PN.hasOneUse())
4253 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4254 if (CI->getType() != PN.getType()) { // noop casts will be folded
4255 bool AllConstant = true;
4256 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4257 if (!isa<Constant>(PN.getIncomingValue(i))) {
4258 AllConstant = false;
4259 break;
4260 }
4261 if (AllConstant) {
4262 // Make a new PHI with all casted values.
4263 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4264 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4265 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4266 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4267 PN.getIncomingBlock(i));
4268 }
4269
4270 // Update the cast instruction.
4271 CI->setOperand(0, New);
4272 WorkList.push_back(CI); // revisit the cast instruction to fold.
4273 WorkList.push_back(New); // Make sure to revisit the new Phi
4274 return &PN; // PN is now dead!
4275 }
4276 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004277
4278 // If all PHI operands are the same operation, pull them through the PHI,
4279 // reducing code size.
4280 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4281 PN.getIncomingValue(0)->hasOneUse())
4282 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4283 return Result;
4284
Chris Lattner71536432005-01-17 05:10:15 +00004285 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4286 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4287 // PHI)... break the cycle.
4288 if (PN.hasOneUse())
4289 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4290 std::set<PHINode*> PotentiallyDeadPHIs;
4291 PotentiallyDeadPHIs.insert(&PN);
4292 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4293 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4294 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004295
Chris Lattner91daeb52003-12-19 05:58:40 +00004296 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004297}
4298
Chris Lattner69193f92004-04-05 01:30:19 +00004299static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4300 Instruction *InsertPoint,
4301 InstCombiner *IC) {
4302 unsigned PS = IC->getTargetData().getPointerSize();
4303 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00004304 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4305 // We must insert a cast to ensure we sign-extend.
4306 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4307 V->getName()), *InsertPoint);
4308 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4309 *InsertPoint);
4310}
4311
Chris Lattner48a44f72002-05-02 17:06:02 +00004312
Chris Lattner113f4f42002-06-25 16:13:24 +00004313Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004314 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00004315 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00004316 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004317 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00004318 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004319
Chris Lattner81a7a232004-10-16 18:11:37 +00004320 if (isa<UndefValue>(GEP.getOperand(0)))
4321 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4322
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004323 bool HasZeroPointerIndex = false;
4324 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4325 HasZeroPointerIndex = C->isNullValue();
4326
4327 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00004328 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00004329
Chris Lattner69193f92004-04-05 01:30:19 +00004330 // Eliminate unneeded casts for indices.
4331 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00004332 gep_type_iterator GTI = gep_type_begin(GEP);
4333 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4334 if (isa<SequentialType>(*GTI)) {
4335 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4336 Value *Src = CI->getOperand(0);
4337 const Type *SrcTy = Src->getType();
4338 const Type *DestTy = CI->getType();
4339 if (Src->getType()->isInteger()) {
4340 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
4341 // We can always eliminate a cast from ulong or long to the other.
4342 // We can always eliminate a cast from uint to int or the other on
4343 // 32-bit pointer platforms.
4344 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
4345 MadeChange = true;
4346 GEP.setOperand(i, Src);
4347 }
4348 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4349 SrcTy->getPrimitiveSize() == 4) {
4350 // We can always eliminate a cast from int to [u]long. We can
4351 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4352 // pointer target.
4353 if (SrcTy->isSigned() ||
4354 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
4355 MadeChange = true;
4356 GEP.setOperand(i, Src);
4357 }
Chris Lattner69193f92004-04-05 01:30:19 +00004358 }
4359 }
4360 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00004361 // If we are using a wider index than needed for this platform, shrink it
4362 // to what we need. If the incoming value needs a cast instruction,
4363 // insert it. This explicit cast can make subsequent optimizations more
4364 // obvious.
4365 Value *Op = GEP.getOperand(i);
4366 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004367 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00004368 GEP.setOperand(i, ConstantExpr::getCast(C,
4369 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004370 MadeChange = true;
4371 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004372 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4373 Op->getName()), GEP);
4374 GEP.setOperand(i, Op);
4375 MadeChange = true;
4376 }
Chris Lattner44d0b952004-07-20 01:48:15 +00004377
4378 // If this is a constant idx, make sure to canonicalize it to be a signed
4379 // operand, otherwise CSE and other optimizations are pessimized.
4380 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
4381 GEP.setOperand(i, ConstantExpr::getCast(CUI,
4382 CUI->getType()->getSignedVersion()));
4383 MadeChange = true;
4384 }
Chris Lattner69193f92004-04-05 01:30:19 +00004385 }
4386 if (MadeChange) return &GEP;
4387
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004388 // Combine Indices - If the source pointer to this getelementptr instruction
4389 // is a getelementptr instruction, combine the indices of the two
4390 // getelementptr instructions into a single instruction.
4391 //
Chris Lattner57c67b02004-03-25 22:59:29 +00004392 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00004393 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00004394 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00004395
4396 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004397 // Note that if our source is a gep chain itself that we wait for that
4398 // chain to be resolved before we perform this transformation. This
4399 // avoids us creating a TON of code in some cases.
4400 //
4401 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
4402 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
4403 return 0; // Wait until our source is folded to completion.
4404
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004405 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00004406
4407 // Find out whether the last index in the source GEP is a sequential idx.
4408 bool EndsWithSequential = false;
4409 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
4410 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00004411 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00004412
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004413 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00004414 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00004415 // Replace: gep (gep %P, long B), long A, ...
4416 // With: T = long A+B; gep %P, T, ...
4417 //
Chris Lattner5f667a62004-05-07 22:09:22 +00004418 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00004419 if (SO1 == Constant::getNullValue(SO1->getType())) {
4420 Sum = GO1;
4421 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
4422 Sum = SO1;
4423 } else {
4424 // If they aren't the same type, convert both to an integer of the
4425 // target's pointer size.
4426 if (SO1->getType() != GO1->getType()) {
4427 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
4428 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
4429 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
4430 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
4431 } else {
4432 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00004433 if (SO1->getType()->getPrimitiveSize() == PS) {
4434 // Convert GO1 to SO1's type.
4435 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
4436
4437 } else if (GO1->getType()->getPrimitiveSize() == PS) {
4438 // Convert SO1 to GO1's type.
4439 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
4440 } else {
4441 const Type *PT = TD->getIntPtrType();
4442 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
4443 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
4444 }
4445 }
4446 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004447 if (isa<Constant>(SO1) && isa<Constant>(GO1))
4448 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
4449 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004450 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
4451 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00004452 }
Chris Lattner69193f92004-04-05 01:30:19 +00004453 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004454
4455 // Recycle the GEP we already have if possible.
4456 if (SrcGEPOperands.size() == 2) {
4457 GEP.setOperand(0, SrcGEPOperands[0]);
4458 GEP.setOperand(1, Sum);
4459 return &GEP;
4460 } else {
4461 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4462 SrcGEPOperands.end()-1);
4463 Indices.push_back(Sum);
4464 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
4465 }
Chris Lattner69193f92004-04-05 01:30:19 +00004466 } else if (isa<Constant>(*GEP.idx_begin()) &&
4467 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00004468 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004469 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00004470 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4471 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004472 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
4473 }
4474
4475 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00004476 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004477
Chris Lattner5f667a62004-05-07 22:09:22 +00004478 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004479 // GEP of global variable. If all of the indices for this GEP are
4480 // constants, we can promote this to a constexpr instead of an instruction.
4481
4482 // Scan for nonconstants...
4483 std::vector<Constant*> Indices;
4484 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
4485 for (; I != E && isa<Constant>(*I); ++I)
4486 Indices.push_back(cast<Constant>(*I));
4487
4488 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00004489 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004490
4491 // Replace all uses of the GEP with the new constexpr...
4492 return ReplaceInstUsesWith(GEP, CE);
4493 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004494 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004495 if (CE->getOpcode() == Instruction::Cast) {
4496 if (HasZeroPointerIndex) {
4497 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
4498 // into : GEP [10 x ubyte]* X, long 0, ...
4499 //
4500 // This occurs when the program declares an array extern like "int X[];"
4501 //
4502 Constant *X = CE->getOperand(0);
4503 const PointerType *CPTy = cast<PointerType>(CE->getType());
4504 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
4505 if (const ArrayType *XATy =
4506 dyn_cast<ArrayType>(XTy->getElementType()))
4507 if (const ArrayType *CATy =
4508 dyn_cast<ArrayType>(CPTy->getElementType()))
4509 if (CATy->getElementType() == XATy->getElementType()) {
4510 // At this point, we know that the cast source type is a pointer
4511 // to an array of the same type as the destination pointer
4512 // array. Because the array type is never stepped over (there
4513 // is a leading zero) we can fold the cast into this GEP.
4514 GEP.setOperand(0, X);
4515 return &GEP;
4516 }
Chris Lattner0798af32005-01-13 20:14:25 +00004517 } else if (GEP.getNumOperands() == 2 &&
4518 isa<PointerType>(CE->getOperand(0)->getType())) {
Chris Lattner14f3cdc2004-11-27 17:55:46 +00004519 // Transform things like:
4520 // %t = getelementptr ubyte* cast ([2 x sbyte]* %str to ubyte*), uint %V
4521 // into: %t1 = getelementptr [2 x sbyte*]* %str, int 0, uint %V; cast
4522 Constant *X = CE->getOperand(0);
4523 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4524 const Type *ResElTy =cast<PointerType>(CE->getType())->getElementType();
4525 if (isa<ArrayType>(SrcElTy) &&
4526 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
4527 TD->getTypeSize(ResElTy)) {
4528 Value *V = InsertNewInstBefore(
4529 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
4530 GEP.getOperand(1), GEP.getName()), GEP);
4531 return new CastInst(V, GEP.getType());
4532 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004533 }
4534 }
Chris Lattnerca081252001-12-14 16:52:21 +00004535 }
4536
Chris Lattnerca081252001-12-14 16:52:21 +00004537 return 0;
4538}
4539
Chris Lattner1085bdf2002-11-04 16:18:53 +00004540Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
4541 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
4542 if (AI.isArrayAllocation()) // Check C != 1
4543 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
4544 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004545 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00004546
4547 // Create and insert the replacement instruction...
4548 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00004549 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004550 else {
4551 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00004552 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004553 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004554
4555 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00004556
4557 // Scan to the end of the allocation instructions, to skip over a block of
4558 // allocas if possible...
4559 //
4560 BasicBlock::iterator It = New;
4561 while (isa<AllocationInst>(*It)) ++It;
4562
4563 // Now that I is pointing to the first non-allocation-inst in the block,
4564 // insert our getelementptr instruction...
4565 //
Chris Lattner69193f92004-04-05 01:30:19 +00004566 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00004567 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
4568
4569 // Now make everything use the getelementptr instead of the original
4570 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00004571 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00004572 } else if (isa<UndefValue>(AI.getArraySize())) {
4573 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00004574 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004575
4576 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
4577 // Note that we only do this for alloca's, because malloc should allocate and
4578 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00004579 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
4580 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00004581 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
4582
Chris Lattner1085bdf2002-11-04 16:18:53 +00004583 return 0;
4584}
4585
Chris Lattner8427bff2003-12-07 01:24:23 +00004586Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
4587 Value *Op = FI.getOperand(0);
4588
4589 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
4590 if (CastInst *CI = dyn_cast<CastInst>(Op))
4591 if (isa<PointerType>(CI->getOperand(0)->getType())) {
4592 FI.setOperand(0, CI->getOperand(0));
4593 return &FI;
4594 }
4595
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004596 // free undef -> unreachable.
4597 if (isa<UndefValue>(Op)) {
4598 // Insert a new store to null because we cannot modify the CFG here.
4599 new StoreInst(ConstantBool::True,
4600 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
4601 return EraseInstFromFunction(FI);
4602 }
4603
Chris Lattnerf3a36602004-02-28 04:57:37 +00004604 // If we have 'free null' delete the instruction. This can happen in stl code
4605 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004606 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00004607 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00004608
Chris Lattner8427bff2003-12-07 01:24:23 +00004609 return 0;
4610}
4611
4612
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004613/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
4614/// constantexpr, return the constant value being addressed by the constant
4615/// expression, or null if something is funny.
4616///
4617static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00004618 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004619 return 0; // Do not allow stepping over the value!
4620
4621 // Loop over all of the operands, tracking down which value we are
4622 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00004623 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
4624 for (++I; I != E; ++I)
4625 if (const StructType *STy = dyn_cast<StructType>(*I)) {
4626 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
4627 assert(CU->getValue() < STy->getNumElements() &&
4628 "Struct index out of range!");
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004629 unsigned El = (unsigned)CU->getValue();
Chris Lattnered79d8a2004-05-27 17:30:27 +00004630 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004631 C = CS->getOperand(El);
Chris Lattnered79d8a2004-05-27 17:30:27 +00004632 } else if (isa<ConstantAggregateZero>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004633 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattner81a7a232004-10-16 18:11:37 +00004634 } else if (isa<UndefValue>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004635 C = UndefValue::get(STy->getElementType(El));
Chris Lattnered79d8a2004-05-27 17:30:27 +00004636 } else {
4637 return 0;
4638 }
4639 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
4640 const ArrayType *ATy = cast<ArrayType>(*I);
4641 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
4642 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004643 C = CA->getOperand((unsigned)CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004644 else if (isa<ConstantAggregateZero>(C))
4645 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00004646 else if (isa<UndefValue>(C))
4647 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004648 else
4649 return 0;
4650 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004651 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00004652 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004653 return C;
4654}
4655
Chris Lattner72684fe2005-01-31 05:51:45 +00004656/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00004657static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
4658 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004659 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00004660
4661 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004662 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00004663 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004664
4665 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
4666 // If the source is an array, the code below will not succeed. Check to
4667 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
4668 // constants.
4669 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
4670 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
4671 if (ASrcTy->getNumElements() != 0) {
4672 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
4673 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
4674 SrcTy = cast<PointerType>(CastOp->getType());
4675 SrcPTy = SrcTy->getElementType();
4676 }
4677
4678 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00004679 // Do not allow turning this into a load of an integer, which is then
4680 // casted to a pointer, this pessimizes pointer analysis a lot.
4681 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004682 IC.getTargetData().getTypeSize(SrcPTy) ==
4683 IC.getTargetData().getTypeSize(DestPTy)) {
4684
4685 // Okay, we are casting from one integer or pointer type to another of
4686 // the same size. Instead of casting the pointer before the load, cast
4687 // the result of the loaded value.
4688 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
4689 CI->getName(),
4690 LI.isVolatile()),LI);
4691 // Now cast the result of the load.
4692 return new CastInst(NewLoad, LI.getType());
4693 }
Chris Lattner35e24772004-07-13 01:49:43 +00004694 }
4695 }
4696 return 0;
4697}
4698
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004699/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00004700/// from this value cannot trap. If it is not obviously safe to load from the
4701/// specified pointer, we do a quick local scan of the basic block containing
4702/// ScanFrom, to determine if the address is already accessed.
4703static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
4704 // If it is an alloca or global variable, it is always safe to load from.
4705 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
4706
4707 // Otherwise, be a little bit agressive by scanning the local block where we
4708 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004709 // from/to. If so, the previous load or store would have already trapped,
4710 // so there is no harm doing an extra load (also, CSE will later eliminate
4711 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00004712 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
4713
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004714 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00004715 --BBI;
4716
4717 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
4718 if (LI->getOperand(0) == V) return true;
4719 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
4720 if (SI->getOperand(1) == V) return true;
4721
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004722 }
Chris Lattnere6f13092004-09-19 19:18:10 +00004723 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004724}
4725
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004726Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
4727 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00004728
Chris Lattner81a7a232004-10-16 18:11:37 +00004729 if (Constant *C = dyn_cast<Constant>(Op)) {
4730 if ((C->isNullValue() || isa<UndefValue>(C)) &&
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004731 !LI.isVolatile()) { // load null/undef -> undef
4732 // Insert a new store to null instruction before the load to indicate that
4733 // this code is not reachable. We do this instead of inserting an
4734 // unreachable instruction directly because we cannot modify the CFG.
4735 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00004736 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004737 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004738
Chris Lattner81a7a232004-10-16 18:11:37 +00004739 // Instcombine load (constant global) into the value loaded.
4740 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
4741 if (GV->isConstant() && !GV->isExternal())
4742 return ReplaceInstUsesWith(LI, GV->getInitializer());
4743
4744 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
4745 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
4746 if (CE->getOpcode() == Instruction::GetElementPtr) {
4747 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
4748 if (GV->isConstant() && !GV->isExternal())
4749 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
4750 return ReplaceInstUsesWith(LI, V);
4751 } else if (CE->getOpcode() == Instruction::Cast) {
4752 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4753 return Res;
4754 }
4755 }
Chris Lattnere228ee52004-04-08 20:39:49 +00004756
4757 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00004758 if (CastInst *CI = dyn_cast<CastInst>(Op))
4759 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4760 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00004761
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004762 if (!LI.isVolatile() && Op->hasOneUse()) {
4763 // Change select and PHI nodes to select values instead of addresses: this
4764 // helps alias analysis out a lot, allows many others simplifications, and
4765 // exposes redundancy in the code.
4766 //
4767 // Note that we cannot do the transformation unless we know that the
4768 // introduced loads cannot trap! Something like this is valid as long as
4769 // the condition is always false: load (select bool %C, int* null, int* %G),
4770 // but it would not be valid if we transformed it to load from null
4771 // unconditionally.
4772 //
4773 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
4774 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00004775 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
4776 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004777 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00004778 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004779 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00004780 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004781 return new SelectInst(SI->getCondition(), V1, V2);
4782 }
4783
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00004784 // load (select (cond, null, P)) -> load P
4785 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
4786 if (C->isNullValue()) {
4787 LI.setOperand(0, SI->getOperand(2));
4788 return &LI;
4789 }
4790
4791 // load (select (cond, P, null)) -> load P
4792 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
4793 if (C->isNullValue()) {
4794 LI.setOperand(0, SI->getOperand(1));
4795 return &LI;
4796 }
4797
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004798 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
4799 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00004800 bool Safe = PN->getParent() == LI.getParent();
4801
4802 // Scan all of the instructions between the PHI and the load to make
4803 // sure there are no instructions that might possibly alter the value
4804 // loaded from the PHI.
4805 if (Safe) {
4806 BasicBlock::iterator I = &LI;
4807 for (--I; !isa<PHINode>(I); --I)
4808 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
4809 Safe = false;
4810 break;
4811 }
4812 }
4813
4814 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00004815 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00004816 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004817 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00004818
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004819 if (Safe) {
4820 // Create the PHI.
4821 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
4822 InsertNewInstBefore(NewPN, *PN);
4823 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
4824
4825 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4826 BasicBlock *BB = PN->getIncomingBlock(i);
4827 Value *&TheLoad = LoadMap[BB];
4828 if (TheLoad == 0) {
4829 Value *InVal = PN->getIncomingValue(i);
4830 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
4831 InVal->getName()+".val"),
4832 *BB->getTerminator());
4833 }
4834 NewPN->addIncoming(TheLoad, BB);
4835 }
4836 return ReplaceInstUsesWith(LI, NewPN);
4837 }
4838 }
4839 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004840 return 0;
4841}
4842
Chris Lattner72684fe2005-01-31 05:51:45 +00004843/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
4844/// when possible.
4845static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
4846 User *CI = cast<User>(SI.getOperand(1));
4847 Value *CastOp = CI->getOperand(0);
4848
4849 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
4850 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
4851 const Type *SrcPTy = SrcTy->getElementType();
4852
4853 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
4854 // If the source is an array, the code below will not succeed. Check to
4855 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
4856 // constants.
4857 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
4858 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
4859 if (ASrcTy->getNumElements() != 0) {
4860 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
4861 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
4862 SrcTy = cast<PointerType>(CastOp->getType());
4863 SrcPTy = SrcTy->getElementType();
4864 }
4865
4866 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
4867 IC.getTargetData().getTypeSize(SrcPTy) ==
4868 IC.getTargetData().getTypeSize(DestPTy)) {
4869
4870 // Okay, we are casting from one integer or pointer type to another of
4871 // the same size. Instead of casting the pointer before the store, cast
4872 // the value to be stored.
4873 Value *NewCast;
4874 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
4875 NewCast = ConstantExpr::getCast(C, SrcPTy);
4876 else
4877 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
4878 SrcPTy,
4879 SI.getOperand(0)->getName()+".c"), SI);
4880
4881 return new StoreInst(NewCast, CastOp);
4882 }
4883 }
4884 }
4885 return 0;
4886}
4887
Chris Lattner31f486c2005-01-31 05:36:43 +00004888Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
4889 Value *Val = SI.getOperand(0);
4890 Value *Ptr = SI.getOperand(1);
4891
4892 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
4893 removeFromWorkList(&SI);
4894 SI.eraseFromParent();
4895 ++NumCombined;
4896 return 0;
4897 }
4898
4899 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
4900
4901 // store X, null -> turns into 'unreachable' in SimplifyCFG
4902 if (isa<ConstantPointerNull>(Ptr)) {
4903 if (!isa<UndefValue>(Val)) {
4904 SI.setOperand(0, UndefValue::get(Val->getType()));
4905 if (Instruction *U = dyn_cast<Instruction>(Val))
4906 WorkList.push_back(U); // Dropped a use.
4907 ++NumCombined;
4908 }
4909 return 0; // Do not modify these!
4910 }
4911
4912 // store undef, Ptr -> noop
4913 if (isa<UndefValue>(Val)) {
4914 removeFromWorkList(&SI);
4915 SI.eraseFromParent();
4916 ++NumCombined;
4917 return 0;
4918 }
4919
Chris Lattner72684fe2005-01-31 05:51:45 +00004920 // If the pointer destination is a cast, see if we can fold the cast into the
4921 // source instead.
4922 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
4923 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
4924 return Res;
4925 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
4926 if (CE->getOpcode() == Instruction::Cast)
4927 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
4928 return Res;
4929
Chris Lattner31f486c2005-01-31 05:36:43 +00004930 return 0;
4931}
4932
4933
Chris Lattner9eef8a72003-06-04 04:46:00 +00004934Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
4935 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00004936 Value *X;
4937 BasicBlock *TrueDest;
4938 BasicBlock *FalseDest;
4939 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
4940 !isa<Constant>(X)) {
4941 // Swap Destinations and condition...
4942 BI.setCondition(X);
4943 BI.setSuccessor(0, FalseDest);
4944 BI.setSuccessor(1, TrueDest);
4945 return &BI;
4946 }
4947
4948 // Cannonicalize setne -> seteq
4949 Instruction::BinaryOps Op; Value *Y;
4950 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
4951 TrueDest, FalseDest)))
4952 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
4953 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
4954 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
4955 std::string Name = I->getName(); I->setName("");
4956 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
4957 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00004958 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00004959 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00004960 BI.setSuccessor(0, FalseDest);
4961 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004962 removeFromWorkList(I);
4963 I->getParent()->getInstList().erase(I);
4964 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00004965 return &BI;
4966 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00004967
Chris Lattner9eef8a72003-06-04 04:46:00 +00004968 return 0;
4969}
Chris Lattner1085bdf2002-11-04 16:18:53 +00004970
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004971Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4972 Value *Cond = SI.getCondition();
4973 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4974 if (I->getOpcode() == Instruction::Add)
4975 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4976 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4977 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00004978 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004979 AddRHS));
4980 SI.setOperand(0, I->getOperand(0));
4981 WorkList.push_back(I);
4982 return &SI;
4983 }
4984 }
4985 return 0;
4986}
4987
Chris Lattnerca081252001-12-14 16:52:21 +00004988
Chris Lattner99f48c62002-09-02 04:59:56 +00004989void InstCombiner::removeFromWorkList(Instruction *I) {
4990 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4991 WorkList.end());
4992}
4993
Chris Lattner39c98bb2004-12-08 23:43:58 +00004994
4995/// TryToSinkInstruction - Try to move the specified instruction from its
4996/// current block into the beginning of DestBlock, which can only happen if it's
4997/// safe to move the instruction past all of the instructions between it and the
4998/// end of its block.
4999static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5000 assert(I->hasOneUse() && "Invariants didn't hold!");
5001
5002 // Cannot move control-flow-involving instructions.
5003 if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
5004
5005 // Do not sink alloca instructions out of the entry block.
5006 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5007 return false;
5008
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005009 // We can only sink load instructions if there is nothing between the load and
5010 // the end of block that could change the value.
5011 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5012 if (LI->isVolatile()) return false; // Don't sink volatile loads.
5013
5014 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5015 Scan != E; ++Scan)
5016 if (Scan->mayWriteToMemory())
5017 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005018 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00005019
5020 BasicBlock::iterator InsertPos = DestBlock->begin();
5021 while (isa<PHINode>(InsertPos)) ++InsertPos;
5022
5023 BasicBlock *SrcBlock = I->getParent();
5024 DestBlock->getInstList().splice(InsertPos, SrcBlock->getInstList(), I);
5025 ++NumSunkInst;
5026 return true;
5027}
5028
Chris Lattner113f4f42002-06-25 16:13:24 +00005029bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00005030 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005031 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00005032
Chris Lattnerb643a9e2004-05-01 23:19:52 +00005033 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
5034 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00005035
Chris Lattnerca081252001-12-14 16:52:21 +00005036
5037 while (!WorkList.empty()) {
5038 Instruction *I = WorkList.back(); // Get an instruction from the worklist
5039 WorkList.pop_back();
5040
Misha Brukman632df282002-10-29 23:06:16 +00005041 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00005042 // Check to see if we can DIE the instruction...
5043 if (isInstructionTriviallyDead(I)) {
5044 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005045 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00005046 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00005047 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005048
Chris Lattnercd517ff2005-01-28 19:32:01 +00005049 DEBUG(std::cerr << "IC: DCE: " << *I);
5050
5051 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005052 removeFromWorkList(I);
5053 continue;
5054 }
Chris Lattner99f48c62002-09-02 04:59:56 +00005055
Misha Brukman632df282002-10-29 23:06:16 +00005056 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00005057 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005058 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00005059 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005060 cast<Constant>(Ptr)->isNullValue() &&
5061 !isa<ConstantPointerNull>(C) &&
5062 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00005063 // If this is a constant expr gep that is effectively computing an
5064 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5065 bool isFoldableGEP = true;
5066 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5067 if (!isa<ConstantInt>(I->getOperand(i)))
5068 isFoldableGEP = false;
5069 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005070 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00005071 std::vector<Value*>(I->op_begin()+1, I->op_end()));
5072 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00005073 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00005074 C = ConstantExpr::getCast(C, I->getType());
5075 }
5076 }
5077
Chris Lattnercd517ff2005-01-28 19:32:01 +00005078 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5079
Chris Lattner99f48c62002-09-02 04:59:56 +00005080 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00005081 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00005082 ReplaceInstUsesWith(*I, C);
5083
Chris Lattner99f48c62002-09-02 04:59:56 +00005084 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005085 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00005086 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005087 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00005088 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005089
Chris Lattner39c98bb2004-12-08 23:43:58 +00005090 // See if we can trivially sink this instruction to a successor basic block.
5091 if (I->hasOneUse()) {
5092 BasicBlock *BB = I->getParent();
5093 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5094 if (UserParent != BB) {
5095 bool UserIsSuccessor = false;
5096 // See if the user is one of our successors.
5097 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5098 if (*SI == UserParent) {
5099 UserIsSuccessor = true;
5100 break;
5101 }
5102
5103 // If the user is one of our immediate successors, and if that successor
5104 // only has us as a predecessors (we'd have to split the critical edge
5105 // otherwise), we can keep going.
5106 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5107 next(pred_begin(UserParent)) == pred_end(UserParent))
5108 // Okay, the CFG is simple enough, try to sink this instruction.
5109 Changed |= TryToSinkInstruction(I, UserParent);
5110 }
5111 }
5112
Chris Lattnerca081252001-12-14 16:52:21 +00005113 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005114 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00005115 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00005116 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00005117 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005118 DEBUG(std::cerr << "IC: Old = " << *I
5119 << " New = " << *Result);
5120
Chris Lattner396dbfe2004-06-09 05:08:07 +00005121 // Everything uses the new instruction now.
5122 I->replaceAllUsesWith(Result);
5123
5124 // Push the new instruction and any users onto the worklist.
5125 WorkList.push_back(Result);
5126 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005127
5128 // Move the name to the new instruction first...
5129 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00005130 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005131
5132 // Insert the new instruction into the basic block...
5133 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00005134 BasicBlock::iterator InsertPos = I;
5135
5136 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5137 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5138 ++InsertPos;
5139
5140 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005141
Chris Lattner63d75af2004-05-01 23:27:23 +00005142 // Make sure that we reprocess all operands now that we reduced their
5143 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00005144 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5145 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5146 WorkList.push_back(OpI);
5147
Chris Lattner396dbfe2004-06-09 05:08:07 +00005148 // Instructions can end up on the worklist more than once. Make sure
5149 // we do not process an instruction that has been deleted.
5150 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005151
5152 // Erase the old instruction.
5153 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00005154 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005155 DEBUG(std::cerr << "IC: MOD = " << *I);
5156
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005157 // If the instruction was modified, it's possible that it is now dead.
5158 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00005159 if (isInstructionTriviallyDead(I)) {
5160 // Make sure we process all operands now that we are reducing their
5161 // use counts.
5162 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5163 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5164 WorkList.push_back(OpI);
5165
5166 // Instructions may end up in the worklist more than once. Erase all
5167 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00005168 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00005169 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00005170 } else {
5171 WorkList.push_back(Result);
5172 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005173 }
Chris Lattner053c0932002-05-14 15:24:07 +00005174 }
Chris Lattner260ab202002-04-18 17:39:14 +00005175 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00005176 }
5177 }
5178
Chris Lattner260ab202002-04-18 17:39:14 +00005179 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00005180}
5181
Brian Gaeke38b79e82004-07-27 17:43:21 +00005182FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00005183 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00005184}
Brian Gaeke960707c2003-11-11 22:41:34 +00005185