blob: c1eb3ebe45f49e54a3c66f8542bc7e18aac65294 [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;
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000632 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000633
Chris Lattner147e9752002-05-08 22:46:53 +0000634 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000635 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000636 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000637
638 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000639 if (!isa<Constant>(RHS))
640 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000641 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000642
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000643 ConstantInt *C2;
644 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
645 if (X == RHS) // X*C + X --> X * (C+1)
646 return BinaryOperator::createMul(RHS, AddOne(C2));
647
648 // X*C1 + X*C2 --> X * (C1+C2)
649 ConstantInt *C1;
650 if (X == dyn_castFoldableMul(RHS, C1))
651 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000652 }
653
654 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000655 if (dyn_castFoldableMul(RHS, C2) == LHS)
656 return BinaryOperator::createMul(LHS, AddOne(C2));
657
Chris Lattner57c8d992003-02-18 19:57:07 +0000658
Chris Lattnerb8b97502003-08-13 19:01:45 +0000659 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000660 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000661 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000662
Chris Lattnerb9cde762003-10-02 15:11:26 +0000663 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000664 Value *X;
665 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
666 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
667 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000668 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000669
Chris Lattnerbff91d92004-10-08 05:07:56 +0000670 // (X & FF00) + xx00 -> (X+xx00) & FF00
671 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
672 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
673 if (Anded == CRHS) {
674 // See if all bits from the first bit set in the Add RHS up are included
675 // in the mask. First, get the rightmost bit.
676 uint64_t AddRHSV = CRHS->getRawValue();
677
678 // Form a mask of all bits from the lowest bit added through the top.
679 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
680 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
681
682 // See if the and mask includes all of these bits.
683 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
684
685 if (AddRHSHighBits == AddRHSHighBitsAnd) {
686 // Okay, the xform is safe. Insert the new add pronto.
687 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
688 LHS->getName()), I);
689 return BinaryOperator::createAnd(NewAdd, C2);
690 }
691 }
692 }
693
Chris Lattnerd4252a72004-07-30 07:50:03 +0000694 // Try to fold constant add into select arguments.
695 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +0000696 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +0000697 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000698 }
699
Chris Lattner113f4f42002-06-25 16:13:24 +0000700 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000701}
702
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000703// isSignBit - Return true if the value represented by the constant only has the
704// highest order bit set.
705static bool isSignBit(ConstantInt *CI) {
706 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
707 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
708}
709
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000710static unsigned getTypeSizeInBits(const Type *Ty) {
711 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
712}
713
Chris Lattner022167f2004-03-13 00:11:49 +0000714/// RemoveNoopCast - Strip off nonconverting casts from the value.
715///
716static Value *RemoveNoopCast(Value *V) {
717 if (CastInst *CI = dyn_cast<CastInst>(V)) {
718 const Type *CTy = CI->getType();
719 const Type *OpTy = CI->getOperand(0)->getType();
720 if (CTy->isInteger() && OpTy->isInteger()) {
721 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
722 return RemoveNoopCast(CI->getOperand(0));
723 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
724 return RemoveNoopCast(CI->getOperand(0));
725 }
726 return V;
727}
728
Chris Lattner113f4f42002-06-25 16:13:24 +0000729Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000730 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000731
Chris Lattnere6794492002-08-12 21:17:25 +0000732 if (Op0 == Op1) // sub X, X -> 0
733 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000734
Chris Lattnere6794492002-08-12 21:17:25 +0000735 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000736 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000737 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000738
Chris Lattner81a7a232004-10-16 18:11:37 +0000739 if (isa<UndefValue>(Op0))
740 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
741 if (isa<UndefValue>(Op1))
742 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
743
Chris Lattner8f2f5982003-11-05 01:06:05 +0000744 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
745 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000746 if (C->isAllOnesValue())
747 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000748
Chris Lattner8f2f5982003-11-05 01:06:05 +0000749 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000750 Value *X;
751 if (match(Op1, m_Not(m_Value(X))))
752 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000753 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000754 // -((uint)X >> 31) -> ((int)X >> 31)
755 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000756 if (C->isNullValue()) {
757 Value *NoopCastedRHS = RemoveNoopCast(Op1);
758 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000759 if (SI->getOpcode() == Instruction::Shr)
760 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
761 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000762 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000763 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000764 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000765 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000766 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000767 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000768 // Ok, the transformation is safe. Insert a cast of the incoming
769 // value, then the new shift, then the new cast.
770 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
771 SI->getOperand(0)->getName());
772 Value *InV = InsertNewInstBefore(FirstCast, I);
773 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
774 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000775 if (NewShift->getType() == I.getType())
776 return NewShift;
777 else {
778 InV = InsertNewInstBefore(NewShift, I);
779 return new CastInst(NewShift, I.getType());
780 }
Chris Lattner92295c52004-03-12 23:53:13 +0000781 }
782 }
Chris Lattner022167f2004-03-13 00:11:49 +0000783 }
Chris Lattner183b3362004-04-09 19:05:30 +0000784
785 // Try to fold constant sub into select arguments.
786 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +0000787 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000788 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000789
790 if (isa<PHINode>(Op0))
791 if (Instruction *NV = FoldOpIntoPhi(I))
792 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000793 }
794
Chris Lattnera9be4492005-04-07 16:15:25 +0000795 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
796 if (Op1I->getOpcode() == Instruction::Add &&
797 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000798 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000799 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000800 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000801 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000802 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
803 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
804 // C1-(X+C2) --> (C1-C2)-X
805 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
806 Op1I->getOperand(0));
807 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000808 }
809
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000810 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000811 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
812 // is not used by anyone else...
813 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000814 if (Op1I->getOpcode() == Instruction::Sub &&
815 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000816 // Swap the two operands of the subexpr...
817 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
818 Op1I->setOperand(0, IIOp1);
819 Op1I->setOperand(1, IIOp0);
820
821 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000822 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000823 }
824
825 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
826 //
827 if (Op1I->getOpcode() == Instruction::And &&
828 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
829 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
830
Chris Lattner396dbfe2004-06-09 05:08:07 +0000831 Value *NewNot =
832 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000833 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000834 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000835
Chris Lattner0aee4b72004-10-06 15:08:25 +0000836 // -(X sdiv C) -> (X sdiv -C)
837 if (Op1I->getOpcode() == Instruction::Div)
838 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +0000839 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +0000840 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
841 return BinaryOperator::createDiv(Op1I->getOperand(0),
842 ConstantExpr::getNeg(DivRHS));
843
Chris Lattner57c8d992003-02-18 19:57:07 +0000844 // X - X*C --> X * (1-C)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000845 ConstantInt *C2;
846 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
847 Constant *CP1 =
848 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000849 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000850 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000851 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000852 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000853
Chris Lattner411336f2005-01-19 21:50:18 +0000854 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
855 if (Op0I->getOpcode() == Instruction::Add)
856 if (!Op0->getType()->isFloatingPoint()) {
857 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
858 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
859 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
860 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
861 }
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000862
863 ConstantInt *C1;
864 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
865 if (X == Op1) { // X*C - X --> X * (C-1)
866 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
867 return BinaryOperator::createMul(Op1, CP1);
868 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000869
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000870 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
871 if (X == dyn_castFoldableMul(Op1, C2))
872 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
873 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000874 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000875}
876
Chris Lattnere79e8542004-02-23 06:38:22 +0000877/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
878/// really just returns true if the most significant (sign) bit is set.
879static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
880 if (RHS->getType()->isSigned()) {
881 // True if source is LHS < 0 or LHS <= -1
882 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
883 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
884 } else {
885 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
886 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
887 // the size of the integer type.
888 if (Opcode == Instruction::SetGE)
889 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
890 if (Opcode == Instruction::SetGT)
891 return RHSC->getValue() ==
892 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
893 }
894 return false;
895}
896
Chris Lattner113f4f42002-06-25 16:13:24 +0000897Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000898 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000899 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000900
Chris Lattner81a7a232004-10-16 18:11:37 +0000901 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
902 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
903
Chris Lattnere6794492002-08-12 21:17:25 +0000904 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000905 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
906 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000907
908 // ((X << C1)*C2) == (X * (C2 << C1))
909 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
910 if (SI->getOpcode() == Instruction::Shl)
911 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000912 return BinaryOperator::createMul(SI->getOperand(0),
913 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000914
Chris Lattnercce81be2003-09-11 22:24:54 +0000915 if (CI->isNullValue())
916 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
917 if (CI->equalsInt(1)) // X * 1 == X
918 return ReplaceInstUsesWith(I, Op0);
919 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000920 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000921
Chris Lattnercce81be2003-09-11 22:24:54 +0000922 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000923 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
924 return new ShiftInst(Instruction::Shl, Op0,
925 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000926 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000927 if (Op1F->isNullValue())
928 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000929
Chris Lattner3082c5a2003-02-18 19:28:33 +0000930 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
931 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
932 if (Op1F->getValue() == 1.0)
933 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
934 }
Chris Lattner183b3362004-04-09 19:05:30 +0000935
936 // Try to fold constant mul into select arguments.
937 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +0000938 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000939 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000940
941 if (isa<PHINode>(Op0))
942 if (Instruction *NV = FoldOpIntoPhi(I))
943 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000944 }
945
Chris Lattner934a64cf2003-03-10 23:23:04 +0000946 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
947 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000948 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000949
Chris Lattner2635b522004-02-23 05:39:21 +0000950 // If one of the operands of the multiply is a cast from a boolean value, then
951 // we know the bool is either zero or one, so this is a 'masking' multiply.
952 // See if we can simplify things based on how the boolean was originally
953 // formed.
954 CastInst *BoolCast = 0;
955 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
956 if (CI->getOperand(0)->getType() == Type::BoolTy)
957 BoolCast = CI;
958 if (!BoolCast)
959 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
960 if (CI->getOperand(0)->getType() == Type::BoolTy)
961 BoolCast = CI;
962 if (BoolCast) {
963 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
964 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
965 const Type *SCOpTy = SCIOp0->getType();
966
Chris Lattnere79e8542004-02-23 06:38:22 +0000967 // If the setcc is true iff the sign bit of X is set, then convert this
968 // multiply into a shift/and combination.
969 if (isa<ConstantInt>(SCIOp1) &&
970 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000971 // Shift the X value right to turn it into "all signbits".
972 Constant *Amt = ConstantUInt::get(Type::UByteTy,
973 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000974 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000975 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000976 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
977 SCIOp0->getName()), I);
978 }
979
980 Value *V =
981 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
982 BoolCast->getOperand(0)->getName()+
983 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000984
985 // If the multiply type is not the same as the source type, sign extend
986 // or truncate to the multiply type.
987 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000988 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000989
990 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000991 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000992 }
993 }
994 }
995
Chris Lattner113f4f42002-06-25 16:13:24 +0000996 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000997}
998
Chris Lattner113f4f42002-06-25 16:13:24 +0000999Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001000 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001001
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001002 if (isa<UndefValue>(Op0)) // undef / X -> 0
1003 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1004 if (isa<UndefValue>(Op1))
1005 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1006
1007 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001008 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001009 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001010 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001011
Chris Lattnere20c3342004-04-26 14:01:59 +00001012 // div X, -1 == -X
1013 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001014 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001015
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001016 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001017 if (LHS->getOpcode() == Instruction::Div)
1018 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001019 // (X / C1) / C2 -> X / (C1*C2)
1020 return BinaryOperator::createDiv(LHS->getOperand(0),
1021 ConstantExpr::getMul(RHS, LHSRHS));
1022 }
1023
Chris Lattner3082c5a2003-02-18 19:28:33 +00001024 // Check to see if this is an unsigned division with an exact power of 2,
1025 // if so, convert to a right shift.
1026 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1027 if (uint64_t Val = C->getValue()) // Don't break X / 0
1028 if (uint64_t C = Log2(Val))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001029 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001030 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001031
Chris Lattner4ad08352004-10-09 02:50:40 +00001032 // -X/C -> X/-C
1033 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001034 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001035 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1036
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001037 if (!RHS->isNullValue()) {
1038 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001039 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001040 return R;
1041 if (isa<PHINode>(Op0))
1042 if (Instruction *NV = FoldOpIntoPhi(I))
1043 return NV;
1044 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001045 }
1046
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001047 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1048 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1049 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1050 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1051 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1052 if (STO->getValue() == 0) { // Couldn't be this argument.
1053 I.setOperand(1, SFO);
1054 return &I;
1055 } else if (SFO->getValue() == 0) {
1056 I.setOperand(1, STO);
1057 return &I;
1058 }
1059
1060 if (uint64_t TSA = Log2(STO->getValue()))
1061 if (uint64_t FSA = Log2(SFO->getValue())) {
1062 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1063 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1064 TC, SI->getName()+".t");
1065 TSI = InsertNewInstBefore(TSI, I);
1066
1067 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1068 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1069 FC, SI->getName()+".f");
1070 FSI = InsertNewInstBefore(FSI, I);
1071 return new SelectInst(SI->getOperand(0), TSI, FSI);
1072 }
1073 }
1074
Chris Lattner3082c5a2003-02-18 19:28:33 +00001075 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001076 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001077 if (LHS->equalsInt(0))
1078 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1079
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001080 return 0;
1081}
1082
1083
Chris Lattner113f4f42002-06-25 16:13:24 +00001084Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001085 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner7fd5f072004-07-06 07:01:22 +00001086 if (I.getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001087 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001088 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001089 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001090 // X % -Y -> X % Y
1091 AddUsesToWorkList(I);
1092 I.setOperand(1, RHSNeg);
1093 return &I;
1094 }
1095
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001096 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001097 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001098 if (isa<UndefValue>(Op1))
1099 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001100
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001101 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001102 if (RHS->equalsInt(1)) // X % 1 == 0
1103 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1104
1105 // Check to see if this is an unsigned remainder with an exact power of 2,
1106 // if so, convert to a bitwise and.
1107 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1108 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001109 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001110 return BinaryOperator::createAnd(Op0,
1111 ConstantUInt::get(I.getType(), Val-1));
1112
1113 if (!RHS->isNullValue()) {
1114 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001115 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001116 return R;
1117 if (isa<PHINode>(Op0))
1118 if (Instruction *NV = FoldOpIntoPhi(I))
1119 return NV;
1120 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001121 }
1122
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001123 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1124 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1125 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1126 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1127 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1128 if (STO->getValue() == 0) { // Couldn't be this argument.
1129 I.setOperand(1, SFO);
1130 return &I;
1131 } else if (SFO->getValue() == 0) {
1132 I.setOperand(1, STO);
1133 return &I;
1134 }
1135
1136 if (!(STO->getValue() & (STO->getValue()-1)) &&
1137 !(SFO->getValue() & (SFO->getValue()-1))) {
1138 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1139 SubOne(STO), SI->getName()+".t"), I);
1140 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1141 SubOne(SFO), SI->getName()+".f"), I);
1142 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1143 }
1144 }
1145
Chris Lattner3082c5a2003-02-18 19:28:33 +00001146 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001147 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001148 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001149 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1150
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001151 return 0;
1152}
1153
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001154// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001155static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001156 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1157 // Calculate -1 casted to the right type...
1158 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1159 uint64_t Val = ~0ULL; // All ones
1160 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1161 return CU->getValue() == Val-1;
1162 }
1163
1164 const ConstantSInt *CS = cast<ConstantSInt>(C);
1165
1166 // Calculate 0111111111..11111
1167 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1168 int64_t Val = INT64_MAX; // All ones
1169 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1170 return CS->getValue() == Val-1;
1171}
1172
1173// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001174static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001175 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1176 return CU->getValue() == 1;
1177
1178 const ConstantSInt *CS = cast<ConstantSInt>(C);
1179
1180 // Calculate 1111111111000000000000
1181 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1182 int64_t Val = -1; // All ones
1183 Val <<= TypeBits-1; // Shift over to the right spot
1184 return CS->getValue() == Val+1;
1185}
1186
Chris Lattner35167c32004-06-09 07:59:58 +00001187// isOneBitSet - Return true if there is exactly one bit set in the specified
1188// constant.
1189static bool isOneBitSet(const ConstantInt *CI) {
1190 uint64_t V = CI->getRawValue();
1191 return V && (V & (V-1)) == 0;
1192}
1193
Chris Lattner8fc5af42004-09-23 21:46:38 +00001194#if 0 // Currently unused
1195// isLowOnes - Return true if the constant is of the form 0+1+.
1196static bool isLowOnes(const ConstantInt *CI) {
1197 uint64_t V = CI->getRawValue();
1198
1199 // There won't be bits set in parts that the type doesn't contain.
1200 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1201
1202 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1203 return U && V && (U & V) == 0;
1204}
1205#endif
1206
1207// isHighOnes - Return true if the constant is of the form 1+0+.
1208// This is the same as lowones(~X).
1209static bool isHighOnes(const ConstantInt *CI) {
1210 uint64_t V = ~CI->getRawValue();
1211
1212 // There won't be bits set in parts that the type doesn't contain.
1213 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1214
1215 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1216 return U && V && (U & V) == 0;
1217}
1218
1219
Chris Lattner3ac7c262003-08-13 20:16:26 +00001220/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1221/// are carefully arranged to allow folding of expressions such as:
1222///
1223/// (A < B) | (A > B) --> (A != B)
1224///
1225/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1226/// represents that the comparison is true if A == B, and bit value '1' is true
1227/// if A < B.
1228///
1229static unsigned getSetCondCode(const SetCondInst *SCI) {
1230 switch (SCI->getOpcode()) {
1231 // False -> 0
1232 case Instruction::SetGT: return 1;
1233 case Instruction::SetEQ: return 2;
1234 case Instruction::SetGE: return 3;
1235 case Instruction::SetLT: return 4;
1236 case Instruction::SetNE: return 5;
1237 case Instruction::SetLE: return 6;
1238 // True -> 7
1239 default:
1240 assert(0 && "Invalid SetCC opcode!");
1241 return 0;
1242 }
1243}
1244
1245/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1246/// opcode and two operands into either a constant true or false, or a brand new
1247/// SetCC instruction.
1248static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1249 switch (Opcode) {
1250 case 0: return ConstantBool::False;
1251 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1252 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1253 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1254 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1255 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1256 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1257 case 7: return ConstantBool::True;
1258 default: assert(0 && "Illegal SetCCCode!"); return 0;
1259 }
1260}
1261
1262// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1263struct FoldSetCCLogical {
1264 InstCombiner &IC;
1265 Value *LHS, *RHS;
1266 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1267 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1268 bool shouldApply(Value *V) const {
1269 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1270 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1271 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1272 return false;
1273 }
1274 Instruction *apply(BinaryOperator &Log) const {
1275 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1276 if (SCI->getOperand(0) != LHS) {
1277 assert(SCI->getOperand(1) == LHS);
1278 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1279 }
1280
1281 unsigned LHSCode = getSetCondCode(SCI);
1282 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1283 unsigned Code;
1284 switch (Log.getOpcode()) {
1285 case Instruction::And: Code = LHSCode & RHSCode; break;
1286 case Instruction::Or: Code = LHSCode | RHSCode; break;
1287 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001288 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001289 }
1290
1291 Value *RV = getSetCCValue(Code, LHS, RHS);
1292 if (Instruction *I = dyn_cast<Instruction>(RV))
1293 return I;
1294 // Otherwise, it's a constant boolean value...
1295 return IC.ReplaceInstUsesWith(Log, RV);
1296 }
1297};
1298
1299
Chris Lattner86102b82005-01-01 16:22:27 +00001300/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1301/// this predicate to simplify operations downstream. V and Mask are known to
1302/// be the same type.
1303static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
1304 if (isa<UndefValue>(V) || Mask->isNullValue())
1305 return true;
1306 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
1307 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
1308
1309 if (Instruction *I = dyn_cast<Instruction>(V)) {
1310 switch (I->getOpcode()) {
1311 case Instruction::And:
1312 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
1313 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
1314 if (ConstantExpr::getAnd(CI, Mask)->isNullValue())
1315 return true;
1316 break;
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001317 case Instruction::Or:
1318 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
1319 return MaskedValueIsZero(I->getOperand(1), Mask) &&
1320 MaskedValueIsZero(I->getOperand(0), Mask);
1321 case Instruction::Select:
1322 // If the T and F values are MaskedValueIsZero, the result is also zero.
1323 return MaskedValueIsZero(I->getOperand(2), Mask) &&
1324 MaskedValueIsZero(I->getOperand(1), Mask);
Chris Lattner86102b82005-01-01 16:22:27 +00001325 case Instruction::Cast: {
1326 const Type *SrcTy = I->getOperand(0)->getType();
1327 if (SrcTy->isIntegral()) {
1328 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
1329 if (SrcTy->isUnsigned() && // Only handle zero ext.
1330 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
1331 return true;
1332
1333 // If this is a noop cast, recurse.
1334 if (SrcTy != Type::BoolTy)
1335 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() ==I->getType()) ||
1336 SrcTy->getSignedVersion() == I->getType()) {
1337 Constant *NewMask =
1338 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
1339 return MaskedValueIsZero(I->getOperand(0),
1340 cast<ConstantIntegral>(NewMask));
1341 }
1342 }
1343 break;
1344 }
1345 case Instruction::Shl:
1346 // (shl X, C1) & C2 == 0 iff (-1 << C1) & C2 == 0
1347 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1348 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1349 C1 = ConstantExpr::getShl(C1, SA);
1350 C1 = ConstantExpr::getAnd(C1, Mask);
1351 if (C1->isNullValue())
1352 return true;
1353 }
1354 break;
1355 case Instruction::Shr:
1356 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1357 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1358 if (I->getType()->isUnsigned()) {
1359 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1360 C1 = ConstantExpr::getShr(C1, SA);
1361 C1 = ConstantExpr::getAnd(C1, Mask);
1362 if (C1->isNullValue())
1363 return true;
1364 }
1365 break;
1366 }
1367 }
1368
1369 return false;
1370}
1371
Chris Lattnerba1cb382003-09-19 17:17:26 +00001372// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1373// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1374// guaranteed to be either a shift instruction or a binary operator.
1375Instruction *InstCombiner::OptAndOp(Instruction *Op,
1376 ConstantIntegral *OpRHS,
1377 ConstantIntegral *AndRHS,
1378 BinaryOperator &TheAnd) {
1379 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001380 Constant *Together = 0;
1381 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001382 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001383
Chris Lattnerba1cb382003-09-19 17:17:26 +00001384 switch (Op->getOpcode()) {
1385 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001386 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001387 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1388 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001389 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001390 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001391 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001392 }
1393 break;
1394 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001395 if (Together == AndRHS) // (X | C) & C --> C
1396 return ReplaceInstUsesWith(TheAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001397
Chris Lattner86102b82005-01-01 16:22:27 +00001398 if (Op->hasOneUse() && Together != OpRHS) {
1399 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1400 std::string Op0Name = Op->getName(); Op->setName("");
1401 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1402 InsertNewInstBefore(Or, TheAnd);
1403 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001404 }
1405 break;
1406 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001407 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001408 // Adding a one to a single bit bit-field should be turned into an XOR
1409 // of the bit. First thing to check is to see if this AND is with a
1410 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001411 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001412
1413 // Clear bits that are not part of the constant.
1414 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1415
1416 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001417 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001418 // Ok, at this point, we know that we are masking the result of the
1419 // ADD down to exactly one bit. If the constant we are adding has
1420 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001421 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001422
1423 // Check to see if any bits below the one bit set in AndRHSV are set.
1424 if ((AddRHS & (AndRHSV-1)) == 0) {
1425 // If not, the only thing that can effect the output of the AND is
1426 // the bit specified by AndRHSV. If that bit is set, the effect of
1427 // the XOR is to toggle the bit. If it is clear, then the ADD has
1428 // no effect.
1429 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1430 TheAnd.setOperand(0, X);
1431 return &TheAnd;
1432 } else {
1433 std::string Name = Op->getName(); Op->setName("");
1434 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001435 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001436 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001437 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001438 }
1439 }
1440 }
1441 }
1442 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001443
1444 case Instruction::Shl: {
1445 // We know that the AND will not produce any of the bits shifted in, so if
1446 // the anded constant includes them, clear them now!
1447 //
1448 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001449 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1450 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1451
1452 if (CI == ShlMask) { // Masking out bits that the shift already masks
1453 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1454 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001455 TheAnd.setOperand(1, CI);
1456 return &TheAnd;
1457 }
1458 break;
1459 }
1460 case Instruction::Shr:
1461 // We know that the AND will not produce any of the bits shifted in, so if
1462 // the anded constant includes them, clear them now! This only applies to
1463 // unsigned shifts, because a signed shr may bring in set bits!
1464 //
1465 if (AndRHS->getType()->isUnsigned()) {
1466 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001467 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1468 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1469
1470 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1471 return ReplaceInstUsesWith(TheAnd, Op);
1472 } else if (CI != AndRHS) {
1473 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001474 return &TheAnd;
1475 }
Chris Lattner7e794272004-09-24 15:21:34 +00001476 } else { // Signed shr.
1477 // See if this is shifting in some sign extension, then masking it out
1478 // with an and.
1479 if (Op->hasOneUse()) {
1480 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1481 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1482 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001483 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001484 // Make the argument unsigned.
1485 Value *ShVal = Op->getOperand(0);
1486 ShVal = InsertCastBefore(ShVal,
1487 ShVal->getType()->getUnsignedVersion(),
1488 TheAnd);
1489 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1490 OpRHS, Op->getName()),
1491 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001492 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1493 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1494 TheAnd.getName()),
1495 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001496 return new CastInst(ShVal, Op->getType());
1497 }
1498 }
Chris Lattner2da29172003-09-19 19:05:02 +00001499 }
1500 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001501 }
1502 return 0;
1503}
1504
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001505
Chris Lattner6862fbd2004-09-29 17:40:11 +00001506/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1507/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1508/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1509/// insert new instructions.
1510Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1511 bool Inside, Instruction &IB) {
1512 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1513 "Lo is not <= Hi in range emission code!");
1514 if (Inside) {
1515 if (Lo == Hi) // Trivially false.
1516 return new SetCondInst(Instruction::SetNE, V, V);
1517 if (cast<ConstantIntegral>(Lo)->isMinValue())
1518 return new SetCondInst(Instruction::SetLT, V, Hi);
1519
1520 Constant *AddCST = ConstantExpr::getNeg(Lo);
1521 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1522 InsertNewInstBefore(Add, IB);
1523 // Convert to unsigned for the comparison.
1524 const Type *UnsType = Add->getType()->getUnsignedVersion();
1525 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1526 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1527 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1528 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1529 }
1530
1531 if (Lo == Hi) // Trivially true.
1532 return new SetCondInst(Instruction::SetEQ, V, V);
1533
1534 Hi = SubOne(cast<ConstantInt>(Hi));
1535 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1536 return new SetCondInst(Instruction::SetGT, V, Hi);
1537
1538 // Emit X-Lo > Hi-Lo-1
1539 Constant *AddCST = ConstantExpr::getNeg(Lo);
1540 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1541 InsertNewInstBefore(Add, IB);
1542 // Convert to unsigned for the comparison.
1543 const Type *UnsType = Add->getType()->getUnsignedVersion();
1544 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1545 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1546 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1547 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1548}
1549
1550
Chris Lattner113f4f42002-06-25 16:13:24 +00001551Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001552 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001553 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001554
Chris Lattner81a7a232004-10-16 18:11:37 +00001555 if (isa<UndefValue>(Op1)) // X & undef -> 0
1556 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1557
Chris Lattner86102b82005-01-01 16:22:27 +00001558 // and X, X = X
1559 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00001560 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001561
Chris Lattner86102b82005-01-01 16:22:27 +00001562 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001563 // and X, -1 == X
1564 if (AndRHS->isAllOnesValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001565 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001566
Chris Lattner86102b82005-01-01 16:22:27 +00001567 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1568 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1569
1570 // If the mask is not masking out any bits, there is no reason to do the
1571 // and in the first place.
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001572 ConstantIntegral *NotAndRHS =
1573 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
1574 if (MaskedValueIsZero(Op0, NotAndRHS))
1575 return ReplaceInstUsesWith(I, Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001576
Chris Lattnerba1cb382003-09-19 17:17:26 +00001577 // Optimize a variety of ((val OP C1) & C2) combinations...
1578 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1579 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001580 Value *Op0LHS = Op0I->getOperand(0);
1581 Value *Op0RHS = Op0I->getOperand(1);
1582 switch (Op0I->getOpcode()) {
1583 case Instruction::Xor:
1584 case Instruction::Or:
1585 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1586 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1587 if (MaskedValueIsZero(Op0LHS, AndRHS))
1588 return BinaryOperator::createAnd(Op0RHS, AndRHS);
1589 if (MaskedValueIsZero(Op0RHS, AndRHS))
1590 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001591
1592 // If the mask is only needed on one incoming arm, push it up.
1593 if (Op0I->hasOneUse()) {
1594 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1595 // Not masking anything out for the LHS, move to RHS.
1596 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1597 Op0RHS->getName()+".masked");
1598 InsertNewInstBefore(NewRHS, I);
1599 return BinaryOperator::create(
1600 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
1601 }
1602 if (!isa<Constant>(NotAndRHS) &&
1603 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1604 // Not masking anything out for the RHS, move to LHS.
1605 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1606 Op0LHS->getName()+".masked");
1607 InsertNewInstBefore(NewLHS, I);
1608 return BinaryOperator::create(
1609 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1610 }
1611 }
1612
Chris Lattner86102b82005-01-01 16:22:27 +00001613 break;
1614 case Instruction::And:
1615 // (X & V) & C2 --> 0 iff (V & C2) == 0
1616 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1617 MaskedValueIsZero(Op0RHS, AndRHS))
1618 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1619 break;
1620 }
1621
Chris Lattner16464b32003-07-23 19:25:52 +00001622 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00001623 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001624 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00001625 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1626 const Type *SrcTy = CI->getOperand(0)->getType();
1627
1628 // If this is an integer sign or zero extension instruction.
1629 if (SrcTy->isIntegral() &&
1630 SrcTy->getPrimitiveSize() < CI->getType()->getPrimitiveSize()) {
1631
1632 if (SrcTy->isUnsigned()) {
1633 // See if this and is clearing out bits that are known to be zero
1634 // anyway (due to the zero extension).
1635 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1636 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1637 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1638 if (Result == Mask) // The "and" isn't doing anything, remove it.
1639 return ReplaceInstUsesWith(I, CI);
1640 if (Result != AndRHS) { // Reduce the and RHS constant.
1641 I.setOperand(1, Result);
1642 return &I;
1643 }
1644
1645 } else {
1646 if (CI->hasOneUse() && SrcTy->isInteger()) {
1647 // We can only do this if all of the sign bits brought in are masked
1648 // out. Compute this by first getting 0000011111, then inverting
1649 // it.
1650 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1651 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1652 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1653 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1654 // If the and is clearing all of the sign bits, change this to a
1655 // zero extension cast. To do this, cast the cast input to
1656 // unsigned, then to the requested size.
1657 Value *CastOp = CI->getOperand(0);
1658 Instruction *NC =
1659 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1660 CI->getName()+".uns");
1661 NC = InsertNewInstBefore(NC, I);
1662 // Finally, insert a replacement for CI.
1663 NC = new CastInst(NC, CI->getType(), CI->getName());
1664 CI->setName("");
1665 NC = InsertNewInstBefore(NC, I);
1666 WorkList.push_back(CI); // Delete CI later.
1667 I.setOperand(0, NC);
1668 return &I; // The AND operand was modified.
1669 }
1670 }
1671 }
1672 }
Chris Lattner33217db2003-07-23 19:36:21 +00001673 }
Chris Lattner183b3362004-04-09 19:05:30 +00001674
1675 // Try to fold constant and into select arguments.
1676 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001677 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001678 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001679 if (isa<PHINode>(Op0))
1680 if (Instruction *NV = FoldOpIntoPhi(I))
1681 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001682 }
1683
Chris Lattnerbb74e222003-03-10 23:06:50 +00001684 Value *Op0NotVal = dyn_castNotVal(Op0);
1685 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001686
Chris Lattner023a4832004-06-18 06:07:51 +00001687 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1688 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1689
Misha Brukman9c003d82004-07-30 12:50:08 +00001690 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001691 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001692 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1693 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001694 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001695 return BinaryOperator::createNot(Or);
1696 }
1697
Chris Lattner623826c2004-09-28 21:48:02 +00001698 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1699 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001700 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1701 return R;
1702
Chris Lattner623826c2004-09-28 21:48:02 +00001703 Value *LHSVal, *RHSVal;
1704 ConstantInt *LHSCst, *RHSCst;
1705 Instruction::BinaryOps LHSCC, RHSCC;
1706 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1707 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1708 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1709 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1710 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1711 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1712 // Ensure that the larger constant is on the RHS.
1713 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1714 SetCondInst *LHS = cast<SetCondInst>(Op0);
1715 if (cast<ConstantBool>(Cmp)->getValue()) {
1716 std::swap(LHS, RHS);
1717 std::swap(LHSCst, RHSCst);
1718 std::swap(LHSCC, RHSCC);
1719 }
1720
1721 // At this point, we know we have have two setcc instructions
1722 // comparing a value against two constants and and'ing the result
1723 // together. Because of the above check, we know that we only have
1724 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1725 // FoldSetCCLogical check above), that the two constants are not
1726 // equal.
1727 assert(LHSCst != RHSCst && "Compares not folded above?");
1728
1729 switch (LHSCC) {
1730 default: assert(0 && "Unknown integer condition code!");
1731 case Instruction::SetEQ:
1732 switch (RHSCC) {
1733 default: assert(0 && "Unknown integer condition code!");
1734 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1735 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1736 return ReplaceInstUsesWith(I, ConstantBool::False);
1737 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1738 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1739 return ReplaceInstUsesWith(I, LHS);
1740 }
1741 case Instruction::SetNE:
1742 switch (RHSCC) {
1743 default: assert(0 && "Unknown integer condition code!");
1744 case Instruction::SetLT:
1745 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1746 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1747 break; // (X != 13 & X < 15) -> no change
1748 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1749 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1750 return ReplaceInstUsesWith(I, RHS);
1751 case Instruction::SetNE:
1752 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1753 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1754 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1755 LHSVal->getName()+".off");
1756 InsertNewInstBefore(Add, I);
1757 const Type *UnsType = Add->getType()->getUnsignedVersion();
1758 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1759 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1760 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1761 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1762 }
1763 break; // (X != 13 & X != 15) -> no change
1764 }
1765 break;
1766 case Instruction::SetLT:
1767 switch (RHSCC) {
1768 default: assert(0 && "Unknown integer condition code!");
1769 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1770 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1771 return ReplaceInstUsesWith(I, ConstantBool::False);
1772 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1773 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1774 return ReplaceInstUsesWith(I, LHS);
1775 }
1776 case Instruction::SetGT:
1777 switch (RHSCC) {
1778 default: assert(0 && "Unknown integer condition code!");
1779 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1780 return ReplaceInstUsesWith(I, LHS);
1781 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1782 return ReplaceInstUsesWith(I, RHS);
1783 case Instruction::SetNE:
1784 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1785 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1786 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001787 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1788 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001789 }
1790 }
1791 }
1792 }
1793
Chris Lattner113f4f42002-06-25 16:13:24 +00001794 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001795}
1796
Chris Lattner113f4f42002-06-25 16:13:24 +00001797Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001798 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001799 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001800
Chris Lattner81a7a232004-10-16 18:11:37 +00001801 if (isa<UndefValue>(Op1))
1802 return ReplaceInstUsesWith(I, // X | undef -> -1
1803 ConstantIntegral::getAllOnesValue(I.getType()));
1804
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001805 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001806 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1807 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001808
1809 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001810 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001811 // If X is known to only contain bits that already exist in RHS, just
1812 // replace this instruction with RHS directly.
1813 if (MaskedValueIsZero(Op0,
1814 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
1815 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001816
Chris Lattnerd4252a72004-07-30 07:50:03 +00001817 ConstantInt *C1; Value *X;
1818 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1819 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1820 std::string Op0Name = Op0->getName(); Op0->setName("");
1821 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1822 InsertNewInstBefore(Or, I);
1823 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1824 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001825
Chris Lattnerd4252a72004-07-30 07:50:03 +00001826 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1827 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1828 std::string Op0Name = Op0->getName(); Op0->setName("");
1829 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1830 InsertNewInstBefore(Or, I);
1831 return BinaryOperator::createXor(Or,
1832 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001833 }
Chris Lattner183b3362004-04-09 19:05:30 +00001834
1835 // Try to fold constant and into select arguments.
1836 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001837 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001838 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001839 if (isa<PHINode>(Op0))
1840 if (Instruction *NV = FoldOpIntoPhi(I))
1841 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001842 }
1843
Chris Lattner812aab72003-08-12 19:11:07 +00001844 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001845 Value *A, *B; ConstantInt *C1, *C2;
1846 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1847 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1848 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001849
Chris Lattnerd4252a72004-07-30 07:50:03 +00001850 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1851 if (A == Op1) // ~A | A == -1
1852 return ReplaceInstUsesWith(I,
1853 ConstantIntegral::getAllOnesValue(I.getType()));
1854 } else {
1855 A = 0;
1856 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001857
Chris Lattnerd4252a72004-07-30 07:50:03 +00001858 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1859 if (Op0 == B)
1860 return ReplaceInstUsesWith(I,
1861 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001862
Misha Brukman9c003d82004-07-30 12:50:08 +00001863 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001864 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1865 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1866 I.getName()+".demorgan"), I);
1867 return BinaryOperator::createNot(And);
1868 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001869 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001870
Chris Lattner3ac7c262003-08-13 20:16:26 +00001871 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001872 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001873 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1874 return R;
1875
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001876 Value *LHSVal, *RHSVal;
1877 ConstantInt *LHSCst, *RHSCst;
1878 Instruction::BinaryOps LHSCC, RHSCC;
1879 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1880 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1881 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1882 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1883 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1884 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1885 // Ensure that the larger constant is on the RHS.
1886 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1887 SetCondInst *LHS = cast<SetCondInst>(Op0);
1888 if (cast<ConstantBool>(Cmp)->getValue()) {
1889 std::swap(LHS, RHS);
1890 std::swap(LHSCst, RHSCst);
1891 std::swap(LHSCC, RHSCC);
1892 }
1893
1894 // At this point, we know we have have two setcc instructions
1895 // comparing a value against two constants and or'ing the result
1896 // together. Because of the above check, we know that we only have
1897 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1898 // FoldSetCCLogical check above), that the two constants are not
1899 // equal.
1900 assert(LHSCst != RHSCst && "Compares not folded above?");
1901
1902 switch (LHSCC) {
1903 default: assert(0 && "Unknown integer condition code!");
1904 case Instruction::SetEQ:
1905 switch (RHSCC) {
1906 default: assert(0 && "Unknown integer condition code!");
1907 case Instruction::SetEQ:
1908 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1909 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1910 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1911 LHSVal->getName()+".off");
1912 InsertNewInstBefore(Add, I);
1913 const Type *UnsType = Add->getType()->getUnsignedVersion();
1914 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1915 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1916 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1917 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1918 }
1919 break; // (X == 13 | X == 15) -> no change
1920
1921 case Instruction::SetGT:
1922 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1923 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1924 break; // (X == 13 | X > 15) -> no change
1925 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1926 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1927 return ReplaceInstUsesWith(I, RHS);
1928 }
1929 break;
1930 case Instruction::SetNE:
1931 switch (RHSCC) {
1932 default: assert(0 && "Unknown integer condition code!");
1933 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1934 return ReplaceInstUsesWith(I, RHS);
1935 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1936 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1937 return ReplaceInstUsesWith(I, LHS);
1938 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1939 return ReplaceInstUsesWith(I, ConstantBool::True);
1940 }
1941 break;
1942 case Instruction::SetLT:
1943 switch (RHSCC) {
1944 default: assert(0 && "Unknown integer condition code!");
1945 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1946 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001947 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1948 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001949 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1950 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1951 return ReplaceInstUsesWith(I, RHS);
1952 }
1953 break;
1954 case Instruction::SetGT:
1955 switch (RHSCC) {
1956 default: assert(0 && "Unknown integer condition code!");
1957 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1958 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1959 return ReplaceInstUsesWith(I, LHS);
1960 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1961 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1962 return ReplaceInstUsesWith(I, ConstantBool::True);
1963 }
1964 }
1965 }
1966 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001967 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001968}
1969
Chris Lattnerc2076352004-02-16 01:20:27 +00001970// XorSelf - Implements: X ^ X --> 0
1971struct XorSelf {
1972 Value *RHS;
1973 XorSelf(Value *rhs) : RHS(rhs) {}
1974 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1975 Instruction *apply(BinaryOperator &Xor) const {
1976 return &Xor;
1977 }
1978};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001979
1980
Chris Lattner113f4f42002-06-25 16:13:24 +00001981Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001982 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001983 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001984
Chris Lattner81a7a232004-10-16 18:11:37 +00001985 if (isa<UndefValue>(Op1))
1986 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1987
Chris Lattnerc2076352004-02-16 01:20:27 +00001988 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1989 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1990 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001991 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001992 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001993
Chris Lattner97638592003-07-23 21:37:07 +00001994 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001995 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001996 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001997 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001998
Chris Lattner97638592003-07-23 21:37:07 +00001999 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002000 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002001 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002002 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002003 return new SetCondInst(SCI->getInverseCondition(),
2004 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002005
Chris Lattner8f2f5982003-11-05 01:06:05 +00002006 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002007 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2008 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002009 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2010 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002011 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002012 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002013 }
Chris Lattner023a4832004-06-18 06:07:51 +00002014
2015 // ~(~X & Y) --> (X | ~Y)
2016 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2017 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2018 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2019 Instruction *NotY =
2020 BinaryOperator::createNot(Op0I->getOperand(1),
2021 Op0I->getOperand(1)->getName()+".not");
2022 InsertNewInstBefore(NotY, I);
2023 return BinaryOperator::createOr(Op0NotVal, NotY);
2024 }
2025 }
Chris Lattner97638592003-07-23 21:37:07 +00002026
2027 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002028 switch (Op0I->getOpcode()) {
2029 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002030 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002031 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002032 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2033 return BinaryOperator::createSub(
2034 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002035 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002036 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002037 }
Chris Lattnere5806662003-11-04 23:50:51 +00002038 break;
2039 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002040 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002041 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2042 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002043 break;
2044 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002045 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002046 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002047 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002048 break;
2049 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002050 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002051 }
Chris Lattner183b3362004-04-09 19:05:30 +00002052
2053 // Try to fold constant and into select arguments.
2054 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002055 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002056 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002057 if (isa<PHINode>(Op0))
2058 if (Instruction *NV = FoldOpIntoPhi(I))
2059 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002060 }
2061
Chris Lattnerbb74e222003-03-10 23:06:50 +00002062 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002063 if (X == Op1)
2064 return ReplaceInstUsesWith(I,
2065 ConstantIntegral::getAllOnesValue(I.getType()));
2066
Chris Lattnerbb74e222003-03-10 23:06:50 +00002067 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002068 if (X == Op0)
2069 return ReplaceInstUsesWith(I,
2070 ConstantIntegral::getAllOnesValue(I.getType()));
2071
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002072 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002073 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002074 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2075 cast<BinaryOperator>(Op1I)->swapOperands();
2076 I.swapOperands();
2077 std::swap(Op0, Op1);
2078 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2079 I.swapOperands();
2080 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00002081 }
2082 } else if (Op1I->getOpcode() == Instruction::Xor) {
2083 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2084 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2085 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2086 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2087 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002088
2089 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002090 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002091 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2092 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002093 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002094 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2095 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002096 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002097 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002098 } else if (Op0I->getOpcode() == Instruction::Xor) {
2099 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2100 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2101 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2102 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002103 }
2104
Chris Lattner7aa2d472004-08-01 19:42:59 +00002105 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002106 Value *A, *B; ConstantInt *C1, *C2;
2107 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2108 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002109 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002110 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002111
Chris Lattner3ac7c262003-08-13 20:16:26 +00002112 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2113 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2114 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2115 return R;
2116
Chris Lattner113f4f42002-06-25 16:13:24 +00002117 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002118}
2119
Chris Lattner6862fbd2004-09-29 17:40:11 +00002120/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2121/// overflowed for this type.
2122static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2123 ConstantInt *In2) {
2124 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2125 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2126}
2127
2128static bool isPositive(ConstantInt *C) {
2129 return cast<ConstantSInt>(C)->getValue() >= 0;
2130}
2131
2132/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2133/// overflowed for this type.
2134static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2135 ConstantInt *In2) {
2136 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2137
2138 if (In1->getType()->isUnsigned())
2139 return cast<ConstantUInt>(Result)->getValue() <
2140 cast<ConstantUInt>(In1)->getValue();
2141 if (isPositive(In1) != isPositive(In2))
2142 return false;
2143 if (isPositive(In1))
2144 return cast<ConstantSInt>(Result)->getValue() <
2145 cast<ConstantSInt>(In1)->getValue();
2146 return cast<ConstantSInt>(Result)->getValue() >
2147 cast<ConstantSInt>(In1)->getValue();
2148}
2149
Chris Lattner0798af32005-01-13 20:14:25 +00002150/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2151/// code necessary to compute the offset from the base pointer (without adding
2152/// in the base pointer). Return the result as a signed integer of intptr size.
2153static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2154 TargetData &TD = IC.getTargetData();
2155 gep_type_iterator GTI = gep_type_begin(GEP);
2156 const Type *UIntPtrTy = TD.getIntPtrType();
2157 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2158 Value *Result = Constant::getNullValue(SIntPtrTy);
2159
2160 // Build a mask for high order bits.
2161 uint64_t PtrSizeMask = ~0ULL;
2162 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2163
Chris Lattner0798af32005-01-13 20:14:25 +00002164 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2165 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002166 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002167 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2168 SIntPtrTy);
2169 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2170 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002171 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002172 Scale = ConstantExpr::getMul(OpC, Scale);
2173 if (Constant *RC = dyn_cast<Constant>(Result))
2174 Result = ConstantExpr::getAdd(RC, Scale);
2175 else {
2176 // Emit an add instruction.
2177 Result = IC.InsertNewInstBefore(
2178 BinaryOperator::createAdd(Result, Scale,
2179 GEP->getName()+".offs"), I);
2180 }
2181 }
2182 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002183 // Convert to correct type.
2184 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2185 Op->getName()+".c"), I);
2186 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002187 // We'll let instcombine(mul) convert this to a shl if possible.
2188 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2189 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002190
2191 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002192 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002193 GEP->getName()+".offs"), I);
2194 }
2195 }
2196 return Result;
2197}
2198
2199/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2200/// else. At this point we know that the GEP is on the LHS of the comparison.
2201Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2202 Instruction::BinaryOps Cond,
2203 Instruction &I) {
2204 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002205
2206 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2207 if (isa<PointerType>(CI->getOperand(0)->getType()))
2208 RHS = CI->getOperand(0);
2209
Chris Lattner0798af32005-01-13 20:14:25 +00002210 Value *PtrBase = GEPLHS->getOperand(0);
2211 if (PtrBase == RHS) {
2212 // As an optimization, we don't actually have to compute the actual value of
2213 // OFFSET if this is a seteq or setne comparison, just return whether each
2214 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002215 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2216 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002217 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2218 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00002219 bool EmitIt = true;
2220 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2221 if (isa<UndefValue>(C)) // undef index -> undef.
2222 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2223 if (C->isNullValue())
2224 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002225 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2226 EmitIt = false; // This is indexing into a zero sized array?
2227 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00002228 return ReplaceInstUsesWith(I, // No comparison is needed here.
2229 ConstantBool::get(Cond == Instruction::SetNE));
2230 }
2231
2232 if (EmitIt) {
2233 Instruction *Comp =
2234 new SetCondInst(Cond, GEPLHS->getOperand(i),
2235 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2236 if (InVal == 0)
2237 InVal = Comp;
2238 else {
2239 InVal = InsertNewInstBefore(InVal, I);
2240 InsertNewInstBefore(Comp, I);
2241 if (Cond == Instruction::SetNE) // True if any are unequal
2242 InVal = BinaryOperator::createOr(InVal, Comp);
2243 else // True if all are equal
2244 InVal = BinaryOperator::createAnd(InVal, Comp);
2245 }
2246 }
2247 }
2248
2249 if (InVal)
2250 return InVal;
2251 else
2252 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2253 ConstantBool::get(Cond == Instruction::SetEQ));
2254 }
Chris Lattner0798af32005-01-13 20:14:25 +00002255
2256 // Only lower this if the setcc is the only user of the GEP or if we expect
2257 // the result to fold to a constant!
2258 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2259 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2260 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2261 return new SetCondInst(Cond, Offset,
2262 Constant::getNullValue(Offset->getType()));
2263 }
2264 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
2265 if (PtrBase != GEPRHS->getOperand(0))
2266 return 0;
2267
Chris Lattner81e84172005-01-13 22:25:21 +00002268 // If one of the GEPs has all zero indices, recurse.
2269 bool AllZeros = true;
2270 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2271 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2272 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2273 AllZeros = false;
2274 break;
2275 }
2276 if (AllZeros)
2277 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2278 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00002279
2280 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00002281 AllZeros = true;
2282 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2283 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2284 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2285 AllZeros = false;
2286 break;
2287 }
2288 if (AllZeros)
2289 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2290
Chris Lattner4fa89822005-01-14 00:20:05 +00002291 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2292 // If the GEPs only differ by one index, compare it.
2293 unsigned NumDifferences = 0; // Keep track of # differences.
2294 unsigned DiffOperand = 0; // The operand that differs.
2295 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2296 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002297 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSize() !=
2298 GEPRHS->getOperand(i)->getType()->getPrimitiveSize()) {
2299 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00002300 NumDifferences = 2;
2301 break;
2302 } else {
2303 if (NumDifferences++) break;
2304 DiffOperand = i;
2305 }
2306 }
2307
2308 if (NumDifferences == 0) // SAME GEP?
2309 return ReplaceInstUsesWith(I, // No comparison is needed here.
2310 ConstantBool::get(Cond == Instruction::SetEQ));
2311 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002312 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2313 Value *RHSV = GEPRHS->getOperand(DiffOperand);
2314 if (LHSV->getType() != RHSV->getType())
2315 LHSV = InsertNewInstBefore(new CastInst(LHSV, RHSV->getType(),
2316 LHSV->getName()+".c"), I);
2317 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00002318 }
2319 }
2320
Chris Lattner0798af32005-01-13 20:14:25 +00002321 // Only lower this if the setcc is the only user of the GEP or if we expect
2322 // the result to fold to a constant!
2323 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2324 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2325 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2326 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2327 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2328 return new SetCondInst(Cond, L, R);
2329 }
2330 }
2331 return 0;
2332}
2333
2334
Chris Lattner113f4f42002-06-25 16:13:24 +00002335Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002336 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002337 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2338 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002339
2340 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002341 if (Op0 == Op1)
2342 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002343
Chris Lattner81a7a232004-10-16 18:11:37 +00002344 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2345 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2346
Chris Lattner15ff1e12004-11-14 07:33:16 +00002347 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2348 // addresses never equal each other! We already know that Op0 != Op1.
2349 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2350 isa<ConstantPointerNull>(Op0)) &&
2351 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
2352 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002353 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2354
2355 // setcc's with boolean values can always be turned into bitwise operations
2356 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002357 switch (I.getOpcode()) {
2358 default: assert(0 && "Invalid setcc instruction!");
2359 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002360 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002361 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002362 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002363 }
Chris Lattner4456da62004-08-11 00:50:51 +00002364 case Instruction::SetNE:
2365 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002366
Chris Lattner4456da62004-08-11 00:50:51 +00002367 case Instruction::SetGT:
2368 std::swap(Op0, Op1); // Change setgt -> setlt
2369 // FALL THROUGH
2370 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2371 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2372 InsertNewInstBefore(Not, I);
2373 return BinaryOperator::createAnd(Not, Op1);
2374 }
2375 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002376 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002377 // FALL THROUGH
2378 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2379 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2380 InsertNewInstBefore(Not, I);
2381 return BinaryOperator::createOr(Not, Op1);
2382 }
2383 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002384 }
2385
Chris Lattner2dd01742004-06-09 04:24:29 +00002386 // See if we are doing a comparison between a constant and an instruction that
2387 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002388 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002389 // Check to see if we are comparing against the minimum or maximum value...
2390 if (CI->isMinValue()) {
2391 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2392 return ReplaceInstUsesWith(I, ConstantBool::False);
2393 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2394 return ReplaceInstUsesWith(I, ConstantBool::True);
2395 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2396 return BinaryOperator::createSetEQ(Op0, Op1);
2397 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2398 return BinaryOperator::createSetNE(Op0, Op1);
2399
2400 } else if (CI->isMaxValue()) {
2401 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2402 return ReplaceInstUsesWith(I, ConstantBool::False);
2403 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2404 return ReplaceInstUsesWith(I, ConstantBool::True);
2405 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2406 return BinaryOperator::createSetEQ(Op0, Op1);
2407 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2408 return BinaryOperator::createSetNE(Op0, Op1);
2409
2410 // Comparing against a value really close to min or max?
2411 } else if (isMinValuePlusOne(CI)) {
2412 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2413 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2414 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2415 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2416
2417 } else if (isMaxValueMinusOne(CI)) {
2418 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2419 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2420 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2421 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2422 }
2423
2424 // If we still have a setle or setge instruction, turn it into the
2425 // appropriate setlt or setgt instruction. Since the border cases have
2426 // already been handled above, this requires little checking.
2427 //
2428 if (I.getOpcode() == Instruction::SetLE)
2429 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2430 if (I.getOpcode() == Instruction::SetGE)
2431 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2432
Chris Lattnere1e10e12004-05-25 06:32:08 +00002433 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002434 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002435 case Instruction::PHI:
2436 if (Instruction *NV = FoldOpIntoPhi(I))
2437 return NV;
2438 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002439 case Instruction::And:
2440 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2441 LHSI->getOperand(0)->hasOneUse()) {
2442 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2443 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2444 // happens a LOT in code produced by the C front-end, for bitfield
2445 // access.
2446 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2447 ConstantUInt *ShAmt;
2448 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2449 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2450 const Type *Ty = LHSI->getType();
2451
2452 // We can fold this as long as we can't shift unknown bits
2453 // into the mask. This can only happen with signed shift
2454 // rights, as they sign-extend.
2455 if (ShAmt) {
2456 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002457 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002458 if (!CanFold) {
2459 // To test for the bad case of the signed shr, see if any
2460 // of the bits shifted in could be tested after the mask.
2461 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00002462 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002463 Constant *ShVal =
2464 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2465 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2466 CanFold = true;
2467 }
2468
2469 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002470 Constant *NewCst;
2471 if (Shift->getOpcode() == Instruction::Shl)
2472 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2473 else
2474 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002475
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002476 // Check to see if we are shifting out any of the bits being
2477 // compared.
2478 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2479 // If we shifted bits out, the fold is not going to work out.
2480 // As a special case, check to see if this means that the
2481 // result is always true or false now.
2482 if (I.getOpcode() == Instruction::SetEQ)
2483 return ReplaceInstUsesWith(I, ConstantBool::False);
2484 if (I.getOpcode() == Instruction::SetNE)
2485 return ReplaceInstUsesWith(I, ConstantBool::True);
2486 } else {
2487 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002488 Constant *NewAndCST;
2489 if (Shift->getOpcode() == Instruction::Shl)
2490 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2491 else
2492 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2493 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002494 LHSI->setOperand(0, Shift->getOperand(0));
2495 WorkList.push_back(Shift); // Shift is dead.
2496 AddUsesToWorkList(I);
2497 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002498 }
2499 }
Chris Lattner35167c32004-06-09 07:59:58 +00002500 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002501 }
2502 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002503
Reid Spencer279fa252004-11-28 21:31:15 +00002504 // (setcc (cast X to larger), CI)
Chris Lattner03f06f12005-01-17 03:20:02 +00002505 case Instruction::Cast:
2506 if (Instruction *R =
2507 visitSetCondInstWithCastAndConstant(I,cast<CastInst>(LHSI),CI))
2508 return R;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002509 break;
Reid Spencer279fa252004-11-28 21:31:15 +00002510
Chris Lattner272d5ca2004-09-28 18:22:15 +00002511 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2512 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2513 switch (I.getOpcode()) {
2514 default: break;
2515 case Instruction::SetEQ:
2516 case Instruction::SetNE: {
2517 // If we are comparing against bits always shifted out, the
2518 // comparison cannot succeed.
2519 Constant *Comp =
2520 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2521 if (Comp != CI) {// Comparing against a bit that we know is zero.
2522 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2523 Constant *Cst = ConstantBool::get(IsSetNE);
2524 return ReplaceInstUsesWith(I, Cst);
2525 }
2526
2527 if (LHSI->hasOneUse()) {
2528 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002529 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002530 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2531 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2532
2533 Constant *Mask;
2534 if (CI->getType()->isUnsigned()) {
2535 Mask = ConstantUInt::get(CI->getType(), Val);
2536 } else if (ShAmtVal != 0) {
2537 Mask = ConstantSInt::get(CI->getType(), Val);
2538 } else {
2539 Mask = ConstantInt::getAllOnesValue(CI->getType());
2540 }
2541
2542 Instruction *AndI =
2543 BinaryOperator::createAnd(LHSI->getOperand(0),
2544 Mask, LHSI->getName()+".mask");
2545 Value *And = InsertNewInstBefore(AndI, I);
2546 return new SetCondInst(I.getOpcode(), And,
2547 ConstantExpr::getUShr(CI, ShAmt));
2548 }
2549 }
2550 }
2551 }
2552 break;
2553
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002554 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002555 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002556 switch (I.getOpcode()) {
2557 default: break;
2558 case Instruction::SetEQ:
2559 case Instruction::SetNE: {
2560 // If we are comparing against bits always shifted out, the
2561 // comparison cannot succeed.
2562 Constant *Comp =
2563 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2564
2565 if (Comp != CI) {// Comparing against a bit that we know is zero.
2566 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2567 Constant *Cst = ConstantBool::get(IsSetNE);
2568 return ReplaceInstUsesWith(I, Cst);
2569 }
2570
2571 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002572 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002573
Chris Lattner1023b872004-09-27 16:18:50 +00002574 // Otherwise strength reduce the shift into an and.
2575 uint64_t Val = ~0ULL; // All ones.
2576 Val <<= ShAmtVal; // Shift over to the right spot.
2577
2578 Constant *Mask;
2579 if (CI->getType()->isUnsigned()) {
2580 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
Chris Lattnercfe2822c2005-03-04 23:21:33 +00002581 if (TypeBits != 64)
2582 Val &= (1ULL << TypeBits)-1;
Chris Lattner1023b872004-09-27 16:18:50 +00002583 Mask = ConstantUInt::get(CI->getType(), Val);
2584 } else {
2585 Mask = ConstantSInt::get(CI->getType(), Val);
2586 }
2587
2588 Instruction *AndI =
2589 BinaryOperator::createAnd(LHSI->getOperand(0),
2590 Mask, LHSI->getName()+".mask");
2591 Value *And = InsertNewInstBefore(AndI, I);
2592 return new SetCondInst(I.getOpcode(), And,
2593 ConstantExpr::getShl(CI, ShAmt));
2594 }
2595 break;
2596 }
2597 }
2598 }
2599 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002600
Chris Lattner6862fbd2004-09-29 17:40:11 +00002601 case Instruction::Div:
2602 // Fold: (div X, C1) op C2 -> range check
2603 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2604 // Fold this div into the comparison, producing a range check.
2605 // Determine, based on the divide type, what the range is being
2606 // checked. If there is an overflow on the low or high side, remember
2607 // it, otherwise compute the range [low, hi) bounding the new value.
2608 bool LoOverflow = false, HiOverflow = 0;
2609 ConstantInt *LoBound = 0, *HiBound = 0;
2610
2611 ConstantInt *Prod;
2612 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2613
Chris Lattnera92af962004-10-11 19:40:04 +00002614 Instruction::BinaryOps Opcode = I.getOpcode();
2615
Chris Lattner6862fbd2004-09-29 17:40:11 +00002616 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2617 } else if (LHSI->getType()->isUnsigned()) { // udiv
2618 LoBound = Prod;
2619 LoOverflow = ProdOV;
2620 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2621 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2622 if (CI->isNullValue()) { // (X / pos) op 0
2623 // Can't overflow.
2624 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2625 HiBound = DivRHS;
2626 } else if (isPositive(CI)) { // (X / pos) op pos
2627 LoBound = Prod;
2628 LoOverflow = ProdOV;
2629 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2630 } else { // (X / pos) op neg
2631 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2632 LoOverflow = AddWithOverflow(LoBound, Prod,
2633 cast<ConstantInt>(DivRHSH));
2634 HiBound = Prod;
2635 HiOverflow = ProdOV;
2636 }
2637 } else { // Divisor is < 0.
2638 if (CI->isNullValue()) { // (X / neg) op 0
2639 LoBound = AddOne(DivRHS);
2640 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2641 } else if (isPositive(CI)) { // (X / neg) op pos
2642 HiOverflow = LoOverflow = ProdOV;
2643 if (!LoOverflow)
2644 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2645 HiBound = AddOne(Prod);
2646 } else { // (X / neg) op neg
2647 LoBound = Prod;
2648 LoOverflow = HiOverflow = ProdOV;
2649 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2650 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002651
Chris Lattnera92af962004-10-11 19:40:04 +00002652 // Dividing by a negate swaps the condition.
2653 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002654 }
2655
2656 if (LoBound) {
2657 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002658 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002659 default: assert(0 && "Unhandled setcc opcode!");
2660 case Instruction::SetEQ:
2661 if (LoOverflow && HiOverflow)
2662 return ReplaceInstUsesWith(I, ConstantBool::False);
2663 else if (HiOverflow)
2664 return new SetCondInst(Instruction::SetGE, X, LoBound);
2665 else if (LoOverflow)
2666 return new SetCondInst(Instruction::SetLT, X, HiBound);
2667 else
2668 return InsertRangeTest(X, LoBound, HiBound, true, I);
2669 case Instruction::SetNE:
2670 if (LoOverflow && HiOverflow)
2671 return ReplaceInstUsesWith(I, ConstantBool::True);
2672 else if (HiOverflow)
2673 return new SetCondInst(Instruction::SetLT, X, LoBound);
2674 else if (LoOverflow)
2675 return new SetCondInst(Instruction::SetGE, X, HiBound);
2676 else
2677 return InsertRangeTest(X, LoBound, HiBound, false, I);
2678 case Instruction::SetLT:
2679 if (LoOverflow)
2680 return ReplaceInstUsesWith(I, ConstantBool::False);
2681 return new SetCondInst(Instruction::SetLT, X, LoBound);
2682 case Instruction::SetGT:
2683 if (HiOverflow)
2684 return ReplaceInstUsesWith(I, ConstantBool::False);
2685 return new SetCondInst(Instruction::SetGE, X, HiBound);
2686 }
2687 }
2688 }
2689 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002690 case Instruction::Select:
2691 // If either operand of the select is a constant, we can fold the
2692 // comparison into the select arms, which will cause one to be
2693 // constant folded and the select turned into a bitwise or.
2694 Value *Op1 = 0, *Op2 = 0;
2695 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00002696 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002697 // Fold the known value into the constant operand.
2698 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2699 // Insert a new SetCC of the other select operand.
2700 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002701 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002702 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00002703 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002704 // Fold the known value into the constant operand.
2705 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2706 // Insert a new SetCC of the other select operand.
2707 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002708 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002709 I.getName()), I);
2710 }
Chris Lattner2dd01742004-06-09 04:24:29 +00002711 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002712
2713 if (Op1)
2714 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2715 break;
2716 }
2717
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002718 // Simplify seteq and setne instructions...
2719 if (I.getOpcode() == Instruction::SetEQ ||
2720 I.getOpcode() == Instruction::SetNE) {
2721 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2722
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002723 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002724 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002725 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2726 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002727 case Instruction::Rem:
2728 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2729 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2730 BO->hasOneUse() &&
2731 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2732 if (unsigned L2 =
2733 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2734 const Type *UTy = BO->getType()->getUnsignedVersion();
2735 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2736 UTy, "tmp"), I);
2737 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2738 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2739 RHSCst, BO->getName()), I);
2740 return BinaryOperator::create(I.getOpcode(), NewRem,
2741 Constant::getNullValue(UTy));
2742 }
2743 break;
2744
Chris Lattnerc992add2003-08-13 05:33:12 +00002745 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002746 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2747 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002748 if (BO->hasOneUse())
2749 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2750 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002751 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002752 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2753 // efficiently invertible, or if the add has just this one use.
2754 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00002755
Chris Lattnerc992add2003-08-13 05:33:12 +00002756 if (Value *NegVal = dyn_castNegVal(BOp1))
2757 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2758 else if (Value *NegVal = dyn_castNegVal(BOp0))
2759 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002760 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002761 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2762 BO->setName("");
2763 InsertNewInstBefore(Neg, I);
2764 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2765 }
2766 }
2767 break;
2768 case Instruction::Xor:
2769 // For the xor case, we can xor two constants together, eliminating
2770 // the explicit xor.
2771 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2772 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002773 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002774
2775 // FALLTHROUGH
2776 case Instruction::Sub:
2777 // Replace (([sub|xor] A, B) != 0) with (A != B)
2778 if (CI->isNullValue())
2779 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2780 BO->getOperand(1));
2781 break;
2782
2783 case Instruction::Or:
2784 // If bits are being or'd in that are not present in the constant we
2785 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002786 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002787 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002788 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002789 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002790 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002791 break;
2792
2793 case Instruction::And:
2794 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002795 // If bits are being compared against that are and'd out, then the
2796 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002797 if (!ConstantExpr::getAnd(CI,
2798 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002799 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002800
Chris Lattner35167c32004-06-09 07:59:58 +00002801 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002802 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002803 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2804 Instruction::SetNE, Op0,
2805 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002806
Chris Lattnerc992add2003-08-13 05:33:12 +00002807 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2808 // to be a signed value as appropriate.
2809 if (isSignBit(BOC)) {
2810 Value *X = BO->getOperand(0);
2811 // If 'X' is not signed, insert a cast now...
2812 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002813 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002814 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002815 }
2816 return new SetCondInst(isSetNE ? Instruction::SetLT :
2817 Instruction::SetGE, X,
2818 Constant::getNullValue(X->getType()));
2819 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002820
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002821 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002822 if (CI->isNullValue() && isHighOnes(BOC)) {
2823 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002824 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002825
2826 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002827 if (NegX->getType()->isSigned()) {
2828 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2829 X = InsertCastBefore(X, DestTy, I);
2830 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002831 }
2832
2833 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002834 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002835 }
2836
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002837 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002838 default: break;
2839 }
2840 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002841 } else { // Not a SetEQ/SetNE
2842 // If the LHS is a cast from an integral value of the same size,
2843 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2844 Value *CastOp = Cast->getOperand(0);
2845 const Type *SrcTy = CastOp->getType();
2846 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2847 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2848 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2849 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2850 "Source and destination signednesses should differ!");
2851 if (Cast->getType()->isSigned()) {
2852 // If this is a signed comparison, check for comparisons in the
2853 // vicinity of zero.
2854 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2855 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002856 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002857 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2858 else if (I.getOpcode() == Instruction::SetGT &&
2859 cast<ConstantSInt>(CI)->getValue() == -1)
2860 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002861 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002862 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2863 } else {
2864 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2865 if (I.getOpcode() == Instruction::SetLT &&
2866 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2867 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002868 return BinaryOperator::createSetGT(CastOp,
2869 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002870 else if (I.getOpcode() == Instruction::SetGT &&
2871 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2872 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002873 return BinaryOperator::createSetLT(CastOp,
2874 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002875 }
2876 }
2877 }
Chris Lattnere967b342003-06-04 05:10:11 +00002878 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002879 }
2880
Chris Lattner0798af32005-01-13 20:14:25 +00002881 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
2882 if (User *GEP = dyn_castGetElementPtr(Op0))
2883 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
2884 return NI;
2885 if (User *GEP = dyn_castGetElementPtr(Op1))
2886 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
2887 SetCondInst::getSwappedCondition(I.getOpcode()), I))
2888 return NI;
2889
Chris Lattner16930792003-11-03 04:25:02 +00002890 // Test to see if the operands of the setcc are casted versions of other
2891 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002892 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2893 Value *CastOp0 = CI->getOperand(0);
2894 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002895 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002896 (I.getOpcode() == Instruction::SetEQ ||
2897 I.getOpcode() == Instruction::SetNE)) {
2898 // We keep moving the cast from the left operand over to the right
2899 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002900 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002901
2902 // If operand #1 is a cast instruction, see if we can eliminate it as
2903 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002904 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2905 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002906 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002907 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002908
2909 // If Op1 is a constant, we can fold the cast into the constant.
2910 if (Op1->getType() != Op0->getType())
2911 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2912 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2913 } else {
2914 // Otherwise, cast the RHS right before the setcc
2915 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2916 InsertNewInstBefore(cast<Instruction>(Op1), I);
2917 }
2918 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2919 }
2920
Chris Lattner6444c372003-11-03 05:17:03 +00002921 // Handle the special case of: setcc (cast bool to X), <cst>
2922 // This comes up when you have code like
2923 // int X = A < B;
2924 // if (X) ...
2925 // For generality, we handle any zero-extension of any operand comparison
2926 // with a constant.
2927 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2928 const Type *SrcTy = CastOp0->getType();
2929 const Type *DestTy = Op0->getType();
2930 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2931 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2932 // Ok, we have an expansion of operand 0 into a new type. Get the
2933 // constant value, masink off bits which are not set in the RHS. These
2934 // could be set if the destination value is signed.
2935 uint64_t ConstVal = ConstantRHS->getRawValue();
2936 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2937
2938 // If the constant we are comparing it with has high bits set, which
2939 // don't exist in the original value, the values could never be equal,
2940 // because the source would be zero extended.
2941 unsigned SrcBits =
2942 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002943 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2944 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002945 switch (I.getOpcode()) {
2946 default: assert(0 && "Unknown comparison type!");
2947 case Instruction::SetEQ:
2948 return ReplaceInstUsesWith(I, ConstantBool::False);
2949 case Instruction::SetNE:
2950 return ReplaceInstUsesWith(I, ConstantBool::True);
2951 case Instruction::SetLT:
2952 case Instruction::SetLE:
2953 if (DestTy->isSigned() && HasSignBit)
2954 return ReplaceInstUsesWith(I, ConstantBool::False);
2955 return ReplaceInstUsesWith(I, ConstantBool::True);
2956 case Instruction::SetGT:
2957 case Instruction::SetGE:
2958 if (DestTy->isSigned() && HasSignBit)
2959 return ReplaceInstUsesWith(I, ConstantBool::True);
2960 return ReplaceInstUsesWith(I, ConstantBool::False);
2961 }
2962 }
2963
2964 // Otherwise, we can replace the setcc with a setcc of the smaller
2965 // operand value.
2966 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2967 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2968 }
2969 }
2970 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002971 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002972}
2973
Reid Spencer279fa252004-11-28 21:31:15 +00002974// visitSetCondInstWithCastAndConstant - this method is part of the
2975// visitSetCondInst method. It handles the situation where we have:
2976// (setcc (cast X to larger), CI)
2977// It tries to remove the cast and even the setcc if the CI value
2978// and range of the cast allow it.
2979Instruction *
2980InstCombiner::visitSetCondInstWithCastAndConstant(BinaryOperator&I,
2981 CastInst* LHSI,
2982 ConstantInt* CI) {
2983 const Type *SrcTy = LHSI->getOperand(0)->getType();
2984 const Type *DestTy = LHSI->getType();
Chris Lattner03f06f12005-01-17 03:20:02 +00002985 if (!SrcTy->isIntegral() || !DestTy->isIntegral())
2986 return 0;
2987
2988 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
2989 unsigned DestBits = DestTy->getPrimitiveSize()*8;
2990 if (SrcTy == Type::BoolTy)
2991 SrcBits = 1;
2992 if (DestTy == Type::BoolTy)
2993 DestBits = 1;
2994 if (SrcBits < DestBits) {
2995 // There are fewer bits in the source of the cast than in the result
2996 // of the cast. Any other case doesn't matter because the constant
2997 // value won't have changed due to sign extension.
2998 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
2999 if (ConstantExpr::getCast(NewCst, DestTy) == CI) {
3000 // The constant value operand of the setCC before and after a
3001 // cast to the source type of the cast instruction is the same
3002 // value, so we just replace with the same setcc opcode, but
3003 // using the source value compared to the constant casted to the
3004 // source type.
3005 if (SrcTy->isSigned() && DestTy->isUnsigned()) {
3006 CastInst* Cst = new CastInst(LHSI->getOperand(0),
3007 SrcTy->getUnsignedVersion(),
3008 LHSI->getName());
3009 InsertNewInstBefore(Cst,I);
3010 return new SetCondInst(I.getOpcode(), Cst,
3011 ConstantExpr::getCast(CI,
3012 SrcTy->getUnsignedVersion()));
Reid Spencer279fa252004-11-28 21:31:15 +00003013 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003014 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),NewCst);
3015 }
3016
3017 // The constant value before and after a cast to the source type
3018 // is different, so various cases are possible depending on the
3019 // opcode and the signs of the types involved in the cast.
3020 switch (I.getOpcode()) {
3021 case Instruction::SetLT: {
3022 return 0;
3023 Constant* Max = ConstantIntegral::getMaxValue(SrcTy);
3024 Max = ConstantExpr::getCast(Max, DestTy);
3025 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
3026 }
3027 case Instruction::SetGT: {
3028 return 0; // FIXME! RENABLE. This breaks for (cast sbyte to uint) > 255
3029 Constant* Min = ConstantIntegral::getMinValue(SrcTy);
3030 Min = ConstantExpr::getCast(Min, DestTy);
3031 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
3032 }
3033 case Instruction::SetEQ:
3034 // We're looking for equality, and we know the values are not
3035 // equal so replace with constant False.
3036 return ReplaceInstUsesWith(I, ConstantBool::False);
3037 case Instruction::SetNE:
3038 // We're testing for inequality, and we know the values are not
3039 // equal so replace with constant True.
3040 return ReplaceInstUsesWith(I, ConstantBool::True);
3041 case Instruction::SetLE:
3042 case Instruction::SetGE:
3043 assert(0 && "SetLE and SetGE should be handled elsewhere");
3044 default:
3045 assert(0 && "unknown integer comparison");
Reid Spencer279fa252004-11-28 21:31:15 +00003046 }
3047 }
3048 return 0;
3049}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003050
3051
Chris Lattnere8d6c602003-03-10 19:16:08 +00003052Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003053 assert(I.getOperand(1)->getType() == Type::UByteTy);
3054 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003055 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003056
3057 // shl X, 0 == X and shr X, 0 == X
3058 // shl 0, X == 0 and shr 0, X == 0
3059 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003060 Op0 == Constant::getNullValue(Op0->getType()))
3061 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003062
Chris Lattner81a7a232004-10-16 18:11:37 +00003063 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3064 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003065 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003066 else // undef << X -> 0 AND undef >>u X -> 0
3067 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3068 }
3069 if (isa<UndefValue>(Op1)) {
3070 if (isLeftShift || I.getType()->isUnsigned())
3071 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3072 else
3073 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3074 }
3075
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003076 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3077 if (!isLeftShift)
3078 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3079 if (CSI->isAllOnesValue())
3080 return ReplaceInstUsesWith(I, CSI);
3081
Chris Lattner183b3362004-04-09 19:05:30 +00003082 // Try to fold constant and into select arguments.
3083 if (isa<Constant>(Op0))
3084 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003085 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003086 return R;
3087
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003088 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003089 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3090 // of a signed value.
3091 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00003092 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003093 if (CUI->getValue() >= TypeBits) {
3094 if (!Op0->getType()->isSigned() || isLeftShift)
3095 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3096 else {
3097 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3098 return &I;
3099 }
3100 }
Chris Lattner55f3d942002-09-10 23:04:09 +00003101
Chris Lattnerede3fe02003-08-13 04:18:28 +00003102 // ((X*C1) << C2) == (X * (C1 << C2))
3103 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3104 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3105 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003106 return BinaryOperator::createMul(BO->getOperand(0),
3107 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00003108
Chris Lattner183b3362004-04-09 19:05:30 +00003109 // Try to fold constant and into select arguments.
3110 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003111 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003112 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003113 if (isa<PHINode>(Op0))
3114 if (Instruction *NV = FoldOpIntoPhi(I))
3115 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00003116
Chris Lattner86102b82005-01-01 16:22:27 +00003117 if (Op0->hasOneUse()) {
3118 // If this is a SHL of a sign-extending cast, see if we can turn the input
3119 // into a zero extending cast (a simple strength reduction).
3120 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3121 const Type *SrcTy = CI->getOperand(0)->getType();
3122 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3123 SrcTy->getPrimitiveSize() < CI->getType()->getPrimitiveSize()) {
3124 // We can change it to a zero extension if we are shifting out all of
3125 // the sign extended bits. To check this, form a mask of all of the
3126 // sign extend bits, then shift them left and see if we have anything
3127 // left.
3128 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3129 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3130 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3131 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3132 // If the shift is nuking all of the sign bits, change this to a
3133 // zero extension cast. To do this, cast the cast input to
3134 // unsigned, then to the requested size.
3135 Value *CastOp = CI->getOperand(0);
3136 Instruction *NC =
3137 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3138 CI->getName()+".uns");
3139 NC = InsertNewInstBefore(NC, I);
3140 // Finally, insert a replacement for CI.
3141 NC = new CastInst(NC, CI->getType(), CI->getName());
3142 CI->setName("");
3143 NC = InsertNewInstBefore(NC, I);
3144 WorkList.push_back(CI); // Delete CI later.
3145 I.setOperand(0, NC);
3146 return &I; // The SHL operand was modified.
3147 }
3148 }
3149 }
3150
3151 // If the operand is an bitwise operator with a constant RHS, and the
3152 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003153 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
3154 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3155 bool isValid = true; // Valid only for And, Or, Xor
3156 bool highBitSet = false; // Transform if high bit of constant set?
3157
3158 switch (Op0BO->getOpcode()) {
3159 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003160 case Instruction::Add:
3161 isValid = isLeftShift;
3162 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003163 case Instruction::Or:
3164 case Instruction::Xor:
3165 highBitSet = false;
3166 break;
3167 case Instruction::And:
3168 highBitSet = true;
3169 break;
3170 }
3171
3172 // If this is a signed shift right, and the high bit is modified
3173 // by the logical operation, do not perform the transformation.
3174 // The highBitSet boolean indicates the value of the high bit of
3175 // the constant which would cause it to be modified for this
3176 // operation.
3177 //
3178 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3179 uint64_t Val = Op0C->getRawValue();
3180 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3181 }
3182
3183 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003184 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003185
3186 Instruction *NewShift =
3187 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3188 Op0BO->getName());
3189 Op0BO->setName("");
3190 InsertNewInstBefore(NewShift, I);
3191
3192 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3193 NewRHS);
3194 }
3195 }
Chris Lattner86102b82005-01-01 16:22:27 +00003196 }
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003197
Chris Lattner3204d4e2003-07-24 17:52:58 +00003198 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003199 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00003200 if (ConstantUInt *ShiftAmt1C =
3201 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003202 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3203 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
Chris Lattner3204d4e2003-07-24 17:52:58 +00003204
3205 // Check for (A << c1) << c2 and (A >> c1) >> c2
3206 if (I.getOpcode() == Op0SI->getOpcode()) {
3207 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003208 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
3209 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00003210 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3211 ConstantUInt::get(Type::UByteTy, Amt));
3212 }
3213
Chris Lattnerab780df2003-07-24 18:38:56 +00003214 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3215 // signed types, we can only support the (A >> c1) << c2 configuration,
3216 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003217 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003218 // Calculate bitmask for what gets shifted off the edge...
3219 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003220 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003221 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003222 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003223 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00003224
3225 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003226 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3227 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00003228 InsertNewInstBefore(Mask, I);
3229
3230 // Figure out what flavor of shift we should use...
3231 if (ShiftAmt1 == ShiftAmt2)
3232 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3233 else if (ShiftAmt1 < ShiftAmt2) {
3234 return new ShiftInst(I.getOpcode(), Mask,
3235 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3236 } else {
3237 return new ShiftInst(Op0SI->getOpcode(), Mask,
3238 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3239 }
3240 }
3241 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003242 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00003243
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003244 return 0;
3245}
3246
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003247enum CastType {
3248 Noop = 0,
3249 Truncate = 1,
3250 Signext = 2,
3251 Zeroext = 3
3252};
3253
3254/// getCastType - In the future, we will split the cast instruction into these
3255/// various types. Until then, we have to do the analysis here.
3256static CastType getCastType(const Type *Src, const Type *Dest) {
3257 assert(Src->isIntegral() && Dest->isIntegral() &&
3258 "Only works on integral types!");
3259 unsigned SrcSize = Src->getPrimitiveSize()*8;
3260 if (Src == Type::BoolTy) SrcSize = 1;
3261 unsigned DestSize = Dest->getPrimitiveSize()*8;
3262 if (Dest == Type::BoolTy) DestSize = 1;
3263
3264 if (SrcSize == DestSize) return Noop;
3265 if (SrcSize > DestSize) return Truncate;
3266 if (Src->isSigned()) return Signext;
3267 return Zeroext;
3268}
3269
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003270
Chris Lattner48a44f72002-05-02 17:06:02 +00003271// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3272// instruction.
3273//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003274static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00003275 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003276
Chris Lattner650b6da2002-08-02 20:00:25 +00003277 // It is legal to eliminate the instruction if casting A->B->A if the sizes
3278 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003279 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003280 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003281 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003282
Chris Lattner4fbad962004-07-21 04:27:24 +00003283 // If we are casting between pointer and integer types, treat pointers as
3284 // integers of the appropriate size for the code below.
3285 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3286 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3287 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003288
Chris Lattner48a44f72002-05-02 17:06:02 +00003289 // Allow free casting and conversion of sizes as long as the sign doesn't
3290 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003291 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003292 CastType FirstCast = getCastType(SrcTy, MidTy);
3293 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003294
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003295 // Capture the effect of these two casts. If the result is a legal cast,
3296 // the CastType is stored here, otherwise a special code is used.
3297 static const unsigned CastResult[] = {
3298 // First cast is noop
3299 0, 1, 2, 3,
3300 // First cast is a truncate
3301 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3302 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003303 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003304 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003305 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003306 };
3307
3308 unsigned Result = CastResult[FirstCast*4+SecondCast];
3309 switch (Result) {
3310 default: assert(0 && "Illegal table value!");
3311 case 0:
3312 case 1:
3313 case 2:
3314 case 3:
3315 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3316 // truncates, we could eliminate more casts.
3317 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3318 case 4:
3319 return false; // Not possible to eliminate this here.
3320 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00003321 // Sign or zero extend followed by truncate is always ok if the result
3322 // is a truncate or noop.
3323 CastType ResultCast = getCastType(SrcTy, DstTy);
3324 if (ResultCast == Noop || ResultCast == Truncate)
3325 return true;
3326 // Otherwise we are still growing the value, we are only safe if the
3327 // result will match the sign/zeroextendness of the result.
3328 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00003329 }
Chris Lattner650b6da2002-08-02 20:00:25 +00003330 }
Chris Lattner48a44f72002-05-02 17:06:02 +00003331 return false;
3332}
3333
Chris Lattner11ffd592004-07-20 05:21:00 +00003334static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003335 if (V->getType() == Ty || isa<Constant>(V)) return false;
3336 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00003337 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3338 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003339 return false;
3340 return true;
3341}
3342
3343/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3344/// InsertBefore instruction. This is specialized a bit to avoid inserting
3345/// casts that are known to not do anything...
3346///
3347Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3348 Instruction *InsertBefore) {
3349 if (V->getType() == DestTy) return V;
3350 if (Constant *C = dyn_cast<Constant>(V))
3351 return ConstantExpr::getCast(C, DestTy);
3352
3353 CastInst *CI = new CastInst(V, DestTy, V->getName());
3354 InsertNewInstBefore(CI, *InsertBefore);
3355 return CI;
3356}
Chris Lattner48a44f72002-05-02 17:06:02 +00003357
3358// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00003359//
Chris Lattner113f4f42002-06-25 16:13:24 +00003360Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00003361 Value *Src = CI.getOperand(0);
3362
Chris Lattner48a44f72002-05-02 17:06:02 +00003363 // If the user is casting a value to the same type, eliminate this cast
3364 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00003365 if (CI.getType() == Src->getType())
3366 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00003367
Chris Lattner81a7a232004-10-16 18:11:37 +00003368 if (isa<UndefValue>(Src)) // cast undef -> undef
3369 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3370
Chris Lattner48a44f72002-05-02 17:06:02 +00003371 // If casting the result of another cast instruction, try to eliminate this
3372 // one!
3373 //
Chris Lattner86102b82005-01-01 16:22:27 +00003374 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3375 Value *A = CSrc->getOperand(0);
3376 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3377 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003378 // This instruction now refers directly to the cast's src operand. This
3379 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00003380 CI.setOperand(0, CSrc->getOperand(0));
3381 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00003382 }
3383
Chris Lattner650b6da2002-08-02 20:00:25 +00003384 // If this is an A->B->A cast, and we are dealing with integral types, try
3385 // to convert this into a logical 'and' instruction.
3386 //
Chris Lattner86102b82005-01-01 16:22:27 +00003387 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003388 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00003389 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
3390 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()&&
3391 A->getType()->getPrimitiveSize() == CI.getType()->getPrimitiveSize()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00003392 assert(CSrc->getType() != Type::ULongTy &&
3393 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00003394 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner86102b82005-01-01 16:22:27 +00003395 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3396 AndValue);
3397 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3398 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3399 if (And->getType() != CI.getType()) {
3400 And->setName(CSrc->getName()+".mask");
3401 InsertNewInstBefore(And, CI);
3402 And = new CastInst(And, CI.getType());
3403 }
3404 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00003405 }
3406 }
Chris Lattner86102b82005-01-01 16:22:27 +00003407
Chris Lattner03841652004-05-25 04:29:21 +00003408 // If this is a cast to bool, turn it into the appropriate setne instruction.
3409 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003410 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00003411 Constant::getNullValue(CI.getOperand(0)->getType()));
3412
Chris Lattnerd0d51602003-06-21 23:12:02 +00003413 // If casting the result of a getelementptr instruction with no offset, turn
3414 // this into a cast of the original pointer!
3415 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00003416 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00003417 bool AllZeroOperands = true;
3418 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3419 if (!isa<Constant>(GEP->getOperand(i)) ||
3420 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3421 AllZeroOperands = false;
3422 break;
3423 }
3424 if (AllZeroOperands) {
3425 CI.setOperand(0, GEP->getOperand(0));
3426 return &CI;
3427 }
3428 }
3429
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003430 // If we are casting a malloc or alloca to a pointer to a type of the same
3431 // size, rewrite the allocation instruction to allocate the "right" type.
3432 //
3433 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00003434 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003435 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
3436 // Get the type really allocated and the type casted to...
3437 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003438 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003439 if (AllocElTy->isSized() && CastElTy->isSized()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003440 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3441 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00003442
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003443 // If the allocation is for an even multiple of the cast type size
3444 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
3445 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003446 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003447 std::string Name = AI->getName(); AI->setName("");
3448 AllocationInst *New;
3449 if (isa<MallocInst>(AI))
3450 New = new MallocInst(CastElTy, Amt, Name);
3451 else
3452 New = new AllocaInst(CastElTy, Amt, Name);
3453 InsertNewInstBefore(New, *AI);
3454 return ReplaceInstUsesWith(CI, New);
3455 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003456 }
3457 }
3458
Chris Lattner86102b82005-01-01 16:22:27 +00003459 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
3460 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
3461 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003462 if (isa<PHINode>(Src))
3463 if (Instruction *NV = FoldOpIntoPhi(CI))
3464 return NV;
3465
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003466 // If the source value is an instruction with only this use, we can attempt to
3467 // propagate the cast into the instruction. Also, only handle integral types
3468 // for now.
3469 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003470 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003471 CI.getType()->isInteger()) { // Don't mess with casts to bool here
3472 const Type *DestTy = CI.getType();
3473 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
3474 unsigned DestBitSize = getTypeSizeInBits(DestTy);
3475
3476 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3477 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3478
3479 switch (SrcI->getOpcode()) {
3480 case Instruction::Add:
3481 case Instruction::Mul:
3482 case Instruction::And:
3483 case Instruction::Or:
3484 case Instruction::Xor:
3485 // If we are discarding information, or just changing the sign, rewrite.
3486 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3487 // Don't insert two casts if they cannot be eliminated. We allow two
3488 // casts to be inserted if the sizes are the same. This could only be
3489 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00003490 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3491 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003492 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3493 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3494 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3495 ->getOpcode(), Op0c, Op1c);
3496 }
3497 }
3498 break;
3499 case Instruction::Shl:
3500 // Allow changing the sign of the source operand. Do not allow changing
3501 // the size of the shift, UNLESS the shift amount is a constant. We
3502 // mush not change variable sized shifts to a smaller size, because it
3503 // is undefined to shift more bits out than exist in the value.
3504 if (DestBitSize == SrcBitSize ||
3505 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3506 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3507 return new ShiftInst(Instruction::Shl, Op0c, Op1);
3508 }
3509 break;
3510 }
3511 }
3512
Chris Lattner260ab202002-04-18 17:39:14 +00003513 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00003514}
3515
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003516/// GetSelectFoldableOperands - We want to turn code that looks like this:
3517/// %C = or %A, %B
3518/// %D = select %cond, %C, %A
3519/// into:
3520/// %C = select %cond, %B, 0
3521/// %D = or %A, %C
3522///
3523/// Assuming that the specified instruction is an operand to the select, return
3524/// a bitmask indicating which operands of this instruction are foldable if they
3525/// equal the other incoming value of the select.
3526///
3527static unsigned GetSelectFoldableOperands(Instruction *I) {
3528 switch (I->getOpcode()) {
3529 case Instruction::Add:
3530 case Instruction::Mul:
3531 case Instruction::And:
3532 case Instruction::Or:
3533 case Instruction::Xor:
3534 return 3; // Can fold through either operand.
3535 case Instruction::Sub: // Can only fold on the amount subtracted.
3536 case Instruction::Shl: // Can only fold on the shift amount.
3537 case Instruction::Shr:
3538 return 1;
3539 default:
3540 return 0; // Cannot fold
3541 }
3542}
3543
3544/// GetSelectFoldableConstant - For the same transformation as the previous
3545/// function, return the identity constant that goes into the select.
3546static Constant *GetSelectFoldableConstant(Instruction *I) {
3547 switch (I->getOpcode()) {
3548 default: assert(0 && "This cannot happen!"); abort();
3549 case Instruction::Add:
3550 case Instruction::Sub:
3551 case Instruction::Or:
3552 case Instruction::Xor:
3553 return Constant::getNullValue(I->getType());
3554 case Instruction::Shl:
3555 case Instruction::Shr:
3556 return Constant::getNullValue(Type::UByteTy);
3557 case Instruction::And:
3558 return ConstantInt::getAllOnesValue(I->getType());
3559 case Instruction::Mul:
3560 return ConstantInt::get(I->getType(), 1);
3561 }
3562}
3563
Chris Lattner411336f2005-01-19 21:50:18 +00003564/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
3565/// have the same opcode and only one use each. Try to simplify this.
3566Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
3567 Instruction *FI) {
3568 if (TI->getNumOperands() == 1) {
3569 // If this is a non-volatile load or a cast from the same type,
3570 // merge.
3571 if (TI->getOpcode() == Instruction::Cast) {
3572 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
3573 return 0;
3574 } else {
3575 return 0; // unknown unary op.
3576 }
3577
3578 // Fold this by inserting a select from the input values.
3579 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
3580 FI->getOperand(0), SI.getName()+".v");
3581 InsertNewInstBefore(NewSI, SI);
3582 return new CastInst(NewSI, TI->getType());
3583 }
3584
3585 // Only handle binary operators here.
3586 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
3587 return 0;
3588
3589 // Figure out if the operations have any operands in common.
3590 Value *MatchOp, *OtherOpT, *OtherOpF;
3591 bool MatchIsOpZero;
3592 if (TI->getOperand(0) == FI->getOperand(0)) {
3593 MatchOp = TI->getOperand(0);
3594 OtherOpT = TI->getOperand(1);
3595 OtherOpF = FI->getOperand(1);
3596 MatchIsOpZero = true;
3597 } else if (TI->getOperand(1) == FI->getOperand(1)) {
3598 MatchOp = TI->getOperand(1);
3599 OtherOpT = TI->getOperand(0);
3600 OtherOpF = FI->getOperand(0);
3601 MatchIsOpZero = false;
3602 } else if (!TI->isCommutative()) {
3603 return 0;
3604 } else if (TI->getOperand(0) == FI->getOperand(1)) {
3605 MatchOp = TI->getOperand(0);
3606 OtherOpT = TI->getOperand(1);
3607 OtherOpF = FI->getOperand(0);
3608 MatchIsOpZero = true;
3609 } else if (TI->getOperand(1) == FI->getOperand(0)) {
3610 MatchOp = TI->getOperand(1);
3611 OtherOpT = TI->getOperand(0);
3612 OtherOpF = FI->getOperand(1);
3613 MatchIsOpZero = true;
3614 } else {
3615 return 0;
3616 }
3617
3618 // If we reach here, they do have operations in common.
3619 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
3620 OtherOpF, SI.getName()+".v");
3621 InsertNewInstBefore(NewSI, SI);
3622
3623 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
3624 if (MatchIsOpZero)
3625 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
3626 else
3627 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
3628 } else {
3629 if (MatchIsOpZero)
3630 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
3631 else
3632 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
3633 }
3634}
3635
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003636Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00003637 Value *CondVal = SI.getCondition();
3638 Value *TrueVal = SI.getTrueValue();
3639 Value *FalseVal = SI.getFalseValue();
3640
3641 // select true, X, Y -> X
3642 // select false, X, Y -> Y
3643 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003644 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00003645 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003646 else {
3647 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00003648 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003649 }
Chris Lattner533bc492004-03-30 19:37:13 +00003650
3651 // select C, X, X -> X
3652 if (TrueVal == FalseVal)
3653 return ReplaceInstUsesWith(SI, TrueVal);
3654
Chris Lattner81a7a232004-10-16 18:11:37 +00003655 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3656 return ReplaceInstUsesWith(SI, FalseVal);
3657 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3658 return ReplaceInstUsesWith(SI, TrueVal);
3659 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3660 if (isa<Constant>(TrueVal))
3661 return ReplaceInstUsesWith(SI, TrueVal);
3662 else
3663 return ReplaceInstUsesWith(SI, FalseVal);
3664 }
3665
Chris Lattner1c631e82004-04-08 04:43:23 +00003666 if (SI.getType() == Type::BoolTy)
3667 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3668 if (C == ConstantBool::True) {
3669 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003670 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003671 } else {
3672 // Change: A = select B, false, C --> A = and !B, C
3673 Value *NotCond =
3674 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3675 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003676 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003677 }
3678 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3679 if (C == ConstantBool::False) {
3680 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003681 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003682 } else {
3683 // Change: A = select B, C, true --> A = or !B, C
3684 Value *NotCond =
3685 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3686 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003687 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003688 }
3689 }
3690
Chris Lattner183b3362004-04-09 19:05:30 +00003691 // Selecting between two integer constants?
3692 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3693 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3694 // select C, 1, 0 -> cast C to int
3695 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3696 return new CastInst(CondVal, SI.getType());
3697 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3698 // select C, 0, 1 -> cast !C to int
3699 Value *NotCond =
3700 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00003701 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00003702 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00003703 }
Chris Lattner35167c32004-06-09 07:59:58 +00003704
3705 // If one of the constants is zero (we know they can't both be) and we
3706 // have a setcc instruction with zero, and we have an 'and' with the
3707 // non-constant value, eliminate this whole mess. This corresponds to
3708 // cases like this: ((X & 27) ? 27 : 0)
3709 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3710 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3711 if ((IC->getOpcode() == Instruction::SetEQ ||
3712 IC->getOpcode() == Instruction::SetNE) &&
3713 isa<ConstantInt>(IC->getOperand(1)) &&
3714 cast<Constant>(IC->getOperand(1))->isNullValue())
3715 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3716 if (ICA->getOpcode() == Instruction::And &&
3717 isa<ConstantInt>(ICA->getOperand(1)) &&
3718 (ICA->getOperand(1) == TrueValC ||
3719 ICA->getOperand(1) == FalseValC) &&
3720 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3721 // Okay, now we know that everything is set up, we just don't
3722 // know whether we have a setne or seteq and whether the true or
3723 // false val is the zero.
3724 bool ShouldNotVal = !TrueValC->isNullValue();
3725 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3726 Value *V = ICA;
3727 if (ShouldNotVal)
3728 V = InsertNewInstBefore(BinaryOperator::create(
3729 Instruction::Xor, V, ICA->getOperand(1)), SI);
3730 return ReplaceInstUsesWith(SI, V);
3731 }
Chris Lattner533bc492004-03-30 19:37:13 +00003732 }
Chris Lattner623fba12004-04-10 22:21:27 +00003733
3734 // See if we are selecting two values based on a comparison of the two values.
3735 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3736 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3737 // Transform (X == Y) ? X : Y -> Y
3738 if (SCI->getOpcode() == Instruction::SetEQ)
3739 return ReplaceInstUsesWith(SI, FalseVal);
3740 // Transform (X != Y) ? X : Y -> X
3741 if (SCI->getOpcode() == Instruction::SetNE)
3742 return ReplaceInstUsesWith(SI, TrueVal);
3743 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3744
3745 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3746 // Transform (X == Y) ? Y : X -> X
3747 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003748 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003749 // Transform (X != Y) ? Y : X -> Y
3750 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003751 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003752 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3753 }
3754 }
Chris Lattner1c631e82004-04-08 04:43:23 +00003755
Chris Lattnera04c9042005-01-13 22:52:24 +00003756 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
3757 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
3758 if (TI->hasOneUse() && FI->hasOneUse()) {
3759 bool isInverse = false;
3760 Instruction *AddOp = 0, *SubOp = 0;
3761
Chris Lattner411336f2005-01-19 21:50:18 +00003762 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
3763 if (TI->getOpcode() == FI->getOpcode())
3764 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
3765 return IV;
3766
3767 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
3768 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00003769 if (TI->getOpcode() == Instruction::Sub &&
3770 FI->getOpcode() == Instruction::Add) {
3771 AddOp = FI; SubOp = TI;
3772 } else if (FI->getOpcode() == Instruction::Sub &&
3773 TI->getOpcode() == Instruction::Add) {
3774 AddOp = TI; SubOp = FI;
3775 }
3776
3777 if (AddOp) {
3778 Value *OtherAddOp = 0;
3779 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
3780 OtherAddOp = AddOp->getOperand(1);
3781 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
3782 OtherAddOp = AddOp->getOperand(0);
3783 }
3784
3785 if (OtherAddOp) {
3786 // So at this point we know we have:
3787 // select C, (add X, Y), (sub X, ?)
3788 // We can do the transform profitably if either 'Y' = '?' or '?' is
3789 // a constant.
3790 if (SubOp->getOperand(1) == AddOp ||
3791 isa<Constant>(SubOp->getOperand(1))) {
3792 Value *NegVal;
3793 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
3794 NegVal = ConstantExpr::getNeg(C);
3795 } else {
3796 NegVal = InsertNewInstBefore(
3797 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
3798 }
3799
Chris Lattner51726c42005-01-14 17:35:12 +00003800 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00003801 Value *NewFalseOp = NegVal;
3802 if (AddOp != TI)
3803 std::swap(NewTrueOp, NewFalseOp);
3804 Instruction *NewSel =
3805 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
3806
3807 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00003808 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00003809 }
3810 }
3811 }
3812 }
3813
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003814 // See if we can fold the select into one of our operands.
3815 if (SI.getType()->isInteger()) {
3816 // See the comment above GetSelectFoldableOperands for a description of the
3817 // transformation we are doing here.
3818 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3819 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3820 !isa<Constant>(FalseVal))
3821 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3822 unsigned OpToFold = 0;
3823 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3824 OpToFold = 1;
3825 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3826 OpToFold = 2;
3827 }
3828
3829 if (OpToFold) {
3830 Constant *C = GetSelectFoldableConstant(TVI);
3831 std::string Name = TVI->getName(); TVI->setName("");
3832 Instruction *NewSel =
3833 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3834 Name);
3835 InsertNewInstBefore(NewSel, SI);
3836 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3837 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3838 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3839 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3840 else {
3841 assert(0 && "Unknown instruction!!");
3842 }
3843 }
3844 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003845
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003846 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3847 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3848 !isa<Constant>(TrueVal))
3849 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3850 unsigned OpToFold = 0;
3851 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3852 OpToFold = 1;
3853 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3854 OpToFold = 2;
3855 }
3856
3857 if (OpToFold) {
3858 Constant *C = GetSelectFoldableConstant(FVI);
3859 std::string Name = FVI->getName(); FVI->setName("");
3860 Instruction *NewSel =
3861 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3862 Name);
3863 InsertNewInstBefore(NewSel, SI);
3864 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3865 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3866 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3867 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3868 else {
3869 assert(0 && "Unknown instruction!!");
3870 }
3871 }
3872 }
3873 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003874 return 0;
3875}
3876
3877
Chris Lattner970c33a2003-06-19 17:00:31 +00003878// CallInst simplification
3879//
3880Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003881 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3882 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00003883 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3884 bool Changed = false;
3885
3886 // memmove/cpy/set of zero bytes is a noop.
3887 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3888 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3889
3890 // FIXME: Increase alignment here.
3891
3892 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3893 if (CI->getRawValue() == 1) {
3894 // Replace the instruction with just byte operations. We would
3895 // transform other cases to loads/stores, but we don't know if
3896 // alignment is sufficient.
3897 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003898 }
3899
Chris Lattner00648e12004-10-12 04:52:52 +00003900 // If we have a memmove and the source operation is a constant global,
3901 // then the source and dest pointers can't alias, so we can change this
3902 // into a call to memcpy.
3903 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3904 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3905 if (GVSrc->isConstant()) {
3906 Module *M = CI.getParent()->getParent()->getParent();
3907 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3908 CI.getCalledFunction()->getFunctionType());
3909 CI.setOperand(0, MemCpy);
3910 Changed = true;
3911 }
3912
3913 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00003914 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
3915 // If this stoppoint is at the same source location as the previous
3916 // stoppoint in the chain, it is not needed.
3917 if (DbgStopPointInst *PrevSPI =
3918 dyn_cast<DbgStopPointInst>(SPI->getChain()))
3919 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
3920 SPI->getColNo() == PrevSPI->getColNo()) {
3921 SPI->replaceAllUsesWith(PrevSPI);
3922 return EraseInstFromFunction(CI);
3923 }
Chris Lattner00648e12004-10-12 04:52:52 +00003924 }
3925
Chris Lattneraec3d942003-10-07 22:32:43 +00003926 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003927}
3928
3929// InvokeInst simplification
3930//
3931Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003932 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003933}
3934
Chris Lattneraec3d942003-10-07 22:32:43 +00003935// visitCallSite - Improvements for call and invoke instructions.
3936//
3937Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003938 bool Changed = false;
3939
3940 // If the callee is a constexpr cast of a function, attempt to move the cast
3941 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003942 if (transformConstExprCastCall(CS)) return 0;
3943
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003944 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00003945
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003946 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3947 // This instruction is not reachable, just remove it. We insert a store to
3948 // undef so that we know that this code is not reachable, despite the fact
3949 // that we can't modify the CFG here.
3950 new StoreInst(ConstantBool::True,
3951 UndefValue::get(PointerType::get(Type::BoolTy)),
3952 CS.getInstruction());
3953
3954 if (!CS.getInstruction()->use_empty())
3955 CS.getInstruction()->
3956 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3957
3958 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3959 // Don't break the CFG, insert a dummy cond branch.
3960 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3961 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00003962 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003963 return EraseInstFromFunction(*CS.getInstruction());
3964 }
Chris Lattner81a7a232004-10-16 18:11:37 +00003965
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003966 const PointerType *PTy = cast<PointerType>(Callee->getType());
3967 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3968 if (FTy->isVarArg()) {
3969 // See if we can optimize any arguments passed through the varargs area of
3970 // the call.
3971 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3972 E = CS.arg_end(); I != E; ++I)
3973 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3974 // If this cast does not effect the value passed through the varargs
3975 // area, we can eliminate the use of the cast.
3976 Value *Op = CI->getOperand(0);
3977 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3978 *I = Op;
3979 Changed = true;
3980 }
3981 }
3982 }
Chris Lattneraec3d942003-10-07 22:32:43 +00003983
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003984 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00003985}
3986
Chris Lattner970c33a2003-06-19 17:00:31 +00003987// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3988// attempt to move the cast to the arguments of the call/invoke.
3989//
3990bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3991 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3992 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00003993 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00003994 return false;
Reid Spencer87436872004-07-18 00:38:32 +00003995 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00003996 Instruction *Caller = CS.getInstruction();
3997
3998 // Okay, this is a cast from a function to a different type. Unless doing so
3999 // would cause a type conversion of one of our arguments, change this call to
4000 // be a direct call with arguments casted to the appropriate types.
4001 //
4002 const FunctionType *FT = Callee->getFunctionType();
4003 const Type *OldRetTy = Caller->getType();
4004
Chris Lattner1f7942f2004-01-14 06:06:08 +00004005 // Check to see if we are changing the return type...
4006 if (OldRetTy != FT->getReturnType()) {
4007 if (Callee->isExternal() &&
4008 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4009 !Caller->use_empty())
4010 return false; // Cannot transform this return value...
4011
4012 // If the callsite is an invoke instruction, and the return value is used by
4013 // a PHI node in a successor, we cannot change the return type of the call
4014 // because there is no place to put the cast instruction (without breaking
4015 // the critical edge). Bail out in this case.
4016 if (!Caller->use_empty())
4017 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4018 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4019 UI != E; ++UI)
4020 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4021 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004022 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00004023 return false;
4024 }
Chris Lattner970c33a2003-06-19 17:00:31 +00004025
4026 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4027 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4028
4029 CallSite::arg_iterator AI = CS.arg_begin();
4030 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4031 const Type *ParamTy = FT->getParamType(i);
4032 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
4033 if (Callee->isExternal() && !isConvertible) return false;
4034 }
4035
4036 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4037 Callee->isExternal())
4038 return false; // Do not delete arguments unless we have a function body...
4039
4040 // Okay, we decided that this is a safe thing to do: go ahead and start
4041 // inserting cast instructions as necessary...
4042 std::vector<Value*> Args;
4043 Args.reserve(NumActualArgs);
4044
4045 AI = CS.arg_begin();
4046 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4047 const Type *ParamTy = FT->getParamType(i);
4048 if ((*AI)->getType() == ParamTy) {
4049 Args.push_back(*AI);
4050 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00004051 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4052 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00004053 }
4054 }
4055
4056 // If the function takes more arguments than the call was taking, add them
4057 // now...
4058 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4059 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4060
4061 // If we are removing arguments to the function, emit an obnoxious warning...
4062 if (FT->getNumParams() < NumActualArgs)
4063 if (!FT->isVarArg()) {
4064 std::cerr << "WARNING: While resolving call to function '"
4065 << Callee->getName() << "' arguments were dropped!\n";
4066 } else {
4067 // Add all of the arguments in their promoted form to the arg list...
4068 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4069 const Type *PTy = getPromotedType((*AI)->getType());
4070 if (PTy != (*AI)->getType()) {
4071 // Must promote to pass through va_arg area!
4072 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4073 InsertNewInstBefore(Cast, *Caller);
4074 Args.push_back(Cast);
4075 } else {
4076 Args.push_back(*AI);
4077 }
4078 }
4079 }
4080
4081 if (FT->getReturnType() == Type::VoidTy)
4082 Caller->setName(""); // Void type should not have a name...
4083
4084 Instruction *NC;
4085 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004086 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00004087 Args, Caller->getName(), Caller);
4088 } else {
4089 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
4090 }
4091
4092 // Insert a cast of the return type as necessary...
4093 Value *NV = NC;
4094 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4095 if (NV->getType() != Type::VoidTy) {
4096 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00004097
4098 // If this is an invoke instruction, we should insert it after the first
4099 // non-phi, instruction in the normal successor block.
4100 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4101 BasicBlock::iterator I = II->getNormalDest()->begin();
4102 while (isa<PHINode>(I)) ++I;
4103 InsertNewInstBefore(NC, *I);
4104 } else {
4105 // Otherwise, it's a call, just insert cast right after the call instr
4106 InsertNewInstBefore(NC, *Caller);
4107 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004108 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00004109 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00004110 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00004111 }
4112 }
4113
4114 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4115 Caller->replaceAllUsesWith(NV);
4116 Caller->getParent()->getInstList().erase(Caller);
4117 removeFromWorkList(Caller);
4118 return true;
4119}
4120
4121
Chris Lattner7515cab2004-11-14 19:13:23 +00004122// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4123// operator and they all are only used by the PHI, PHI together their
4124// inputs, and do the operation once, to the result of the PHI.
4125Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4126 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4127
4128 // Scan the instruction, looking for input operations that can be folded away.
4129 // If all input operands to the phi are the same instruction (e.g. a cast from
4130 // the same type or "+42") we can pull the operation through the PHI, reducing
4131 // code size and simplifying code.
4132 Constant *ConstantOp = 0;
4133 const Type *CastSrcTy = 0;
4134 if (isa<CastInst>(FirstInst)) {
4135 CastSrcTy = FirstInst->getOperand(0)->getType();
4136 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4137 // Can fold binop or shift if the RHS is a constant.
4138 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4139 if (ConstantOp == 0) return 0;
4140 } else {
4141 return 0; // Cannot fold this operation.
4142 }
4143
4144 // Check to see if all arguments are the same operation.
4145 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4146 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4147 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4148 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4149 return 0;
4150 if (CastSrcTy) {
4151 if (I->getOperand(0)->getType() != CastSrcTy)
4152 return 0; // Cast operation must match.
4153 } else if (I->getOperand(1) != ConstantOp) {
4154 return 0;
4155 }
4156 }
4157
4158 // Okay, they are all the same operation. Create a new PHI node of the
4159 // correct type, and PHI together all of the LHS's of the instructions.
4160 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4161 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00004162 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00004163
4164 Value *InVal = FirstInst->getOperand(0);
4165 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00004166
4167 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00004168 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4169 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4170 if (NewInVal != InVal)
4171 InVal = 0;
4172 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4173 }
4174
4175 Value *PhiVal;
4176 if (InVal) {
4177 // The new PHI unions all of the same values together. This is really
4178 // common, so we handle it intelligently here for compile-time speed.
4179 PhiVal = InVal;
4180 delete NewPN;
4181 } else {
4182 InsertNewInstBefore(NewPN, PN);
4183 PhiVal = NewPN;
4184 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004185
4186 // Insert and return the new operation.
4187 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004188 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00004189 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004190 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004191 else
4192 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00004193 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004194}
Chris Lattner48a44f72002-05-02 17:06:02 +00004195
Chris Lattner71536432005-01-17 05:10:15 +00004196/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4197/// that is dead.
4198static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4199 if (PN->use_empty()) return true;
4200 if (!PN->hasOneUse()) return false;
4201
4202 // Remember this node, and if we find the cycle, return.
4203 if (!PotentiallyDeadPHIs.insert(PN).second)
4204 return true;
4205
4206 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4207 return DeadPHICycle(PU, PotentiallyDeadPHIs);
4208
4209 return false;
4210}
4211
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004212// PHINode simplification
4213//
Chris Lattner113f4f42002-06-25 16:13:24 +00004214Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnere29d6342004-10-17 21:22:38 +00004215 if (Value *V = hasConstantValue(&PN)) {
4216 // If V is an instruction, we have to be certain that it dominates PN.
4217 // However, because we don't have dom info, we can't do a perfect job.
4218 if (Instruction *I = dyn_cast<Instruction>(V)) {
4219 // We know that the instruction dominates the PHI if there are no undef
4220 // values coming in.
Chris Lattner3b92f172004-10-18 01:48:31 +00004221 if (I->getParent() != &I->getParent()->getParent()->front() ||
4222 isa<InvokeInst>(I))
Chris Lattner107c15c2004-10-17 21:31:34 +00004223 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4224 if (isa<UndefValue>(PN.getIncomingValue(i))) {
4225 V = 0;
4226 break;
4227 }
Chris Lattnere29d6342004-10-17 21:22:38 +00004228 }
4229
4230 if (V)
4231 return ReplaceInstUsesWith(PN, V);
4232 }
Chris Lattner4db2d222004-02-16 05:07:08 +00004233
4234 // If the only user of this instruction is a cast instruction, and all of the
4235 // incoming values are constants, change this PHI to merge together the casted
4236 // constants.
4237 if (PN.hasOneUse())
4238 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4239 if (CI->getType() != PN.getType()) { // noop casts will be folded
4240 bool AllConstant = true;
4241 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4242 if (!isa<Constant>(PN.getIncomingValue(i))) {
4243 AllConstant = false;
4244 break;
4245 }
4246 if (AllConstant) {
4247 // Make a new PHI with all casted values.
4248 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4249 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4250 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4251 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4252 PN.getIncomingBlock(i));
4253 }
4254
4255 // Update the cast instruction.
4256 CI->setOperand(0, New);
4257 WorkList.push_back(CI); // revisit the cast instruction to fold.
4258 WorkList.push_back(New); // Make sure to revisit the new Phi
4259 return &PN; // PN is now dead!
4260 }
4261 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004262
4263 // If all PHI operands are the same operation, pull them through the PHI,
4264 // reducing code size.
4265 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4266 PN.getIncomingValue(0)->hasOneUse())
4267 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4268 return Result;
4269
Chris Lattner71536432005-01-17 05:10:15 +00004270 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4271 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4272 // PHI)... break the cycle.
4273 if (PN.hasOneUse())
4274 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4275 std::set<PHINode*> PotentiallyDeadPHIs;
4276 PotentiallyDeadPHIs.insert(&PN);
4277 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4278 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4279 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004280
Chris Lattner91daeb52003-12-19 05:58:40 +00004281 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004282}
4283
Chris Lattner69193f92004-04-05 01:30:19 +00004284static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4285 Instruction *InsertPoint,
4286 InstCombiner *IC) {
4287 unsigned PS = IC->getTargetData().getPointerSize();
4288 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00004289 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4290 // We must insert a cast to ensure we sign-extend.
4291 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4292 V->getName()), *InsertPoint);
4293 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4294 *InsertPoint);
4295}
4296
Chris Lattner48a44f72002-05-02 17:06:02 +00004297
Chris Lattner113f4f42002-06-25 16:13:24 +00004298Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004299 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00004300 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00004301 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004302 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00004303 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004304
Chris Lattner81a7a232004-10-16 18:11:37 +00004305 if (isa<UndefValue>(GEP.getOperand(0)))
4306 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4307
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004308 bool HasZeroPointerIndex = false;
4309 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4310 HasZeroPointerIndex = C->isNullValue();
4311
4312 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00004313 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00004314
Chris Lattner69193f92004-04-05 01:30:19 +00004315 // Eliminate unneeded casts for indices.
4316 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00004317 gep_type_iterator GTI = gep_type_begin(GEP);
4318 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4319 if (isa<SequentialType>(*GTI)) {
4320 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4321 Value *Src = CI->getOperand(0);
4322 const Type *SrcTy = Src->getType();
4323 const Type *DestTy = CI->getType();
4324 if (Src->getType()->isInteger()) {
4325 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
4326 // We can always eliminate a cast from ulong or long to the other.
4327 // We can always eliminate a cast from uint to int or the other on
4328 // 32-bit pointer platforms.
4329 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
4330 MadeChange = true;
4331 GEP.setOperand(i, Src);
4332 }
4333 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4334 SrcTy->getPrimitiveSize() == 4) {
4335 // We can always eliminate a cast from int to [u]long. We can
4336 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4337 // pointer target.
4338 if (SrcTy->isSigned() ||
4339 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
4340 MadeChange = true;
4341 GEP.setOperand(i, Src);
4342 }
Chris Lattner69193f92004-04-05 01:30:19 +00004343 }
4344 }
4345 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00004346 // If we are using a wider index than needed for this platform, shrink it
4347 // to what we need. If the incoming value needs a cast instruction,
4348 // insert it. This explicit cast can make subsequent optimizations more
4349 // obvious.
4350 Value *Op = GEP.getOperand(i);
4351 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004352 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00004353 GEP.setOperand(i, ConstantExpr::getCast(C,
4354 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004355 MadeChange = true;
4356 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004357 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4358 Op->getName()), GEP);
4359 GEP.setOperand(i, Op);
4360 MadeChange = true;
4361 }
Chris Lattner44d0b952004-07-20 01:48:15 +00004362
4363 // If this is a constant idx, make sure to canonicalize it to be a signed
4364 // operand, otherwise CSE and other optimizations are pessimized.
4365 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
4366 GEP.setOperand(i, ConstantExpr::getCast(CUI,
4367 CUI->getType()->getSignedVersion()));
4368 MadeChange = true;
4369 }
Chris Lattner69193f92004-04-05 01:30:19 +00004370 }
4371 if (MadeChange) return &GEP;
4372
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004373 // Combine Indices - If the source pointer to this getelementptr instruction
4374 // is a getelementptr instruction, combine the indices of the two
4375 // getelementptr instructions into a single instruction.
4376 //
Chris Lattner57c67b02004-03-25 22:59:29 +00004377 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00004378 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00004379 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00004380
4381 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004382 // Note that if our source is a gep chain itself that we wait for that
4383 // chain to be resolved before we perform this transformation. This
4384 // avoids us creating a TON of code in some cases.
4385 //
4386 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
4387 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
4388 return 0; // Wait until our source is folded to completion.
4389
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004390 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00004391
4392 // Find out whether the last index in the source GEP is a sequential idx.
4393 bool EndsWithSequential = false;
4394 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
4395 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00004396 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00004397
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004398 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00004399 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00004400 // Replace: gep (gep %P, long B), long A, ...
4401 // With: T = long A+B; gep %P, T, ...
4402 //
Chris Lattner5f667a62004-05-07 22:09:22 +00004403 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00004404 if (SO1 == Constant::getNullValue(SO1->getType())) {
4405 Sum = GO1;
4406 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
4407 Sum = SO1;
4408 } else {
4409 // If they aren't the same type, convert both to an integer of the
4410 // target's pointer size.
4411 if (SO1->getType() != GO1->getType()) {
4412 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
4413 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
4414 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
4415 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
4416 } else {
4417 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00004418 if (SO1->getType()->getPrimitiveSize() == PS) {
4419 // Convert GO1 to SO1's type.
4420 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
4421
4422 } else if (GO1->getType()->getPrimitiveSize() == PS) {
4423 // Convert SO1 to GO1's type.
4424 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
4425 } else {
4426 const Type *PT = TD->getIntPtrType();
4427 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
4428 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
4429 }
4430 }
4431 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004432 if (isa<Constant>(SO1) && isa<Constant>(GO1))
4433 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
4434 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004435 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
4436 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00004437 }
Chris Lattner69193f92004-04-05 01:30:19 +00004438 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004439
4440 // Recycle the GEP we already have if possible.
4441 if (SrcGEPOperands.size() == 2) {
4442 GEP.setOperand(0, SrcGEPOperands[0]);
4443 GEP.setOperand(1, Sum);
4444 return &GEP;
4445 } else {
4446 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4447 SrcGEPOperands.end()-1);
4448 Indices.push_back(Sum);
4449 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
4450 }
Chris Lattner69193f92004-04-05 01:30:19 +00004451 } else if (isa<Constant>(*GEP.idx_begin()) &&
4452 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00004453 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004454 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00004455 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4456 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004457 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
4458 }
4459
4460 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00004461 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004462
Chris Lattner5f667a62004-05-07 22:09:22 +00004463 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004464 // GEP of global variable. If all of the indices for this GEP are
4465 // constants, we can promote this to a constexpr instead of an instruction.
4466
4467 // Scan for nonconstants...
4468 std::vector<Constant*> Indices;
4469 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
4470 for (; I != E && isa<Constant>(*I); ++I)
4471 Indices.push_back(cast<Constant>(*I));
4472
4473 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00004474 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004475
4476 // Replace all uses of the GEP with the new constexpr...
4477 return ReplaceInstUsesWith(GEP, CE);
4478 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004479 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004480 if (CE->getOpcode() == Instruction::Cast) {
4481 if (HasZeroPointerIndex) {
4482 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
4483 // into : GEP [10 x ubyte]* X, long 0, ...
4484 //
4485 // This occurs when the program declares an array extern like "int X[];"
4486 //
4487 Constant *X = CE->getOperand(0);
4488 const PointerType *CPTy = cast<PointerType>(CE->getType());
4489 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
4490 if (const ArrayType *XATy =
4491 dyn_cast<ArrayType>(XTy->getElementType()))
4492 if (const ArrayType *CATy =
4493 dyn_cast<ArrayType>(CPTy->getElementType()))
4494 if (CATy->getElementType() == XATy->getElementType()) {
4495 // At this point, we know that the cast source type is a pointer
4496 // to an array of the same type as the destination pointer
4497 // array. Because the array type is never stepped over (there
4498 // is a leading zero) we can fold the cast into this GEP.
4499 GEP.setOperand(0, X);
4500 return &GEP;
4501 }
Chris Lattner0798af32005-01-13 20:14:25 +00004502 } else if (GEP.getNumOperands() == 2 &&
4503 isa<PointerType>(CE->getOperand(0)->getType())) {
Chris Lattner14f3cdc2004-11-27 17:55:46 +00004504 // Transform things like:
4505 // %t = getelementptr ubyte* cast ([2 x sbyte]* %str to ubyte*), uint %V
4506 // into: %t1 = getelementptr [2 x sbyte*]* %str, int 0, uint %V; cast
4507 Constant *X = CE->getOperand(0);
4508 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4509 const Type *ResElTy =cast<PointerType>(CE->getType())->getElementType();
4510 if (isa<ArrayType>(SrcElTy) &&
4511 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
4512 TD->getTypeSize(ResElTy)) {
4513 Value *V = InsertNewInstBefore(
4514 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
4515 GEP.getOperand(1), GEP.getName()), GEP);
4516 return new CastInst(V, GEP.getType());
4517 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004518 }
4519 }
Chris Lattnerca081252001-12-14 16:52:21 +00004520 }
4521
Chris Lattnerca081252001-12-14 16:52:21 +00004522 return 0;
4523}
4524
Chris Lattner1085bdf2002-11-04 16:18:53 +00004525Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
4526 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
4527 if (AI.isArrayAllocation()) // Check C != 1
4528 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
4529 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004530 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00004531
4532 // Create and insert the replacement instruction...
4533 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00004534 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004535 else {
4536 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00004537 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004538 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004539
4540 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00004541
4542 // Scan to the end of the allocation instructions, to skip over a block of
4543 // allocas if possible...
4544 //
4545 BasicBlock::iterator It = New;
4546 while (isa<AllocationInst>(*It)) ++It;
4547
4548 // Now that I is pointing to the first non-allocation-inst in the block,
4549 // insert our getelementptr instruction...
4550 //
Chris Lattner69193f92004-04-05 01:30:19 +00004551 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00004552 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
4553
4554 // Now make everything use the getelementptr instead of the original
4555 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00004556 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00004557 } else if (isa<UndefValue>(AI.getArraySize())) {
4558 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00004559 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004560
4561 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
4562 // Note that we only do this for alloca's, because malloc should allocate and
4563 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00004564 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
4565 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00004566 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
4567
Chris Lattner1085bdf2002-11-04 16:18:53 +00004568 return 0;
4569}
4570
Chris Lattner8427bff2003-12-07 01:24:23 +00004571Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
4572 Value *Op = FI.getOperand(0);
4573
4574 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
4575 if (CastInst *CI = dyn_cast<CastInst>(Op))
4576 if (isa<PointerType>(CI->getOperand(0)->getType())) {
4577 FI.setOperand(0, CI->getOperand(0));
4578 return &FI;
4579 }
4580
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004581 // free undef -> unreachable.
4582 if (isa<UndefValue>(Op)) {
4583 // Insert a new store to null because we cannot modify the CFG here.
4584 new StoreInst(ConstantBool::True,
4585 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
4586 return EraseInstFromFunction(FI);
4587 }
4588
Chris Lattnerf3a36602004-02-28 04:57:37 +00004589 // If we have 'free null' delete the instruction. This can happen in stl code
4590 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004591 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00004592 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00004593
Chris Lattner8427bff2003-12-07 01:24:23 +00004594 return 0;
4595}
4596
4597
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004598/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
4599/// constantexpr, return the constant value being addressed by the constant
4600/// expression, or null if something is funny.
4601///
4602static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00004603 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004604 return 0; // Do not allow stepping over the value!
4605
4606 // Loop over all of the operands, tracking down which value we are
4607 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00004608 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
4609 for (++I; I != E; ++I)
4610 if (const StructType *STy = dyn_cast<StructType>(*I)) {
4611 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
4612 assert(CU->getValue() < STy->getNumElements() &&
4613 "Struct index out of range!");
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004614 unsigned El = (unsigned)CU->getValue();
Chris Lattnered79d8a2004-05-27 17:30:27 +00004615 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004616 C = CS->getOperand(El);
Chris Lattnered79d8a2004-05-27 17:30:27 +00004617 } else if (isa<ConstantAggregateZero>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004618 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattner81a7a232004-10-16 18:11:37 +00004619 } else if (isa<UndefValue>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004620 C = UndefValue::get(STy->getElementType(El));
Chris Lattnered79d8a2004-05-27 17:30:27 +00004621 } else {
4622 return 0;
4623 }
4624 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
4625 const ArrayType *ATy = cast<ArrayType>(*I);
4626 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
4627 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004628 C = CA->getOperand((unsigned)CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004629 else if (isa<ConstantAggregateZero>(C))
4630 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00004631 else if (isa<UndefValue>(C))
4632 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004633 else
4634 return 0;
4635 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004636 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00004637 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004638 return C;
4639}
4640
Chris Lattner72684fe2005-01-31 05:51:45 +00004641/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00004642static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
4643 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004644 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00004645
4646 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004647 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00004648 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004649
4650 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
4651 // If the source is an array, the code below will not succeed. Check to
4652 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
4653 // constants.
4654 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
4655 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
4656 if (ASrcTy->getNumElements() != 0) {
4657 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
4658 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
4659 SrcTy = cast<PointerType>(CastOp->getType());
4660 SrcPTy = SrcTy->getElementType();
4661 }
4662
4663 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00004664 // Do not allow turning this into a load of an integer, which is then
4665 // casted to a pointer, this pessimizes pointer analysis a lot.
4666 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004667 IC.getTargetData().getTypeSize(SrcPTy) ==
4668 IC.getTargetData().getTypeSize(DestPTy)) {
4669
4670 // Okay, we are casting from one integer or pointer type to another of
4671 // the same size. Instead of casting the pointer before the load, cast
4672 // the result of the loaded value.
4673 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
4674 CI->getName(),
4675 LI.isVolatile()),LI);
4676 // Now cast the result of the load.
4677 return new CastInst(NewLoad, LI.getType());
4678 }
Chris Lattner35e24772004-07-13 01:49:43 +00004679 }
4680 }
4681 return 0;
4682}
4683
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004684/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00004685/// from this value cannot trap. If it is not obviously safe to load from the
4686/// specified pointer, we do a quick local scan of the basic block containing
4687/// ScanFrom, to determine if the address is already accessed.
4688static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
4689 // If it is an alloca or global variable, it is always safe to load from.
4690 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
4691
4692 // Otherwise, be a little bit agressive by scanning the local block where we
4693 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004694 // from/to. If so, the previous load or store would have already trapped,
4695 // so there is no harm doing an extra load (also, CSE will later eliminate
4696 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00004697 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
4698
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004699 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00004700 --BBI;
4701
4702 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
4703 if (LI->getOperand(0) == V) return true;
4704 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
4705 if (SI->getOperand(1) == V) return true;
4706
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004707 }
Chris Lattnere6f13092004-09-19 19:18:10 +00004708 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004709}
4710
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004711Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
4712 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00004713
Chris Lattner81a7a232004-10-16 18:11:37 +00004714 if (Constant *C = dyn_cast<Constant>(Op)) {
4715 if ((C->isNullValue() || isa<UndefValue>(C)) &&
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004716 !LI.isVolatile()) { // load null/undef -> undef
4717 // Insert a new store to null instruction before the load to indicate that
4718 // this code is not reachable. We do this instead of inserting an
4719 // unreachable instruction directly because we cannot modify the CFG.
4720 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00004721 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004722 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004723
Chris Lattner81a7a232004-10-16 18:11:37 +00004724 // Instcombine load (constant global) into the value loaded.
4725 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
4726 if (GV->isConstant() && !GV->isExternal())
4727 return ReplaceInstUsesWith(LI, GV->getInitializer());
4728
4729 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
4730 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
4731 if (CE->getOpcode() == Instruction::GetElementPtr) {
4732 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
4733 if (GV->isConstant() && !GV->isExternal())
4734 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
4735 return ReplaceInstUsesWith(LI, V);
4736 } else if (CE->getOpcode() == Instruction::Cast) {
4737 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4738 return Res;
4739 }
4740 }
Chris Lattnere228ee52004-04-08 20:39:49 +00004741
4742 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00004743 if (CastInst *CI = dyn_cast<CastInst>(Op))
4744 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4745 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00004746
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004747 if (!LI.isVolatile() && Op->hasOneUse()) {
4748 // Change select and PHI nodes to select values instead of addresses: this
4749 // helps alias analysis out a lot, allows many others simplifications, and
4750 // exposes redundancy in the code.
4751 //
4752 // Note that we cannot do the transformation unless we know that the
4753 // introduced loads cannot trap! Something like this is valid as long as
4754 // the condition is always false: load (select bool %C, int* null, int* %G),
4755 // but it would not be valid if we transformed it to load from null
4756 // unconditionally.
4757 //
4758 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
4759 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00004760 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
4761 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004762 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00004763 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004764 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00004765 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004766 return new SelectInst(SI->getCondition(), V1, V2);
4767 }
4768
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00004769 // load (select (cond, null, P)) -> load P
4770 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
4771 if (C->isNullValue()) {
4772 LI.setOperand(0, SI->getOperand(2));
4773 return &LI;
4774 }
4775
4776 // load (select (cond, P, null)) -> load P
4777 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
4778 if (C->isNullValue()) {
4779 LI.setOperand(0, SI->getOperand(1));
4780 return &LI;
4781 }
4782
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004783 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
4784 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00004785 bool Safe = PN->getParent() == LI.getParent();
4786
4787 // Scan all of the instructions between the PHI and the load to make
4788 // sure there are no instructions that might possibly alter the value
4789 // loaded from the PHI.
4790 if (Safe) {
4791 BasicBlock::iterator I = &LI;
4792 for (--I; !isa<PHINode>(I); --I)
4793 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
4794 Safe = false;
4795 break;
4796 }
4797 }
4798
4799 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00004800 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00004801 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004802 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00004803
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004804 if (Safe) {
4805 // Create the PHI.
4806 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
4807 InsertNewInstBefore(NewPN, *PN);
4808 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
4809
4810 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4811 BasicBlock *BB = PN->getIncomingBlock(i);
4812 Value *&TheLoad = LoadMap[BB];
4813 if (TheLoad == 0) {
4814 Value *InVal = PN->getIncomingValue(i);
4815 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
4816 InVal->getName()+".val"),
4817 *BB->getTerminator());
4818 }
4819 NewPN->addIncoming(TheLoad, BB);
4820 }
4821 return ReplaceInstUsesWith(LI, NewPN);
4822 }
4823 }
4824 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004825 return 0;
4826}
4827
Chris Lattner72684fe2005-01-31 05:51:45 +00004828/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
4829/// when possible.
4830static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
4831 User *CI = cast<User>(SI.getOperand(1));
4832 Value *CastOp = CI->getOperand(0);
4833
4834 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
4835 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
4836 const Type *SrcPTy = SrcTy->getElementType();
4837
4838 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
4839 // If the source is an array, the code below will not succeed. Check to
4840 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
4841 // constants.
4842 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
4843 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
4844 if (ASrcTy->getNumElements() != 0) {
4845 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
4846 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
4847 SrcTy = cast<PointerType>(CastOp->getType());
4848 SrcPTy = SrcTy->getElementType();
4849 }
4850
4851 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
4852 IC.getTargetData().getTypeSize(SrcPTy) ==
4853 IC.getTargetData().getTypeSize(DestPTy)) {
4854
4855 // Okay, we are casting from one integer or pointer type to another of
4856 // the same size. Instead of casting the pointer before the store, cast
4857 // the value to be stored.
4858 Value *NewCast;
4859 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
4860 NewCast = ConstantExpr::getCast(C, SrcPTy);
4861 else
4862 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
4863 SrcPTy,
4864 SI.getOperand(0)->getName()+".c"), SI);
4865
4866 return new StoreInst(NewCast, CastOp);
4867 }
4868 }
4869 }
4870 return 0;
4871}
4872
Chris Lattner31f486c2005-01-31 05:36:43 +00004873Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
4874 Value *Val = SI.getOperand(0);
4875 Value *Ptr = SI.getOperand(1);
4876
4877 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
4878 removeFromWorkList(&SI);
4879 SI.eraseFromParent();
4880 ++NumCombined;
4881 return 0;
4882 }
4883
4884 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
4885
4886 // store X, null -> turns into 'unreachable' in SimplifyCFG
4887 if (isa<ConstantPointerNull>(Ptr)) {
4888 if (!isa<UndefValue>(Val)) {
4889 SI.setOperand(0, UndefValue::get(Val->getType()));
4890 if (Instruction *U = dyn_cast<Instruction>(Val))
4891 WorkList.push_back(U); // Dropped a use.
4892 ++NumCombined;
4893 }
4894 return 0; // Do not modify these!
4895 }
4896
4897 // store undef, Ptr -> noop
4898 if (isa<UndefValue>(Val)) {
4899 removeFromWorkList(&SI);
4900 SI.eraseFromParent();
4901 ++NumCombined;
4902 return 0;
4903 }
4904
Chris Lattner72684fe2005-01-31 05:51:45 +00004905 // If the pointer destination is a cast, see if we can fold the cast into the
4906 // source instead.
4907 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
4908 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
4909 return Res;
4910 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
4911 if (CE->getOpcode() == Instruction::Cast)
4912 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
4913 return Res;
4914
Chris Lattner31f486c2005-01-31 05:36:43 +00004915 return 0;
4916}
4917
4918
Chris Lattner9eef8a72003-06-04 04:46:00 +00004919Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
4920 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00004921 Value *X;
4922 BasicBlock *TrueDest;
4923 BasicBlock *FalseDest;
4924 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
4925 !isa<Constant>(X)) {
4926 // Swap Destinations and condition...
4927 BI.setCondition(X);
4928 BI.setSuccessor(0, FalseDest);
4929 BI.setSuccessor(1, TrueDest);
4930 return &BI;
4931 }
4932
4933 // Cannonicalize setne -> seteq
4934 Instruction::BinaryOps Op; Value *Y;
4935 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
4936 TrueDest, FalseDest)))
4937 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
4938 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
4939 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
4940 std::string Name = I->getName(); I->setName("");
4941 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
4942 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00004943 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00004944 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00004945 BI.setSuccessor(0, FalseDest);
4946 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004947 removeFromWorkList(I);
4948 I->getParent()->getInstList().erase(I);
4949 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00004950 return &BI;
4951 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00004952
Chris Lattner9eef8a72003-06-04 04:46:00 +00004953 return 0;
4954}
Chris Lattner1085bdf2002-11-04 16:18:53 +00004955
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004956Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4957 Value *Cond = SI.getCondition();
4958 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4959 if (I->getOpcode() == Instruction::Add)
4960 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4961 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4962 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00004963 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004964 AddRHS));
4965 SI.setOperand(0, I->getOperand(0));
4966 WorkList.push_back(I);
4967 return &SI;
4968 }
4969 }
4970 return 0;
4971}
4972
Chris Lattnerca081252001-12-14 16:52:21 +00004973
Chris Lattner99f48c62002-09-02 04:59:56 +00004974void InstCombiner::removeFromWorkList(Instruction *I) {
4975 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4976 WorkList.end());
4977}
4978
Chris Lattner39c98bb2004-12-08 23:43:58 +00004979
4980/// TryToSinkInstruction - Try to move the specified instruction from its
4981/// current block into the beginning of DestBlock, which can only happen if it's
4982/// safe to move the instruction past all of the instructions between it and the
4983/// end of its block.
4984static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
4985 assert(I->hasOneUse() && "Invariants didn't hold!");
4986
4987 // Cannot move control-flow-involving instructions.
4988 if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
4989
4990 // Do not sink alloca instructions out of the entry block.
4991 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
4992 return false;
4993
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00004994 // We can only sink load instructions if there is nothing between the load and
4995 // the end of block that could change the value.
4996 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4997 if (LI->isVolatile()) return false; // Don't sink volatile loads.
4998
4999 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5000 Scan != E; ++Scan)
5001 if (Scan->mayWriteToMemory())
5002 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005003 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00005004
5005 BasicBlock::iterator InsertPos = DestBlock->begin();
5006 while (isa<PHINode>(InsertPos)) ++InsertPos;
5007
5008 BasicBlock *SrcBlock = I->getParent();
5009 DestBlock->getInstList().splice(InsertPos, SrcBlock->getInstList(), I);
5010 ++NumSunkInst;
5011 return true;
5012}
5013
Chris Lattner113f4f42002-06-25 16:13:24 +00005014bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00005015 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005016 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00005017
Chris Lattnerb643a9e2004-05-01 23:19:52 +00005018 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
5019 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00005020
Chris Lattnerca081252001-12-14 16:52:21 +00005021
5022 while (!WorkList.empty()) {
5023 Instruction *I = WorkList.back(); // Get an instruction from the worklist
5024 WorkList.pop_back();
5025
Misha Brukman632df282002-10-29 23:06:16 +00005026 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00005027 // Check to see if we can DIE the instruction...
5028 if (isInstructionTriviallyDead(I)) {
5029 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005030 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00005031 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00005032 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005033
Chris Lattnercd517ff2005-01-28 19:32:01 +00005034 DEBUG(std::cerr << "IC: DCE: " << *I);
5035
5036 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005037 removeFromWorkList(I);
5038 continue;
5039 }
Chris Lattner99f48c62002-09-02 04:59:56 +00005040
Misha Brukman632df282002-10-29 23:06:16 +00005041 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00005042 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005043 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00005044 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005045 cast<Constant>(Ptr)->isNullValue() &&
5046 !isa<ConstantPointerNull>(C) &&
5047 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00005048 // If this is a constant expr gep that is effectively computing an
5049 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5050 bool isFoldableGEP = true;
5051 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5052 if (!isa<ConstantInt>(I->getOperand(i)))
5053 isFoldableGEP = false;
5054 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005055 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00005056 std::vector<Value*>(I->op_begin()+1, I->op_end()));
5057 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00005058 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00005059 C = ConstantExpr::getCast(C, I->getType());
5060 }
5061 }
5062
Chris Lattnercd517ff2005-01-28 19:32:01 +00005063 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5064
Chris Lattner99f48c62002-09-02 04:59:56 +00005065 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00005066 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00005067 ReplaceInstUsesWith(*I, C);
5068
Chris Lattner99f48c62002-09-02 04:59:56 +00005069 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005070 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00005071 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005072 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00005073 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005074
Chris Lattner39c98bb2004-12-08 23:43:58 +00005075 // See if we can trivially sink this instruction to a successor basic block.
5076 if (I->hasOneUse()) {
5077 BasicBlock *BB = I->getParent();
5078 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5079 if (UserParent != BB) {
5080 bool UserIsSuccessor = false;
5081 // See if the user is one of our successors.
5082 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5083 if (*SI == UserParent) {
5084 UserIsSuccessor = true;
5085 break;
5086 }
5087
5088 // If the user is one of our immediate successors, and if that successor
5089 // only has us as a predecessors (we'd have to split the critical edge
5090 // otherwise), we can keep going.
5091 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5092 next(pred_begin(UserParent)) == pred_end(UserParent))
5093 // Okay, the CFG is simple enough, try to sink this instruction.
5094 Changed |= TryToSinkInstruction(I, UserParent);
5095 }
5096 }
5097
Chris Lattnerca081252001-12-14 16:52:21 +00005098 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005099 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00005100 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00005101 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00005102 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005103 DEBUG(std::cerr << "IC: Old = " << *I
5104 << " New = " << *Result);
5105
Chris Lattner396dbfe2004-06-09 05:08:07 +00005106 // Everything uses the new instruction now.
5107 I->replaceAllUsesWith(Result);
5108
5109 // Push the new instruction and any users onto the worklist.
5110 WorkList.push_back(Result);
5111 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005112
5113 // Move the name to the new instruction first...
5114 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00005115 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005116
5117 // Insert the new instruction into the basic block...
5118 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00005119 BasicBlock::iterator InsertPos = I;
5120
5121 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5122 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5123 ++InsertPos;
5124
5125 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005126
Chris Lattner63d75af2004-05-01 23:27:23 +00005127 // Make sure that we reprocess all operands now that we reduced their
5128 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00005129 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5130 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5131 WorkList.push_back(OpI);
5132
Chris Lattner396dbfe2004-06-09 05:08:07 +00005133 // Instructions can end up on the worklist more than once. Make sure
5134 // we do not process an instruction that has been deleted.
5135 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005136
5137 // Erase the old instruction.
5138 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00005139 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005140 DEBUG(std::cerr << "IC: MOD = " << *I);
5141
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005142 // If the instruction was modified, it's possible that it is now dead.
5143 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00005144 if (isInstructionTriviallyDead(I)) {
5145 // Make sure we process all operands now that we are reducing their
5146 // use counts.
5147 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5148 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5149 WorkList.push_back(OpI);
5150
5151 // Instructions may end up in the worklist more than once. Erase all
5152 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00005153 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00005154 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00005155 } else {
5156 WorkList.push_back(Result);
5157 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005158 }
Chris Lattner053c0932002-05-14 15:24:07 +00005159 }
Chris Lattner260ab202002-04-18 17:39:14 +00005160 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00005161 }
5162 }
5163
Chris Lattner260ab202002-04-18 17:39:14 +00005164 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00005165}
5166
Brian Gaeke38b79e82004-07-27 17:43:21 +00005167FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00005168 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00005169}
Brian Gaeke960707c2003-11-11 22:41:34 +00005170