blob: 766cf0173261a5195cca25048d129b000fb89181 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// 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.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
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
Misha Brukmanb1c93172005-04-21 23:48:37 +0000106 //
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;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000162
Chris Lattner7e794272004-09-24 15:21:34 +0000163 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();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000278
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000279 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;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000305 }
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();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000430
Chris Lattnerb8b97502003-08-13 19:01:45 +0000431 // 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 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000466
Chris Lattnerb8b97502003-08-13 19:01:45 +0000467 // Now that the instructions are reassociated, have the functor perform
468 // the transformation...
469 return F.apply(Root);
470 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000471
Chris Lattnerb8b97502003-08-13 19:01:45 +0000472 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;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000496 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +0000497 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());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000509
Chris Lattner86102b82005-01-01 16:22:27 +0000510 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)) {
Chris Lattner374e6592005-04-21 05:43:13 +0000551 // Bool selects with constant operands can be folded to logical ops.
552 if (SI->getType() == Type::BoolTy) return 0;
553
Chris Lattner86102b82005-01-01 16:22:27 +0000554 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
555 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
556
557 return new SelectInst(SI->getCondition(), SelectTrueVal,
558 SelectFalseVal);
559 }
560 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +0000561}
562
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000563
564/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
565/// node as operand #0, see if we can fold the instruction into the PHI (which
566/// is only possible if all operands to the PHI are constants).
567Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
568 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000569 unsigned NumPHIValues = PN->getNumIncomingValues();
570 if (!PN->hasOneUse() || NumPHIValues == 0 ||
571 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000572
573 // Check to see if all of the operands of the PHI are constants. If not, we
574 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000575 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000576 if (!isa<Constant>(PN->getIncomingValue(i)))
577 return 0;
578
579 // Okay, we can do the transformation: create the new PHI node.
580 PHINode *NewPN = new PHINode(I.getType(), I.getName());
581 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +0000582 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000583 InsertNewInstBefore(NewPN, *PN);
584
585 // Next, add all of the operands to the PHI.
586 if (I.getNumOperands() == 2) {
587 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000588 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000589 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
590 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
591 PN->getIncomingBlock(i));
592 }
593 } else {
594 assert(isa<CastInst>(I) && "Unary op should be a cast!");
595 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000596 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000597 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
598 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
599 PN->getIncomingBlock(i));
600 }
601 }
602 return ReplaceInstUsesWith(I, NewPN);
603}
604
Chris Lattner113f4f42002-06-25 16:13:24 +0000605Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000606 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000607 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000608
Chris Lattnercf4a9962004-04-10 22:01:55 +0000609 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000610 // X + undef -> undef
611 if (isa<UndefValue>(RHS))
612 return ReplaceInstUsesWith(I, RHS);
613
Chris Lattnercf4a9962004-04-10 22:01:55 +0000614 // X + 0 --> X
615 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
616 RHSC->isNullValue())
617 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000618
Chris Lattnercf4a9962004-04-10 22:01:55 +0000619 // X + (signbit) --> X ^ signbit
620 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
621 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
622 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattner33eb9092004-11-05 04:45:43 +0000623 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000624 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000625 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000626
627 if (isa<PHINode>(LHS))
628 if (Instruction *NV = FoldOpIntoPhi(I))
629 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000630 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000631
Chris Lattnerb8b97502003-08-13 19:01:45 +0000632 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000633 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000634 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +0000635
636 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
637 if (RHSI->getOpcode() == Instruction::Sub)
638 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
639 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
640 }
641 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
642 if (LHSI->getOpcode() == Instruction::Sub)
643 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
644 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
645 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000646 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000647
Chris Lattner147e9752002-05-08 22:46:53 +0000648 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000649 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000650 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000651
652 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000653 if (!isa<Constant>(RHS))
654 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000655 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000656
Misha Brukmanb1c93172005-04-21 23:48:37 +0000657
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000658 ConstantInt *C2;
659 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
660 if (X == RHS) // X*C + X --> X * (C+1)
661 return BinaryOperator::createMul(RHS, AddOne(C2));
662
663 // X*C1 + X*C2 --> X * (C1+C2)
664 ConstantInt *C1;
665 if (X == dyn_castFoldableMul(RHS, C1))
666 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000667 }
668
669 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000670 if (dyn_castFoldableMul(RHS, C2) == LHS)
671 return BinaryOperator::createMul(LHS, AddOne(C2));
672
Chris Lattner57c8d992003-02-18 19:57:07 +0000673
Chris Lattnerb8b97502003-08-13 19:01:45 +0000674 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000675 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000676 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000677
Chris Lattnerb9cde762003-10-02 15:11:26 +0000678 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000679 Value *X;
680 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
681 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
682 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000683 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000684
Chris Lattnerbff91d92004-10-08 05:07:56 +0000685 // (X & FF00) + xx00 -> (X+xx00) & FF00
686 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
687 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
688 if (Anded == CRHS) {
689 // See if all bits from the first bit set in the Add RHS up are included
690 // in the mask. First, get the rightmost bit.
691 uint64_t AddRHSV = CRHS->getRawValue();
692
693 // Form a mask of all bits from the lowest bit added through the top.
694 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
695 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
696
697 // See if the and mask includes all of these bits.
698 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000699
Chris Lattnerbff91d92004-10-08 05:07:56 +0000700 if (AddRHSHighBits == AddRHSHighBitsAnd) {
701 // Okay, the xform is safe. Insert the new add pronto.
702 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
703 LHS->getName()), I);
704 return BinaryOperator::createAnd(NewAdd, C2);
705 }
706 }
707 }
708
Chris Lattnerd4252a72004-07-30 07:50:03 +0000709 // Try to fold constant add into select arguments.
710 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +0000711 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +0000712 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000713 }
714
Chris Lattner113f4f42002-06-25 16:13:24 +0000715 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000716}
717
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000718// isSignBit - Return true if the value represented by the constant only has the
719// highest order bit set.
720static bool isSignBit(ConstantInt *CI) {
721 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
722 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
723}
724
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000725static unsigned getTypeSizeInBits(const Type *Ty) {
726 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
727}
728
Chris Lattner022167f2004-03-13 00:11:49 +0000729/// RemoveNoopCast - Strip off nonconverting casts from the value.
730///
731static Value *RemoveNoopCast(Value *V) {
732 if (CastInst *CI = dyn_cast<CastInst>(V)) {
733 const Type *CTy = CI->getType();
734 const Type *OpTy = CI->getOperand(0)->getType();
735 if (CTy->isInteger() && OpTy->isInteger()) {
736 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
737 return RemoveNoopCast(CI->getOperand(0));
738 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
739 return RemoveNoopCast(CI->getOperand(0));
740 }
741 return V;
742}
743
Chris Lattner113f4f42002-06-25 16:13:24 +0000744Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000745 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000746
Chris Lattnere6794492002-08-12 21:17:25 +0000747 if (Op0 == Op1) // sub X, X -> 0
748 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000749
Chris Lattnere6794492002-08-12 21:17:25 +0000750 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000751 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000752 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000753
Chris Lattner81a7a232004-10-16 18:11:37 +0000754 if (isa<UndefValue>(Op0))
755 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
756 if (isa<UndefValue>(Op1))
757 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
758
Chris Lattner8f2f5982003-11-05 01:06:05 +0000759 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
760 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000761 if (C->isAllOnesValue())
762 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000763
Chris Lattner8f2f5982003-11-05 01:06:05 +0000764 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000765 Value *X;
766 if (match(Op1, m_Not(m_Value(X))))
767 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000768 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000769 // -((uint)X >> 31) -> ((int)X >> 31)
770 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000771 if (C->isNullValue()) {
772 Value *NoopCastedRHS = RemoveNoopCast(Op1);
773 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000774 if (SI->getOpcode() == Instruction::Shr)
775 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
776 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000777 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000778 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000779 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000780 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000781 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000782 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000783 // Ok, the transformation is safe. Insert a cast of the incoming
784 // value, then the new shift, then the new cast.
785 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
786 SI->getOperand(0)->getName());
787 Value *InV = InsertNewInstBefore(FirstCast, I);
788 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
789 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000790 if (NewShift->getType() == I.getType())
791 return NewShift;
792 else {
793 InV = InsertNewInstBefore(NewShift, I);
794 return new CastInst(NewShift, I.getType());
795 }
Chris Lattner92295c52004-03-12 23:53:13 +0000796 }
797 }
Chris Lattner022167f2004-03-13 00:11:49 +0000798 }
Chris Lattner183b3362004-04-09 19:05:30 +0000799
800 // Try to fold constant sub into select arguments.
801 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +0000802 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000803 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000804
805 if (isa<PHINode>(Op0))
806 if (Instruction *NV = FoldOpIntoPhi(I))
807 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000808 }
809
Chris Lattnera9be4492005-04-07 16:15:25 +0000810 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
811 if (Op1I->getOpcode() == Instruction::Add &&
812 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000813 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000814 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000815 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000816 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000817 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
818 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
819 // C1-(X+C2) --> (C1-C2)-X
820 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
821 Op1I->getOperand(0));
822 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000823 }
824
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000825 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000826 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
827 // is not used by anyone else...
828 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000829 if (Op1I->getOpcode() == Instruction::Sub &&
830 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000831 // Swap the two operands of the subexpr...
832 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
833 Op1I->setOperand(0, IIOp1);
834 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000835
Chris Lattner3082c5a2003-02-18 19:28:33 +0000836 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000837 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000838 }
839
840 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
841 //
842 if (Op1I->getOpcode() == Instruction::And &&
843 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
844 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
845
Chris Lattner396dbfe2004-06-09 05:08:07 +0000846 Value *NewNot =
847 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000848 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000849 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000850
Chris Lattner0aee4b72004-10-06 15:08:25 +0000851 // -(X sdiv C) -> (X sdiv -C)
852 if (Op1I->getOpcode() == Instruction::Div)
853 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +0000854 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +0000855 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +0000856 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +0000857 ConstantExpr::getNeg(DivRHS));
858
Chris Lattner57c8d992003-02-18 19:57:07 +0000859 // X - X*C --> X * (1-C)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000860 ConstantInt *C2;
861 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000862 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000863 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000864 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000865 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000866 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000867 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000868
Chris Lattner47060462005-04-07 17:14:51 +0000869 if (!Op0->getType()->isFloatingPoint())
870 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
871 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +0000872 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
873 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
874 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
875 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +0000876 } else if (Op0I->getOpcode() == Instruction::Sub) {
877 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
878 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +0000879 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000880
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000881 ConstantInt *C1;
882 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
883 if (X == Op1) { // X*C - X --> X * (C-1)
884 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
885 return BinaryOperator::createMul(Op1, CP1);
886 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000887
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000888 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
889 if (X == dyn_castFoldableMul(Op1, C2))
890 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
891 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000892 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000893}
894
Chris Lattnere79e8542004-02-23 06:38:22 +0000895/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
896/// really just returns true if the most significant (sign) bit is set.
897static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
898 if (RHS->getType()->isSigned()) {
899 // True if source is LHS < 0 or LHS <= -1
900 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
901 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
902 } else {
903 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
904 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
905 // the size of the integer type.
906 if (Opcode == Instruction::SetGE)
907 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
908 if (Opcode == Instruction::SetGT)
909 return RHSC->getValue() ==
910 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
911 }
912 return false;
913}
914
Chris Lattner113f4f42002-06-25 16:13:24 +0000915Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000916 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000917 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000918
Chris Lattner81a7a232004-10-16 18:11:37 +0000919 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
920 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
921
Chris Lattnere6794492002-08-12 21:17:25 +0000922 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000923 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
924 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000925
926 // ((X << C1)*C2) == (X * (C2 << C1))
927 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
928 if (SI->getOpcode() == Instruction::Shl)
929 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000930 return BinaryOperator::createMul(SI->getOperand(0),
931 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000932
Chris Lattnercce81be2003-09-11 22:24:54 +0000933 if (CI->isNullValue())
934 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
935 if (CI->equalsInt(1)) // X * 1 == X
936 return ReplaceInstUsesWith(I, Op0);
937 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000938 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000939
Chris Lattnercce81be2003-09-11 22:24:54 +0000940 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000941 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
942 return new ShiftInst(Instruction::Shl, Op0,
943 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000944 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000945 if (Op1F->isNullValue())
946 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000947
Chris Lattner3082c5a2003-02-18 19:28:33 +0000948 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
949 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
950 if (Op1F->getValue() == 1.0)
951 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
952 }
Chris Lattner183b3362004-04-09 19:05:30 +0000953
954 // Try to fold constant mul into select arguments.
955 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +0000956 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000957 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000958
959 if (isa<PHINode>(Op0))
960 if (Instruction *NV = FoldOpIntoPhi(I))
961 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000962 }
963
Chris Lattner934a64cf2003-03-10 23:23:04 +0000964 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
965 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000966 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000967
Chris Lattner2635b522004-02-23 05:39:21 +0000968 // If one of the operands of the multiply is a cast from a boolean value, then
969 // we know the bool is either zero or one, so this is a 'masking' multiply.
970 // See if we can simplify things based on how the boolean was originally
971 // formed.
972 CastInst *BoolCast = 0;
973 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
974 if (CI->getOperand(0)->getType() == Type::BoolTy)
975 BoolCast = CI;
976 if (!BoolCast)
977 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
978 if (CI->getOperand(0)->getType() == Type::BoolTy)
979 BoolCast = CI;
980 if (BoolCast) {
981 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
982 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
983 const Type *SCOpTy = SCIOp0->getType();
984
Chris Lattnere79e8542004-02-23 06:38:22 +0000985 // If the setcc is true iff the sign bit of X is set, then convert this
986 // multiply into a shift/and combination.
987 if (isa<ConstantInt>(SCIOp1) &&
988 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000989 // Shift the X value right to turn it into "all signbits".
990 Constant *Amt = ConstantUInt::get(Type::UByteTy,
991 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000992 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000993 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000994 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
995 SCIOp0->getName()), I);
996 }
997
998 Value *V =
999 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1000 BoolCast->getOperand(0)->getName()+
1001 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001002
1003 // If the multiply type is not the same as the source type, sign extend
1004 // or truncate to the multiply type.
1005 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001006 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001007
Chris Lattner2635b522004-02-23 05:39:21 +00001008 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001009 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001010 }
1011 }
1012 }
1013
Chris Lattner113f4f42002-06-25 16:13:24 +00001014 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001015}
1016
Chris Lattner113f4f42002-06-25 16:13:24 +00001017Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001018 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001019
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001020 if (isa<UndefValue>(Op0)) // undef / X -> 0
1021 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1022 if (isa<UndefValue>(Op1))
1023 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1024
1025 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001026 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001027 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001028 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001029
Chris Lattnere20c3342004-04-26 14:01:59 +00001030 // div X, -1 == -X
1031 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001032 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001033
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001034 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001035 if (LHS->getOpcode() == Instruction::Div)
1036 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001037 // (X / C1) / C2 -> X / (C1*C2)
1038 return BinaryOperator::createDiv(LHS->getOperand(0),
1039 ConstantExpr::getMul(RHS, LHSRHS));
1040 }
1041
Chris Lattner3082c5a2003-02-18 19:28:33 +00001042 // Check to see if this is an unsigned division with an exact power of 2,
1043 // if so, convert to a right shift.
1044 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1045 if (uint64_t Val = C->getValue()) // Don't break X / 0
1046 if (uint64_t C = Log2(Val))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001047 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001048 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001049
Chris Lattner4ad08352004-10-09 02:50:40 +00001050 // -X/C -> X/-C
1051 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001052 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001053 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1054
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001055 if (!RHS->isNullValue()) {
1056 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001057 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001058 return R;
1059 if (isa<PHINode>(Op0))
1060 if (Instruction *NV = FoldOpIntoPhi(I))
1061 return NV;
1062 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001063 }
1064
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001065 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1066 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1067 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1068 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1069 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1070 if (STO->getValue() == 0) { // Couldn't be this argument.
1071 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001072 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001073 } else if (SFO->getValue() == 0) {
Chris Lattner42362612005-04-08 04:03:26 +00001074 I.setOperand(2, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001075 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001076 }
1077
Chris Lattner42362612005-04-08 04:03:26 +00001078 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
1079 unsigned TSA = 0, FSA = 0;
1080 if ((TVA == 1 || (TSA = Log2(TVA))) && // Log2 fails for 0 & 1.
1081 (FVA == 1 || (FSA = Log2(FVA)))) {
1082 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1083 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1084 TC, SI->getName()+".t");
1085 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001086
Chris Lattner42362612005-04-08 04:03:26 +00001087 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1088 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1089 FC, SI->getName()+".f");
1090 FSI = InsertNewInstBefore(FSI, I);
1091 return new SelectInst(SI->getOperand(0), TSI, FSI);
1092 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001093 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001094
Chris Lattner3082c5a2003-02-18 19:28:33 +00001095 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001096 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001097 if (LHS->equalsInt(0))
1098 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1099
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001100 return 0;
1101}
1102
1103
Chris Lattner113f4f42002-06-25 16:13:24 +00001104Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001105 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner7fd5f072004-07-06 07:01:22 +00001106 if (I.getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001107 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001108 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001109 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001110 // X % -Y -> X % Y
1111 AddUsesToWorkList(I);
1112 I.setOperand(1, RHSNeg);
1113 return &I;
1114 }
1115
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001116 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001117 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001118 if (isa<UndefValue>(Op1))
1119 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001120
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001121 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001122 if (RHS->equalsInt(1)) // X % 1 == 0
1123 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1124
1125 // Check to see if this is an unsigned remainder with an exact power of 2,
1126 // if so, convert to a bitwise and.
1127 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1128 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001129 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001130 return BinaryOperator::createAnd(Op0,
1131 ConstantUInt::get(I.getType(), Val-1));
1132
1133 if (!RHS->isNullValue()) {
1134 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001135 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001136 return R;
1137 if (isa<PHINode>(Op0))
1138 if (Instruction *NV = FoldOpIntoPhi(I))
1139 return NV;
1140 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001141 }
1142
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001143 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1144 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1145 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1146 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1147 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1148 if (STO->getValue() == 0) { // Couldn't be this argument.
1149 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001150 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001151 } else if (SFO->getValue() == 0) {
1152 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001153 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001154 }
1155
1156 if (!(STO->getValue() & (STO->getValue()-1)) &&
1157 !(SFO->getValue() & (SFO->getValue()-1))) {
1158 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1159 SubOne(STO), SI->getName()+".t"), I);
1160 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1161 SubOne(SFO), SI->getName()+".f"), I);
1162 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1163 }
1164 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001165
Chris Lattner3082c5a2003-02-18 19:28:33 +00001166 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001167 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001168 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001169 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1170
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001171 return 0;
1172}
1173
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001174// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001175static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001176 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1177 // Calculate -1 casted to the right type...
1178 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1179 uint64_t Val = ~0ULL; // All ones
1180 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1181 return CU->getValue() == Val-1;
1182 }
1183
1184 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001185
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001186 // Calculate 0111111111..11111
1187 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1188 int64_t Val = INT64_MAX; // All ones
1189 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1190 return CS->getValue() == Val-1;
1191}
1192
1193// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001194static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001195 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1196 return CU->getValue() == 1;
1197
1198 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001199
1200 // Calculate 1111111111000000000000
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001201 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1202 int64_t Val = -1; // All ones
1203 Val <<= TypeBits-1; // Shift over to the right spot
1204 return CS->getValue() == Val+1;
1205}
1206
Chris Lattner35167c32004-06-09 07:59:58 +00001207// isOneBitSet - Return true if there is exactly one bit set in the specified
1208// constant.
1209static bool isOneBitSet(const ConstantInt *CI) {
1210 uint64_t V = CI->getRawValue();
1211 return V && (V & (V-1)) == 0;
1212}
1213
Chris Lattner8fc5af42004-09-23 21:46:38 +00001214#if 0 // Currently unused
1215// isLowOnes - Return true if the constant is of the form 0+1+.
1216static bool isLowOnes(const ConstantInt *CI) {
1217 uint64_t V = CI->getRawValue();
1218
1219 // There won't be bits set in parts that the type doesn't contain.
1220 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1221
1222 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1223 return U && V && (U & V) == 0;
1224}
1225#endif
1226
1227// isHighOnes - Return true if the constant is of the form 1+0+.
1228// This is the same as lowones(~X).
1229static bool isHighOnes(const ConstantInt *CI) {
1230 uint64_t V = ~CI->getRawValue();
1231
1232 // There won't be bits set in parts that the type doesn't contain.
1233 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1234
1235 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1236 return U && V && (U & V) == 0;
1237}
1238
1239
Chris Lattner3ac7c262003-08-13 20:16:26 +00001240/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1241/// are carefully arranged to allow folding of expressions such as:
1242///
1243/// (A < B) | (A > B) --> (A != B)
1244///
1245/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1246/// represents that the comparison is true if A == B, and bit value '1' is true
1247/// if A < B.
1248///
1249static unsigned getSetCondCode(const SetCondInst *SCI) {
1250 switch (SCI->getOpcode()) {
1251 // False -> 0
1252 case Instruction::SetGT: return 1;
1253 case Instruction::SetEQ: return 2;
1254 case Instruction::SetGE: return 3;
1255 case Instruction::SetLT: return 4;
1256 case Instruction::SetNE: return 5;
1257 case Instruction::SetLE: return 6;
1258 // True -> 7
1259 default:
1260 assert(0 && "Invalid SetCC opcode!");
1261 return 0;
1262 }
1263}
1264
1265/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1266/// opcode and two operands into either a constant true or false, or a brand new
1267/// SetCC instruction.
1268static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1269 switch (Opcode) {
1270 case 0: return ConstantBool::False;
1271 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1272 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1273 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1274 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1275 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1276 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1277 case 7: return ConstantBool::True;
1278 default: assert(0 && "Illegal SetCCCode!"); return 0;
1279 }
1280}
1281
1282// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1283struct FoldSetCCLogical {
1284 InstCombiner &IC;
1285 Value *LHS, *RHS;
1286 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1287 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1288 bool shouldApply(Value *V) const {
1289 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1290 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1291 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1292 return false;
1293 }
1294 Instruction *apply(BinaryOperator &Log) const {
1295 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1296 if (SCI->getOperand(0) != LHS) {
1297 assert(SCI->getOperand(1) == LHS);
1298 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1299 }
1300
1301 unsigned LHSCode = getSetCondCode(SCI);
1302 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1303 unsigned Code;
1304 switch (Log.getOpcode()) {
1305 case Instruction::And: Code = LHSCode & RHSCode; break;
1306 case Instruction::Or: Code = LHSCode | RHSCode; break;
1307 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001308 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001309 }
1310
1311 Value *RV = getSetCCValue(Code, LHS, RHS);
1312 if (Instruction *I = dyn_cast<Instruction>(RV))
1313 return I;
1314 // Otherwise, it's a constant boolean value...
1315 return IC.ReplaceInstUsesWith(Log, RV);
1316 }
1317};
1318
1319
Chris Lattner86102b82005-01-01 16:22:27 +00001320/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1321/// this predicate to simplify operations downstream. V and Mask are known to
1322/// be the same type.
1323static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
1324 if (isa<UndefValue>(V) || Mask->isNullValue())
1325 return true;
1326 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
1327 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001328
Chris Lattner86102b82005-01-01 16:22:27 +00001329 if (Instruction *I = dyn_cast<Instruction>(V)) {
1330 switch (I->getOpcode()) {
1331 case Instruction::And:
1332 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
1333 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
1334 if (ConstantExpr::getAnd(CI, Mask)->isNullValue())
1335 return true;
1336 break;
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001337 case Instruction::Or:
1338 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001339 return MaskedValueIsZero(I->getOperand(1), Mask) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001340 MaskedValueIsZero(I->getOperand(0), Mask);
1341 case Instruction::Select:
1342 // If the T and F values are MaskedValueIsZero, the result is also zero.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001343 return MaskedValueIsZero(I->getOperand(2), Mask) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001344 MaskedValueIsZero(I->getOperand(1), Mask);
Chris Lattner86102b82005-01-01 16:22:27 +00001345 case Instruction::Cast: {
1346 const Type *SrcTy = I->getOperand(0)->getType();
1347 if (SrcTy->isIntegral()) {
1348 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
1349 if (SrcTy->isUnsigned() && // Only handle zero ext.
1350 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
1351 return true;
1352
1353 // If this is a noop cast, recurse.
1354 if (SrcTy != Type::BoolTy)
1355 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() ==I->getType()) ||
1356 SrcTy->getSignedVersion() == I->getType()) {
1357 Constant *NewMask =
1358 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
1359 return MaskedValueIsZero(I->getOperand(0),
1360 cast<ConstantIntegral>(NewMask));
1361 }
1362 }
1363 break;
1364 }
1365 case Instruction::Shl:
1366 // (shl X, C1) & C2 == 0 iff (-1 << C1) & C2 == 0
1367 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1368 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1369 C1 = ConstantExpr::getShl(C1, SA);
1370 C1 = ConstantExpr::getAnd(C1, Mask);
1371 if (C1->isNullValue())
1372 return true;
1373 }
1374 break;
1375 case Instruction::Shr:
1376 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1377 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1378 if (I->getType()->isUnsigned()) {
1379 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1380 C1 = ConstantExpr::getShr(C1, SA);
1381 C1 = ConstantExpr::getAnd(C1, Mask);
1382 if (C1->isNullValue())
1383 return true;
1384 }
1385 break;
1386 }
1387 }
1388
1389 return false;
1390}
1391
Chris Lattnerba1cb382003-09-19 17:17:26 +00001392// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1393// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1394// guaranteed to be either a shift instruction or a binary operator.
1395Instruction *InstCombiner::OptAndOp(Instruction *Op,
1396 ConstantIntegral *OpRHS,
1397 ConstantIntegral *AndRHS,
1398 BinaryOperator &TheAnd) {
1399 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001400 Constant *Together = 0;
1401 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001402 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001403
Chris Lattnerba1cb382003-09-19 17:17:26 +00001404 switch (Op->getOpcode()) {
1405 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001406 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001407 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1408 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001409 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001410 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001411 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001412 }
1413 break;
1414 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001415 if (Together == AndRHS) // (X | C) & C --> C
1416 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001417
Chris Lattner86102b82005-01-01 16:22:27 +00001418 if (Op->hasOneUse() && Together != OpRHS) {
1419 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1420 std::string Op0Name = Op->getName(); Op->setName("");
1421 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1422 InsertNewInstBefore(Or, TheAnd);
1423 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001424 }
1425 break;
1426 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001427 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001428 // Adding a one to a single bit bit-field should be turned into an XOR
1429 // of the bit. First thing to check is to see if this AND is with a
1430 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001431 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001432
1433 // Clear bits that are not part of the constant.
1434 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1435
1436 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001437 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001438 // Ok, at this point, we know that we are masking the result of the
1439 // ADD down to exactly one bit. If the constant we are adding has
1440 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001441 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001442
Chris Lattnerba1cb382003-09-19 17:17:26 +00001443 // Check to see if any bits below the one bit set in AndRHSV are set.
1444 if ((AddRHS & (AndRHSV-1)) == 0) {
1445 // If not, the only thing that can effect the output of the AND is
1446 // the bit specified by AndRHSV. If that bit is set, the effect of
1447 // the XOR is to toggle the bit. If it is clear, then the ADD has
1448 // no effect.
1449 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1450 TheAnd.setOperand(0, X);
1451 return &TheAnd;
1452 } else {
1453 std::string Name = Op->getName(); Op->setName("");
1454 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001455 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001456 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001457 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001458 }
1459 }
1460 }
1461 }
1462 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001463
1464 case Instruction::Shl: {
1465 // We know that the AND will not produce any of the bits shifted in, so if
1466 // the anded constant includes them, clear them now!
1467 //
1468 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001469 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1470 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001471
Chris Lattner7e794272004-09-24 15:21:34 +00001472 if (CI == ShlMask) { // Masking out bits that the shift already masks
1473 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1474 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001475 TheAnd.setOperand(1, CI);
1476 return &TheAnd;
1477 }
1478 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001479 }
Chris Lattner2da29172003-09-19 19:05:02 +00001480 case Instruction::Shr:
1481 // We know that the AND will not produce any of the bits shifted in, so if
1482 // the anded constant includes them, clear them now! This only applies to
1483 // unsigned shifts, because a signed shr may bring in set bits!
1484 //
1485 if (AndRHS->getType()->isUnsigned()) {
1486 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001487 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1488 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1489
1490 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1491 return ReplaceInstUsesWith(TheAnd, Op);
1492 } else if (CI != AndRHS) {
1493 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001494 return &TheAnd;
1495 }
Chris Lattner7e794272004-09-24 15:21:34 +00001496 } else { // Signed shr.
1497 // See if this is shifting in some sign extension, then masking it out
1498 // with an and.
1499 if (Op->hasOneUse()) {
1500 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1501 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1502 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001503 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001504 // Make the argument unsigned.
1505 Value *ShVal = Op->getOperand(0);
1506 ShVal = InsertCastBefore(ShVal,
1507 ShVal->getType()->getUnsignedVersion(),
1508 TheAnd);
1509 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1510 OpRHS, Op->getName()),
1511 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001512 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1513 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1514 TheAnd.getName()),
1515 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001516 return new CastInst(ShVal, Op->getType());
1517 }
1518 }
Chris Lattner2da29172003-09-19 19:05:02 +00001519 }
1520 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001521 }
1522 return 0;
1523}
1524
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001525
Chris Lattner6862fbd2004-09-29 17:40:11 +00001526/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1527/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1528/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1529/// insert new instructions.
1530Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1531 bool Inside, Instruction &IB) {
1532 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1533 "Lo is not <= Hi in range emission code!");
1534 if (Inside) {
1535 if (Lo == Hi) // Trivially false.
1536 return new SetCondInst(Instruction::SetNE, V, V);
1537 if (cast<ConstantIntegral>(Lo)->isMinValue())
1538 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001539
Chris Lattner6862fbd2004-09-29 17:40:11 +00001540 Constant *AddCST = ConstantExpr::getNeg(Lo);
1541 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1542 InsertNewInstBefore(Add, IB);
1543 // Convert to unsigned for the comparison.
1544 const Type *UnsType = Add->getType()->getUnsignedVersion();
1545 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1546 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1547 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1548 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1549 }
1550
1551 if (Lo == Hi) // Trivially true.
1552 return new SetCondInst(Instruction::SetEQ, V, V);
1553
1554 Hi = SubOne(cast<ConstantInt>(Hi));
1555 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1556 return new SetCondInst(Instruction::SetGT, V, Hi);
1557
1558 // Emit X-Lo > Hi-Lo-1
1559 Constant *AddCST = ConstantExpr::getNeg(Lo);
1560 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1561 InsertNewInstBefore(Add, IB);
1562 // Convert to unsigned for the comparison.
1563 const Type *UnsType = Add->getType()->getUnsignedVersion();
1564 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1565 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1566 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1567 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1568}
1569
1570
Chris Lattner113f4f42002-06-25 16:13:24 +00001571Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001572 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001573 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001574
Chris Lattner81a7a232004-10-16 18:11:37 +00001575 if (isa<UndefValue>(Op1)) // X & undef -> 0
1576 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1577
Chris Lattner86102b82005-01-01 16:22:27 +00001578 // and X, X = X
1579 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00001580 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001581
Chris Lattner86102b82005-01-01 16:22:27 +00001582 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001583 // and X, -1 == X
1584 if (AndRHS->isAllOnesValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001585 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001586
Chris Lattner86102b82005-01-01 16:22:27 +00001587 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1588 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1589
1590 // If the mask is not masking out any bits, there is no reason to do the
1591 // and in the first place.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001592 ConstantIntegral *NotAndRHS =
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001593 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001594 if (MaskedValueIsZero(Op0, NotAndRHS))
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001595 return ReplaceInstUsesWith(I, Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001596
Chris Lattnerba1cb382003-09-19 17:17:26 +00001597 // Optimize a variety of ((val OP C1) & C2) combinations...
1598 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1599 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001600 Value *Op0LHS = Op0I->getOperand(0);
1601 Value *Op0RHS = Op0I->getOperand(1);
1602 switch (Op0I->getOpcode()) {
1603 case Instruction::Xor:
1604 case Instruction::Or:
1605 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1606 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1607 if (MaskedValueIsZero(Op0LHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001608 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattner86102b82005-01-01 16:22:27 +00001609 if (MaskedValueIsZero(Op0RHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001610 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001611
1612 // If the mask is only needed on one incoming arm, push it up.
1613 if (Op0I->hasOneUse()) {
1614 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1615 // Not masking anything out for the LHS, move to RHS.
1616 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1617 Op0RHS->getName()+".masked");
1618 InsertNewInstBefore(NewRHS, I);
1619 return BinaryOperator::create(
1620 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001621 }
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001622 if (!isa<Constant>(NotAndRHS) &&
1623 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1624 // Not masking anything out for the RHS, move to LHS.
1625 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1626 Op0LHS->getName()+".masked");
1627 InsertNewInstBefore(NewLHS, I);
1628 return BinaryOperator::create(
1629 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1630 }
1631 }
1632
Chris Lattner86102b82005-01-01 16:22:27 +00001633 break;
1634 case Instruction::And:
1635 // (X & V) & C2 --> 0 iff (V & C2) == 0
1636 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1637 MaskedValueIsZero(Op0RHS, AndRHS))
1638 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1639 break;
1640 }
1641
Chris Lattner16464b32003-07-23 19:25:52 +00001642 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00001643 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001644 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00001645 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1646 const Type *SrcTy = CI->getOperand(0)->getType();
1647
1648 // If this is an integer sign or zero extension instruction.
1649 if (SrcTy->isIntegral() &&
1650 SrcTy->getPrimitiveSize() < CI->getType()->getPrimitiveSize()) {
1651
1652 if (SrcTy->isUnsigned()) {
1653 // See if this and is clearing out bits that are known to be zero
1654 // anyway (due to the zero extension).
1655 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1656 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1657 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1658 if (Result == Mask) // The "and" isn't doing anything, remove it.
1659 return ReplaceInstUsesWith(I, CI);
1660 if (Result != AndRHS) { // Reduce the and RHS constant.
1661 I.setOperand(1, Result);
1662 return &I;
1663 }
1664
1665 } else {
1666 if (CI->hasOneUse() && SrcTy->isInteger()) {
1667 // We can only do this if all of the sign bits brought in are masked
1668 // out. Compute this by first getting 0000011111, then inverting
1669 // it.
1670 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1671 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1672 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1673 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1674 // If the and is clearing all of the sign bits, change this to a
1675 // zero extension cast. To do this, cast the cast input to
1676 // unsigned, then to the requested size.
1677 Value *CastOp = CI->getOperand(0);
1678 Instruction *NC =
1679 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1680 CI->getName()+".uns");
1681 NC = InsertNewInstBefore(NC, I);
1682 // Finally, insert a replacement for CI.
1683 NC = new CastInst(NC, CI->getType(), CI->getName());
1684 CI->setName("");
1685 NC = InsertNewInstBefore(NC, I);
1686 WorkList.push_back(CI); // Delete CI later.
1687 I.setOperand(0, NC);
1688 return &I; // The AND operand was modified.
1689 }
1690 }
1691 }
1692 }
Chris Lattner33217db2003-07-23 19:36:21 +00001693 }
Chris Lattner183b3362004-04-09 19:05:30 +00001694
1695 // Try to fold constant and into select arguments.
1696 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001697 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001698 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001699 if (isa<PHINode>(Op0))
1700 if (Instruction *NV = FoldOpIntoPhi(I))
1701 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001702 }
1703
Chris Lattnerbb74e222003-03-10 23:06:50 +00001704 Value *Op0NotVal = dyn_castNotVal(Op0);
1705 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001706
Chris Lattner023a4832004-06-18 06:07:51 +00001707 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1708 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1709
Misha Brukman9c003d82004-07-30 12:50:08 +00001710 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001711 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001712 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1713 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001714 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001715 return BinaryOperator::createNot(Or);
1716 }
1717
Chris Lattner623826c2004-09-28 21:48:02 +00001718 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1719 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001720 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1721 return R;
1722
Chris Lattner623826c2004-09-28 21:48:02 +00001723 Value *LHSVal, *RHSVal;
1724 ConstantInt *LHSCst, *RHSCst;
1725 Instruction::BinaryOps LHSCC, RHSCC;
1726 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1727 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1728 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1729 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001730 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00001731 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1732 // Ensure that the larger constant is on the RHS.
1733 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1734 SetCondInst *LHS = cast<SetCondInst>(Op0);
1735 if (cast<ConstantBool>(Cmp)->getValue()) {
1736 std::swap(LHS, RHS);
1737 std::swap(LHSCst, RHSCst);
1738 std::swap(LHSCC, RHSCC);
1739 }
1740
1741 // At this point, we know we have have two setcc instructions
1742 // comparing a value against two constants and and'ing the result
1743 // together. Because of the above check, we know that we only have
1744 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1745 // FoldSetCCLogical check above), that the two constants are not
1746 // equal.
1747 assert(LHSCst != RHSCst && "Compares not folded above?");
1748
1749 switch (LHSCC) {
1750 default: assert(0 && "Unknown integer condition code!");
1751 case Instruction::SetEQ:
1752 switch (RHSCC) {
1753 default: assert(0 && "Unknown integer condition code!");
1754 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1755 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1756 return ReplaceInstUsesWith(I, ConstantBool::False);
1757 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1758 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1759 return ReplaceInstUsesWith(I, LHS);
1760 }
1761 case Instruction::SetNE:
1762 switch (RHSCC) {
1763 default: assert(0 && "Unknown integer condition code!");
1764 case Instruction::SetLT:
1765 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1766 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1767 break; // (X != 13 & X < 15) -> no change
1768 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1769 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1770 return ReplaceInstUsesWith(I, RHS);
1771 case Instruction::SetNE:
1772 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1773 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1774 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1775 LHSVal->getName()+".off");
1776 InsertNewInstBefore(Add, I);
1777 const Type *UnsType = Add->getType()->getUnsignedVersion();
1778 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1779 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1780 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1781 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1782 }
1783 break; // (X != 13 & X != 15) -> no change
1784 }
1785 break;
1786 case Instruction::SetLT:
1787 switch (RHSCC) {
1788 default: assert(0 && "Unknown integer condition code!");
1789 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1790 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1791 return ReplaceInstUsesWith(I, ConstantBool::False);
1792 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1793 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1794 return ReplaceInstUsesWith(I, LHS);
1795 }
1796 case Instruction::SetGT:
1797 switch (RHSCC) {
1798 default: assert(0 && "Unknown integer condition code!");
1799 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1800 return ReplaceInstUsesWith(I, LHS);
1801 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1802 return ReplaceInstUsesWith(I, RHS);
1803 case Instruction::SetNE:
1804 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1805 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1806 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001807 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1808 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001809 }
1810 }
1811 }
1812 }
1813
Chris Lattner113f4f42002-06-25 16:13:24 +00001814 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001815}
1816
Chris Lattner113f4f42002-06-25 16:13:24 +00001817Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001818 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001819 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001820
Chris Lattner81a7a232004-10-16 18:11:37 +00001821 if (isa<UndefValue>(Op1))
1822 return ReplaceInstUsesWith(I, // X | undef -> -1
1823 ConstantIntegral::getAllOnesValue(I.getType()));
1824
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001825 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001826 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1827 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001828
1829 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001830 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001831 // If X is known to only contain bits that already exist in RHS, just
1832 // replace this instruction with RHS directly.
1833 if (MaskedValueIsZero(Op0,
1834 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
1835 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001836
Chris Lattnerd4252a72004-07-30 07:50:03 +00001837 ConstantInt *C1; Value *X;
1838 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1839 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1840 std::string Op0Name = Op0->getName(); Op0->setName("");
1841 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1842 InsertNewInstBefore(Or, I);
1843 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1844 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001845
Chris Lattnerd4252a72004-07-30 07:50:03 +00001846 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1847 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1848 std::string Op0Name = Op0->getName(); Op0->setName("");
1849 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1850 InsertNewInstBefore(Or, I);
1851 return BinaryOperator::createXor(Or,
1852 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001853 }
Chris Lattner183b3362004-04-09 19:05:30 +00001854
1855 // Try to fold constant and into select arguments.
1856 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001857 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001858 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001859 if (isa<PHINode>(Op0))
1860 if (Instruction *NV = FoldOpIntoPhi(I))
1861 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001862 }
1863
Chris Lattner812aab72003-08-12 19:11:07 +00001864 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001865 Value *A, *B; ConstantInt *C1, *C2;
1866 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1867 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1868 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001869
Chris Lattnerd4252a72004-07-30 07:50:03 +00001870 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1871 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00001872 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00001873 ConstantIntegral::getAllOnesValue(I.getType()));
1874 } else {
1875 A = 0;
1876 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001877
Chris Lattnerd4252a72004-07-30 07:50:03 +00001878 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1879 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00001880 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00001881 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001882
Misha Brukman9c003d82004-07-30 12:50:08 +00001883 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001884 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1885 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1886 I.getName()+".demorgan"), I);
1887 return BinaryOperator::createNot(And);
1888 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001889 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001890
Chris Lattner3ac7c262003-08-13 20:16:26 +00001891 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001892 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001893 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1894 return R;
1895
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001896 Value *LHSVal, *RHSVal;
1897 ConstantInt *LHSCst, *RHSCst;
1898 Instruction::BinaryOps LHSCC, RHSCC;
1899 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1900 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1901 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1902 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001903 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001904 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1905 // Ensure that the larger constant is on the RHS.
1906 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1907 SetCondInst *LHS = cast<SetCondInst>(Op0);
1908 if (cast<ConstantBool>(Cmp)->getValue()) {
1909 std::swap(LHS, RHS);
1910 std::swap(LHSCst, RHSCst);
1911 std::swap(LHSCC, RHSCC);
1912 }
1913
1914 // At this point, we know we have have two setcc instructions
1915 // comparing a value against two constants and or'ing the result
1916 // together. Because of the above check, we know that we only have
1917 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1918 // FoldSetCCLogical check above), that the two constants are not
1919 // equal.
1920 assert(LHSCst != RHSCst && "Compares not folded above?");
1921
1922 switch (LHSCC) {
1923 default: assert(0 && "Unknown integer condition code!");
1924 case Instruction::SetEQ:
1925 switch (RHSCC) {
1926 default: assert(0 && "Unknown integer condition code!");
1927 case Instruction::SetEQ:
1928 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1929 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1930 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1931 LHSVal->getName()+".off");
1932 InsertNewInstBefore(Add, I);
1933 const Type *UnsType = Add->getType()->getUnsignedVersion();
1934 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1935 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1936 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1937 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1938 }
1939 break; // (X == 13 | X == 15) -> no change
1940
Chris Lattner5c219462005-04-19 06:04:18 +00001941 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
1942 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001943 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1944 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1945 return ReplaceInstUsesWith(I, RHS);
1946 }
1947 break;
1948 case Instruction::SetNE:
1949 switch (RHSCC) {
1950 default: assert(0 && "Unknown integer condition code!");
1951 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1952 return ReplaceInstUsesWith(I, RHS);
1953 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1954 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1955 return ReplaceInstUsesWith(I, LHS);
1956 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1957 return ReplaceInstUsesWith(I, ConstantBool::True);
1958 }
1959 break;
1960 case Instruction::SetLT:
1961 switch (RHSCC) {
1962 default: assert(0 && "Unknown integer condition code!");
1963 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1964 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001965 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1966 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001967 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1968 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1969 return ReplaceInstUsesWith(I, RHS);
1970 }
1971 break;
1972 case Instruction::SetGT:
1973 switch (RHSCC) {
1974 default: assert(0 && "Unknown integer condition code!");
1975 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1976 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1977 return ReplaceInstUsesWith(I, LHS);
1978 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1979 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1980 return ReplaceInstUsesWith(I, ConstantBool::True);
1981 }
1982 }
1983 }
1984 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001985 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001986}
1987
Chris Lattnerc2076352004-02-16 01:20:27 +00001988// XorSelf - Implements: X ^ X --> 0
1989struct XorSelf {
1990 Value *RHS;
1991 XorSelf(Value *rhs) : RHS(rhs) {}
1992 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1993 Instruction *apply(BinaryOperator &Xor) const {
1994 return &Xor;
1995 }
1996};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001997
1998
Chris Lattner113f4f42002-06-25 16:13:24 +00001999Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002000 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002001 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002002
Chris Lattner81a7a232004-10-16 18:11:37 +00002003 if (isa<UndefValue>(Op1))
2004 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2005
Chris Lattnerc2076352004-02-16 01:20:27 +00002006 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2007 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2008 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002009 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002010 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002011
Chris Lattner97638592003-07-23 21:37:07 +00002012 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002013 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00002014 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00002015 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002016
Chris Lattner97638592003-07-23 21:37:07 +00002017 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002018 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002019 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002020 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002021 return new SetCondInst(SCI->getInverseCondition(),
2022 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002023
Chris Lattner8f2f5982003-11-05 01:06:05 +00002024 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002025 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2026 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002027 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2028 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002029 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002030 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002031 }
Chris Lattner023a4832004-06-18 06:07:51 +00002032
2033 // ~(~X & Y) --> (X | ~Y)
2034 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2035 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2036 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2037 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002038 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002039 Op0I->getOperand(1)->getName()+".not");
2040 InsertNewInstBefore(NotY, I);
2041 return BinaryOperator::createOr(Op0NotVal, NotY);
2042 }
2043 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002044
Chris Lattner97638592003-07-23 21:37:07 +00002045 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002046 switch (Op0I->getOpcode()) {
2047 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002048 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002049 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002050 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2051 return BinaryOperator::createSub(
2052 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002053 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002054 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002055 }
Chris Lattnere5806662003-11-04 23:50:51 +00002056 break;
2057 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002058 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002059 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2060 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002061 break;
2062 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002063 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002064 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002065 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002066 break;
2067 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002068 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002069 }
Chris Lattner183b3362004-04-09 19:05:30 +00002070
2071 // Try to fold constant and into select arguments.
2072 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002073 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002074 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002075 if (isa<PHINode>(Op0))
2076 if (Instruction *NV = FoldOpIntoPhi(I))
2077 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002078 }
2079
Chris Lattnerbb74e222003-03-10 23:06:50 +00002080 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002081 if (X == Op1)
2082 return ReplaceInstUsesWith(I,
2083 ConstantIntegral::getAllOnesValue(I.getType()));
2084
Chris Lattnerbb74e222003-03-10 23:06:50 +00002085 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002086 if (X == Op0)
2087 return ReplaceInstUsesWith(I,
2088 ConstantIntegral::getAllOnesValue(I.getType()));
2089
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002090 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002091 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002092 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2093 cast<BinaryOperator>(Op1I)->swapOperands();
2094 I.swapOperands();
2095 std::swap(Op0, Op1);
2096 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2097 I.swapOperands();
2098 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002099 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002100 } else if (Op1I->getOpcode() == Instruction::Xor) {
2101 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2102 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2103 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2104 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2105 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002106
2107 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002108 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002109 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2110 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002111 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002112 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2113 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002114 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002115 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002116 } else if (Op0I->getOpcode() == Instruction::Xor) {
2117 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2118 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2119 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2120 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002121 }
2122
Chris Lattner7aa2d472004-08-01 19:42:59 +00002123 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002124 Value *A, *B; ConstantInt *C1, *C2;
2125 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2126 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002127 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002128 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002129
Chris Lattner3ac7c262003-08-13 20:16:26 +00002130 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2131 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2132 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2133 return R;
2134
Chris Lattner113f4f42002-06-25 16:13:24 +00002135 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002136}
2137
Chris Lattner6862fbd2004-09-29 17:40:11 +00002138/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2139/// overflowed for this type.
2140static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2141 ConstantInt *In2) {
2142 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2143 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2144}
2145
2146static bool isPositive(ConstantInt *C) {
2147 return cast<ConstantSInt>(C)->getValue() >= 0;
2148}
2149
2150/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2151/// overflowed for this type.
2152static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2153 ConstantInt *In2) {
2154 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2155
2156 if (In1->getType()->isUnsigned())
2157 return cast<ConstantUInt>(Result)->getValue() <
2158 cast<ConstantUInt>(In1)->getValue();
2159 if (isPositive(In1) != isPositive(In2))
2160 return false;
2161 if (isPositive(In1))
2162 return cast<ConstantSInt>(Result)->getValue() <
2163 cast<ConstantSInt>(In1)->getValue();
2164 return cast<ConstantSInt>(Result)->getValue() >
2165 cast<ConstantSInt>(In1)->getValue();
2166}
2167
Chris Lattner0798af32005-01-13 20:14:25 +00002168/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2169/// code necessary to compute the offset from the base pointer (without adding
2170/// in the base pointer). Return the result as a signed integer of intptr size.
2171static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2172 TargetData &TD = IC.getTargetData();
2173 gep_type_iterator GTI = gep_type_begin(GEP);
2174 const Type *UIntPtrTy = TD.getIntPtrType();
2175 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2176 Value *Result = Constant::getNullValue(SIntPtrTy);
2177
2178 // Build a mask for high order bits.
2179 uint64_t PtrSizeMask = ~0ULL;
2180 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2181
Chris Lattner0798af32005-01-13 20:14:25 +00002182 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2183 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002184 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002185 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2186 SIntPtrTy);
2187 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2188 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002189 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002190 Scale = ConstantExpr::getMul(OpC, Scale);
2191 if (Constant *RC = dyn_cast<Constant>(Result))
2192 Result = ConstantExpr::getAdd(RC, Scale);
2193 else {
2194 // Emit an add instruction.
2195 Result = IC.InsertNewInstBefore(
2196 BinaryOperator::createAdd(Result, Scale,
2197 GEP->getName()+".offs"), I);
2198 }
2199 }
2200 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002201 // Convert to correct type.
2202 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2203 Op->getName()+".c"), I);
2204 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002205 // We'll let instcombine(mul) convert this to a shl if possible.
2206 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2207 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002208
2209 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002210 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002211 GEP->getName()+".offs"), I);
2212 }
2213 }
2214 return Result;
2215}
2216
2217/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2218/// else. At this point we know that the GEP is on the LHS of the comparison.
2219Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2220 Instruction::BinaryOps Cond,
2221 Instruction &I) {
2222 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002223
2224 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2225 if (isa<PointerType>(CI->getOperand(0)->getType()))
2226 RHS = CI->getOperand(0);
2227
Chris Lattner0798af32005-01-13 20:14:25 +00002228 Value *PtrBase = GEPLHS->getOperand(0);
2229 if (PtrBase == RHS) {
2230 // As an optimization, we don't actually have to compute the actual value of
2231 // OFFSET if this is a seteq or setne comparison, just return whether each
2232 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002233 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2234 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002235 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2236 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00002237 bool EmitIt = true;
2238 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2239 if (isa<UndefValue>(C)) // undef index -> undef.
2240 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2241 if (C->isNullValue())
2242 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002243 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2244 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00002245 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00002246 return ReplaceInstUsesWith(I, // No comparison is needed here.
2247 ConstantBool::get(Cond == Instruction::SetNE));
2248 }
2249
2250 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002251 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00002252 new SetCondInst(Cond, GEPLHS->getOperand(i),
2253 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2254 if (InVal == 0)
2255 InVal = Comp;
2256 else {
2257 InVal = InsertNewInstBefore(InVal, I);
2258 InsertNewInstBefore(Comp, I);
2259 if (Cond == Instruction::SetNE) // True if any are unequal
2260 InVal = BinaryOperator::createOr(InVal, Comp);
2261 else // True if all are equal
2262 InVal = BinaryOperator::createAnd(InVal, Comp);
2263 }
2264 }
2265 }
2266
2267 if (InVal)
2268 return InVal;
2269 else
2270 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2271 ConstantBool::get(Cond == Instruction::SetEQ));
2272 }
Chris Lattner0798af32005-01-13 20:14:25 +00002273
2274 // Only lower this if the setcc is the only user of the GEP or if we expect
2275 // the result to fold to a constant!
2276 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2277 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2278 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2279 return new SetCondInst(Cond, Offset,
2280 Constant::getNullValue(Offset->getType()));
2281 }
2282 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
2283 if (PtrBase != GEPRHS->getOperand(0))
2284 return 0;
2285
Chris Lattner81e84172005-01-13 22:25:21 +00002286 // If one of the GEPs has all zero indices, recurse.
2287 bool AllZeros = true;
2288 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2289 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2290 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2291 AllZeros = false;
2292 break;
2293 }
2294 if (AllZeros)
2295 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2296 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00002297
2298 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00002299 AllZeros = true;
2300 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2301 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2302 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2303 AllZeros = false;
2304 break;
2305 }
2306 if (AllZeros)
2307 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2308
Chris Lattner4fa89822005-01-14 00:20:05 +00002309 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2310 // If the GEPs only differ by one index, compare it.
2311 unsigned NumDifferences = 0; // Keep track of # differences.
2312 unsigned DiffOperand = 0; // The operand that differs.
2313 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2314 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002315 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSize() !=
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002316 GEPRHS->getOperand(i)->getType()->getPrimitiveSize()) {
2317 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00002318 NumDifferences = 2;
2319 break;
2320 } else {
2321 if (NumDifferences++) break;
2322 DiffOperand = i;
2323 }
2324 }
2325
2326 if (NumDifferences == 0) // SAME GEP?
2327 return ReplaceInstUsesWith(I, // No comparison is needed here.
2328 ConstantBool::get(Cond == Instruction::SetEQ));
2329 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002330 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2331 Value *RHSV = GEPRHS->getOperand(DiffOperand);
2332 if (LHSV->getType() != RHSV->getType())
2333 LHSV = InsertNewInstBefore(new CastInst(LHSV, RHSV->getType(),
2334 LHSV->getName()+".c"), I);
2335 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00002336 }
2337 }
2338
Chris Lattner0798af32005-01-13 20:14:25 +00002339 // Only lower this if the setcc is the only user of the GEP or if we expect
2340 // the result to fold to a constant!
2341 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2342 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2343 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2344 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2345 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2346 return new SetCondInst(Cond, L, R);
2347 }
2348 }
2349 return 0;
2350}
2351
2352
Chris Lattner113f4f42002-06-25 16:13:24 +00002353Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002354 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002355 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2356 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002357
2358 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002359 if (Op0 == Op1)
2360 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002361
Chris Lattner81a7a232004-10-16 18:11:37 +00002362 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2363 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2364
Chris Lattner15ff1e12004-11-14 07:33:16 +00002365 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2366 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002367 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2368 isa<ConstantPointerNull>(Op0)) &&
2369 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00002370 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002371 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2372
2373 // setcc's with boolean values can always be turned into bitwise operations
2374 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002375 switch (I.getOpcode()) {
2376 default: assert(0 && "Invalid setcc instruction!");
2377 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002378 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002379 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002380 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002381 }
Chris Lattner4456da62004-08-11 00:50:51 +00002382 case Instruction::SetNE:
2383 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002384
Chris Lattner4456da62004-08-11 00:50:51 +00002385 case Instruction::SetGT:
2386 std::swap(Op0, Op1); // Change setgt -> setlt
2387 // FALL THROUGH
2388 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2389 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2390 InsertNewInstBefore(Not, I);
2391 return BinaryOperator::createAnd(Not, Op1);
2392 }
2393 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002394 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002395 // FALL THROUGH
2396 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2397 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2398 InsertNewInstBefore(Not, I);
2399 return BinaryOperator::createOr(Not, Op1);
2400 }
2401 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002402 }
2403
Chris Lattner2dd01742004-06-09 04:24:29 +00002404 // See if we are doing a comparison between a constant and an instruction that
2405 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002406 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002407 // Check to see if we are comparing against the minimum or maximum value...
2408 if (CI->isMinValue()) {
2409 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2410 return ReplaceInstUsesWith(I, ConstantBool::False);
2411 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2412 return ReplaceInstUsesWith(I, ConstantBool::True);
2413 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2414 return BinaryOperator::createSetEQ(Op0, Op1);
2415 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2416 return BinaryOperator::createSetNE(Op0, Op1);
2417
2418 } else if (CI->isMaxValue()) {
2419 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2420 return ReplaceInstUsesWith(I, ConstantBool::False);
2421 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2422 return ReplaceInstUsesWith(I, ConstantBool::True);
2423 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2424 return BinaryOperator::createSetEQ(Op0, Op1);
2425 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2426 return BinaryOperator::createSetNE(Op0, Op1);
2427
2428 // Comparing against a value really close to min or max?
2429 } else if (isMinValuePlusOne(CI)) {
2430 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2431 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2432 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2433 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2434
2435 } else if (isMaxValueMinusOne(CI)) {
2436 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2437 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2438 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2439 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2440 }
2441
2442 // If we still have a setle or setge instruction, turn it into the
2443 // appropriate setlt or setgt instruction. Since the border cases have
2444 // already been handled above, this requires little checking.
2445 //
2446 if (I.getOpcode() == Instruction::SetLE)
2447 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2448 if (I.getOpcode() == Instruction::SetGE)
2449 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2450
Chris Lattnere1e10e12004-05-25 06:32:08 +00002451 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002452 switch (LHSI->getOpcode()) {
2453 case Instruction::And:
2454 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2455 LHSI->getOperand(0)->hasOneUse()) {
2456 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2457 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2458 // happens a LOT in code produced by the C front-end, for bitfield
2459 // access.
2460 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2461 ConstantUInt *ShAmt;
2462 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2463 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2464 const Type *Ty = LHSI->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002465
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002466 // We can fold this as long as we can't shift unknown bits
2467 // into the mask. This can only happen with signed shift
2468 // rights, as they sign-extend.
2469 if (ShAmt) {
2470 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002471 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002472 if (!CanFold) {
2473 // To test for the bad case of the signed shr, see if any
2474 // of the bits shifted in could be tested after the mask.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002475 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00002476 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002477 Constant *ShVal =
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002478 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2479 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2480 CanFold = true;
2481 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002482
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002483 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002484 Constant *NewCst;
2485 if (Shift->getOpcode() == Instruction::Shl)
2486 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2487 else
2488 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002489
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002490 // Check to see if we are shifting out any of the bits being
2491 // compared.
2492 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2493 // If we shifted bits out, the fold is not going to work out.
2494 // As a special case, check to see if this means that the
2495 // result is always true or false now.
2496 if (I.getOpcode() == Instruction::SetEQ)
2497 return ReplaceInstUsesWith(I, ConstantBool::False);
2498 if (I.getOpcode() == Instruction::SetNE)
2499 return ReplaceInstUsesWith(I, ConstantBool::True);
2500 } else {
2501 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002502 Constant *NewAndCST;
2503 if (Shift->getOpcode() == Instruction::Shl)
2504 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2505 else
2506 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2507 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002508 LHSI->setOperand(0, Shift->getOperand(0));
2509 WorkList.push_back(Shift); // Shift is dead.
2510 AddUsesToWorkList(I);
2511 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002512 }
2513 }
Chris Lattner35167c32004-06-09 07:59:58 +00002514 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002515 }
2516 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002517
Reid Spencer279fa252004-11-28 21:31:15 +00002518 // (setcc (cast X to larger), CI)
Chris Lattner03f06f12005-01-17 03:20:02 +00002519 case Instruction::Cast:
Misha Brukmanb1c93172005-04-21 23:48:37 +00002520 if (Instruction *R =
Chris Lattner03f06f12005-01-17 03:20:02 +00002521 visitSetCondInstWithCastAndConstant(I,cast<CastInst>(LHSI),CI))
2522 return R;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002523 break;
Reid Spencer279fa252004-11-28 21:31:15 +00002524
Chris Lattner272d5ca2004-09-28 18:22:15 +00002525 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2526 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2527 switch (I.getOpcode()) {
2528 default: break;
2529 case Instruction::SetEQ:
2530 case Instruction::SetNE: {
2531 // If we are comparing against bits always shifted out, the
2532 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002533 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00002534 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2535 if (Comp != CI) {// Comparing against a bit that we know is zero.
2536 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2537 Constant *Cst = ConstantBool::get(IsSetNE);
2538 return ReplaceInstUsesWith(I, Cst);
2539 }
2540
2541 if (LHSI->hasOneUse()) {
2542 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002543 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002544 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2545 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2546
2547 Constant *Mask;
2548 if (CI->getType()->isUnsigned()) {
2549 Mask = ConstantUInt::get(CI->getType(), Val);
2550 } else if (ShAmtVal != 0) {
2551 Mask = ConstantSInt::get(CI->getType(), Val);
2552 } else {
2553 Mask = ConstantInt::getAllOnesValue(CI->getType());
2554 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002555
Chris Lattner272d5ca2004-09-28 18:22:15 +00002556 Instruction *AndI =
2557 BinaryOperator::createAnd(LHSI->getOperand(0),
2558 Mask, LHSI->getName()+".mask");
2559 Value *And = InsertNewInstBefore(AndI, I);
2560 return new SetCondInst(I.getOpcode(), And,
2561 ConstantExpr::getUShr(CI, ShAmt));
2562 }
2563 }
2564 }
2565 }
2566 break;
2567
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002568 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002569 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002570 switch (I.getOpcode()) {
2571 default: break;
2572 case Instruction::SetEQ:
2573 case Instruction::SetNE: {
2574 // If we are comparing against bits always shifted out, the
2575 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002576 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00002577 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002578
Chris Lattner1023b872004-09-27 16:18:50 +00002579 if (Comp != CI) {// Comparing against a bit that we know is zero.
2580 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2581 Constant *Cst = ConstantBool::get(IsSetNE);
2582 return ReplaceInstUsesWith(I, Cst);
2583 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002584
Chris Lattner1023b872004-09-27 16:18:50 +00002585 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002586 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002587
Chris Lattner1023b872004-09-27 16:18:50 +00002588 // Otherwise strength reduce the shift into an and.
2589 uint64_t Val = ~0ULL; // All ones.
2590 Val <<= ShAmtVal; // Shift over to the right spot.
2591
2592 Constant *Mask;
2593 if (CI->getType()->isUnsigned()) {
2594 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
Chris Lattnercfe2822c2005-03-04 23:21:33 +00002595 if (TypeBits != 64)
2596 Val &= (1ULL << TypeBits)-1;
Chris Lattner1023b872004-09-27 16:18:50 +00002597 Mask = ConstantUInt::get(CI->getType(), Val);
2598 } else {
2599 Mask = ConstantSInt::get(CI->getType(), Val);
2600 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002601
Chris Lattner1023b872004-09-27 16:18:50 +00002602 Instruction *AndI =
2603 BinaryOperator::createAnd(LHSI->getOperand(0),
2604 Mask, LHSI->getName()+".mask");
2605 Value *And = InsertNewInstBefore(AndI, I);
2606 return new SetCondInst(I.getOpcode(), And,
2607 ConstantExpr::getShl(CI, ShAmt));
2608 }
2609 break;
2610 }
2611 }
2612 }
2613 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002614
Chris Lattner6862fbd2004-09-29 17:40:11 +00002615 case Instruction::Div:
2616 // Fold: (div X, C1) op C2 -> range check
2617 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2618 // Fold this div into the comparison, producing a range check.
2619 // Determine, based on the divide type, what the range is being
2620 // checked. If there is an overflow on the low or high side, remember
2621 // it, otherwise compute the range [low, hi) bounding the new value.
2622 bool LoOverflow = false, HiOverflow = 0;
2623 ConstantInt *LoBound = 0, *HiBound = 0;
2624
2625 ConstantInt *Prod;
2626 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2627
Chris Lattnera92af962004-10-11 19:40:04 +00002628 Instruction::BinaryOps Opcode = I.getOpcode();
2629
Chris Lattner6862fbd2004-09-29 17:40:11 +00002630 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2631 } else if (LHSI->getType()->isUnsigned()) { // udiv
2632 LoBound = Prod;
2633 LoOverflow = ProdOV;
2634 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2635 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2636 if (CI->isNullValue()) { // (X / pos) op 0
2637 // Can't overflow.
2638 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2639 HiBound = DivRHS;
2640 } else if (isPositive(CI)) { // (X / pos) op pos
2641 LoBound = Prod;
2642 LoOverflow = ProdOV;
2643 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2644 } else { // (X / pos) op neg
2645 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2646 LoOverflow = AddWithOverflow(LoBound, Prod,
2647 cast<ConstantInt>(DivRHSH));
2648 HiBound = Prod;
2649 HiOverflow = ProdOV;
2650 }
2651 } else { // Divisor is < 0.
2652 if (CI->isNullValue()) { // (X / neg) op 0
2653 LoBound = AddOne(DivRHS);
2654 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2655 } else if (isPositive(CI)) { // (X / neg) op pos
2656 HiOverflow = LoOverflow = ProdOV;
2657 if (!LoOverflow)
2658 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2659 HiBound = AddOne(Prod);
2660 } else { // (X / neg) op neg
2661 LoBound = Prod;
2662 LoOverflow = HiOverflow = ProdOV;
2663 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2664 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002665
Chris Lattnera92af962004-10-11 19:40:04 +00002666 // Dividing by a negate swaps the condition.
2667 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002668 }
2669
2670 if (LoBound) {
2671 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002672 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002673 default: assert(0 && "Unhandled setcc opcode!");
2674 case Instruction::SetEQ:
2675 if (LoOverflow && HiOverflow)
2676 return ReplaceInstUsesWith(I, ConstantBool::False);
2677 else if (HiOverflow)
2678 return new SetCondInst(Instruction::SetGE, X, LoBound);
2679 else if (LoOverflow)
2680 return new SetCondInst(Instruction::SetLT, X, HiBound);
2681 else
2682 return InsertRangeTest(X, LoBound, HiBound, true, I);
2683 case Instruction::SetNE:
2684 if (LoOverflow && HiOverflow)
2685 return ReplaceInstUsesWith(I, ConstantBool::True);
2686 else if (HiOverflow)
2687 return new SetCondInst(Instruction::SetLT, X, LoBound);
2688 else if (LoOverflow)
2689 return new SetCondInst(Instruction::SetGE, X, HiBound);
2690 else
2691 return InsertRangeTest(X, LoBound, HiBound, false, I);
2692 case Instruction::SetLT:
2693 if (LoOverflow)
2694 return ReplaceInstUsesWith(I, ConstantBool::False);
2695 return new SetCondInst(Instruction::SetLT, X, LoBound);
2696 case Instruction::SetGT:
2697 if (HiOverflow)
2698 return ReplaceInstUsesWith(I, ConstantBool::False);
2699 return new SetCondInst(Instruction::SetGE, X, HiBound);
2700 }
2701 }
2702 }
2703 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002704 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002705
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002706 // Simplify seteq and setne instructions...
2707 if (I.getOpcode() == Instruction::SetEQ ||
2708 I.getOpcode() == Instruction::SetNE) {
2709 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2710
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002711 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002712 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002713 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2714 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002715 case Instruction::Rem:
2716 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2717 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2718 BO->hasOneUse() &&
2719 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2720 if (unsigned L2 =
2721 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2722 const Type *UTy = BO->getType()->getUnsignedVersion();
2723 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2724 UTy, "tmp"), I);
2725 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2726 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2727 RHSCst, BO->getName()), I);
2728 return BinaryOperator::create(I.getOpcode(), NewRem,
2729 Constant::getNullValue(UTy));
2730 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002731 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00002732
Chris Lattnerc992add2003-08-13 05:33:12 +00002733 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002734 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2735 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002736 if (BO->hasOneUse())
2737 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2738 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002739 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002740 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2741 // efficiently invertible, or if the add has just this one use.
2742 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002743
Chris Lattnerc992add2003-08-13 05:33:12 +00002744 if (Value *NegVal = dyn_castNegVal(BOp1))
2745 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2746 else if (Value *NegVal = dyn_castNegVal(BOp0))
2747 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002748 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002749 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2750 BO->setName("");
2751 InsertNewInstBefore(Neg, I);
2752 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2753 }
2754 }
2755 break;
2756 case Instruction::Xor:
2757 // For the xor case, we can xor two constants together, eliminating
2758 // the explicit xor.
2759 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2760 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002761 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002762
2763 // FALLTHROUGH
2764 case Instruction::Sub:
2765 // Replace (([sub|xor] A, B) != 0) with (A != B)
2766 if (CI->isNullValue())
2767 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2768 BO->getOperand(1));
2769 break;
2770
2771 case Instruction::Or:
2772 // If bits are being or'd in that are not present in the constant we
2773 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002774 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002775 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002776 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002777 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002778 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002779 break;
2780
2781 case Instruction::And:
2782 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002783 // If bits are being compared against that are and'd out, then the
2784 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002785 if (!ConstantExpr::getAnd(CI,
2786 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002787 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002788
Chris Lattner35167c32004-06-09 07:59:58 +00002789 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002790 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002791 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2792 Instruction::SetNE, Op0,
2793 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002794
Chris Lattnerc992add2003-08-13 05:33:12 +00002795 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2796 // to be a signed value as appropriate.
2797 if (isSignBit(BOC)) {
2798 Value *X = BO->getOperand(0);
2799 // If 'X' is not signed, insert a cast now...
2800 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002801 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002802 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002803 }
2804 return new SetCondInst(isSetNE ? Instruction::SetLT :
2805 Instruction::SetGE, X,
2806 Constant::getNullValue(X->getType()));
2807 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002808
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002809 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002810 if (CI->isNullValue() && isHighOnes(BOC)) {
2811 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002812 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002813
2814 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002815 if (NegX->getType()->isSigned()) {
2816 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2817 X = InsertCastBefore(X, DestTy, I);
2818 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002819 }
2820
2821 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002822 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002823 }
2824
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002825 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002826 default: break;
2827 }
2828 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002829 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00002830 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002831 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2832 Value *CastOp = Cast->getOperand(0);
2833 const Type *SrcTy = CastOp->getType();
2834 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2835 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2836 SrcTySize == Cast->getType()->getPrimitiveSize()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002837 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00002838 "Source and destination signednesses should differ!");
2839 if (Cast->getType()->isSigned()) {
2840 // If this is a signed comparison, check for comparisons in the
2841 // vicinity of zero.
2842 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2843 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002844 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002845 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2846 else if (I.getOpcode() == Instruction::SetGT &&
2847 cast<ConstantSInt>(CI)->getValue() == -1)
2848 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002849 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002850 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2851 } else {
2852 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2853 if (I.getOpcode() == Instruction::SetLT &&
2854 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2855 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002856 return BinaryOperator::createSetGT(CastOp,
2857 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002858 else if (I.getOpcode() == Instruction::SetGT &&
2859 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2860 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002861 return BinaryOperator::createSetLT(CastOp,
2862 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002863 }
2864 }
2865 }
Chris Lattnere967b342003-06-04 05:10:11 +00002866 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002867 }
2868
Chris Lattner77c32c32005-04-23 15:31:55 +00002869 // Handle setcc with constant RHS's that can be integer, FP or pointer.
2870 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2871 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2872 switch (LHSI->getOpcode()) {
2873 case Instruction::PHI:
2874 if (Instruction *NV = FoldOpIntoPhi(I))
2875 return NV;
2876 break;
2877 case Instruction::Select:
2878 // If either operand of the select is a constant, we can fold the
2879 // comparison into the select arms, which will cause one to be
2880 // constant folded and the select turned into a bitwise or.
2881 Value *Op1 = 0, *Op2 = 0;
2882 if (LHSI->hasOneUse()) {
2883 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2884 // Fold the known value into the constant operand.
2885 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
2886 // Insert a new SetCC of the other select operand.
2887 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2888 LHSI->getOperand(2), RHSC,
2889 I.getName()), I);
2890 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2891 // Fold the known value into the constant operand.
2892 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
2893 // Insert a new SetCC of the other select operand.
2894 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2895 LHSI->getOperand(1), RHSC,
2896 I.getName()), I);
2897 }
2898 }
Jeff Cohen82639852005-04-23 21:38:35 +00002899
Chris Lattner77c32c32005-04-23 15:31:55 +00002900 if (Op1)
2901 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2902 break;
2903 }
2904 }
2905
Chris Lattner0798af32005-01-13 20:14:25 +00002906 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
2907 if (User *GEP = dyn_castGetElementPtr(Op0))
2908 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
2909 return NI;
2910 if (User *GEP = dyn_castGetElementPtr(Op1))
2911 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
2912 SetCondInst::getSwappedCondition(I.getOpcode()), I))
2913 return NI;
2914
Chris Lattner16930792003-11-03 04:25:02 +00002915 // Test to see if the operands of the setcc are casted versions of other
2916 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002917 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2918 Value *CastOp0 = CI->getOperand(0);
2919 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002920 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002921 (I.getOpcode() == Instruction::SetEQ ||
2922 I.getOpcode() == Instruction::SetNE)) {
2923 // We keep moving the cast from the left operand over to the right
2924 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002925 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002926
Chris Lattner16930792003-11-03 04:25:02 +00002927 // If operand #1 is a cast instruction, see if we can eliminate it as
2928 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002929 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2930 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002931 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002932 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002933
Chris Lattner16930792003-11-03 04:25:02 +00002934 // If Op1 is a constant, we can fold the cast into the constant.
2935 if (Op1->getType() != Op0->getType())
2936 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2937 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2938 } else {
2939 // Otherwise, cast the RHS right before the setcc
2940 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2941 InsertNewInstBefore(cast<Instruction>(Op1), I);
2942 }
2943 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2944 }
2945
Chris Lattner6444c372003-11-03 05:17:03 +00002946 // Handle the special case of: setcc (cast bool to X), <cst>
2947 // This comes up when you have code like
2948 // int X = A < B;
2949 // if (X) ...
2950 // For generality, we handle any zero-extension of any operand comparison
2951 // with a constant.
2952 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2953 const Type *SrcTy = CastOp0->getType();
2954 const Type *DestTy = Op0->getType();
2955 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2956 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2957 // Ok, we have an expansion of operand 0 into a new type. Get the
2958 // constant value, masink off bits which are not set in the RHS. These
2959 // could be set if the destination value is signed.
2960 uint64_t ConstVal = ConstantRHS->getRawValue();
2961 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2962
2963 // If the constant we are comparing it with has high bits set, which
2964 // don't exist in the original value, the values could never be equal,
2965 // because the source would be zero extended.
2966 unsigned SrcBits =
2967 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002968 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2969 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002970 switch (I.getOpcode()) {
2971 default: assert(0 && "Unknown comparison type!");
2972 case Instruction::SetEQ:
2973 return ReplaceInstUsesWith(I, ConstantBool::False);
2974 case Instruction::SetNE:
2975 return ReplaceInstUsesWith(I, ConstantBool::True);
2976 case Instruction::SetLT:
2977 case Instruction::SetLE:
2978 if (DestTy->isSigned() && HasSignBit)
2979 return ReplaceInstUsesWith(I, ConstantBool::False);
2980 return ReplaceInstUsesWith(I, ConstantBool::True);
2981 case Instruction::SetGT:
2982 case Instruction::SetGE:
2983 if (DestTy->isSigned() && HasSignBit)
2984 return ReplaceInstUsesWith(I, ConstantBool::True);
2985 return ReplaceInstUsesWith(I, ConstantBool::False);
2986 }
2987 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002988
Chris Lattner6444c372003-11-03 05:17:03 +00002989 // Otherwise, we can replace the setcc with a setcc of the smaller
2990 // operand value.
2991 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2992 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2993 }
2994 }
2995 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002996 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002997}
2998
Misha Brukmanb1c93172005-04-21 23:48:37 +00002999// visitSetCondInstWithCastAndConstant - this method is part of the
Reid Spencer279fa252004-11-28 21:31:15 +00003000// visitSetCondInst method. It handles the situation where we have:
3001// (setcc (cast X to larger), CI)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003002// It tries to remove the cast and even the setcc if the CI value
Reid Spencer279fa252004-11-28 21:31:15 +00003003// and range of the cast allow it.
3004Instruction *
3005InstCombiner::visitSetCondInstWithCastAndConstant(BinaryOperator&I,
3006 CastInst* LHSI,
3007 ConstantInt* CI) {
3008 const Type *SrcTy = LHSI->getOperand(0)->getType();
3009 const Type *DestTy = LHSI->getType();
Chris Lattner03f06f12005-01-17 03:20:02 +00003010 if (!SrcTy->isIntegral() || !DestTy->isIntegral())
3011 return 0;
3012
3013 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
3014 unsigned DestBits = DestTy->getPrimitiveSize()*8;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003015 if (SrcTy == Type::BoolTy)
Chris Lattner03f06f12005-01-17 03:20:02 +00003016 SrcBits = 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003017 if (DestTy == Type::BoolTy)
Chris Lattner03f06f12005-01-17 03:20:02 +00003018 DestBits = 1;
3019 if (SrcBits < DestBits) {
3020 // There are fewer bits in the source of the cast than in the result
3021 // of the cast. Any other case doesn't matter because the constant
3022 // value won't have changed due to sign extension.
3023 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
3024 if (ConstantExpr::getCast(NewCst, DestTy) == CI) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003025 // The constant value operand of the setCC before and after a
3026 // cast to the source type of the cast instruction is the same
3027 // value, so we just replace with the same setcc opcode, but
3028 // using the source value compared to the constant casted to the
3029 // source type.
Chris Lattner03f06f12005-01-17 03:20:02 +00003030 if (SrcTy->isSigned() && DestTy->isUnsigned()) {
3031 CastInst* Cst = new CastInst(LHSI->getOperand(0),
3032 SrcTy->getUnsignedVersion(),
3033 LHSI->getName());
3034 InsertNewInstBefore(Cst,I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003035 return new SetCondInst(I.getOpcode(), Cst,
Chris Lattner03f06f12005-01-17 03:20:02 +00003036 ConstantExpr::getCast(CI,
3037 SrcTy->getUnsignedVersion()));
Reid Spencer279fa252004-11-28 21:31:15 +00003038 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003039 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),NewCst);
3040 }
3041
Misha Brukmanb1c93172005-04-21 23:48:37 +00003042 // The constant value before and after a cast to the source type
3043 // is different, so various cases are possible depending on the
Chris Lattner03f06f12005-01-17 03:20:02 +00003044 // opcode and the signs of the types involved in the cast.
3045 switch (I.getOpcode()) {
3046 case Instruction::SetLT: {
3047 return 0;
3048 Constant* Max = ConstantIntegral::getMaxValue(SrcTy);
3049 Max = ConstantExpr::getCast(Max, DestTy);
3050 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
3051 }
3052 case Instruction::SetGT: {
3053 return 0; // FIXME! RENABLE. This breaks for (cast sbyte to uint) > 255
3054 Constant* Min = ConstantIntegral::getMinValue(SrcTy);
3055 Min = ConstantExpr::getCast(Min, DestTy);
3056 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
3057 }
3058 case Instruction::SetEQ:
3059 // We're looking for equality, and we know the values are not
3060 // equal so replace with constant False.
3061 return ReplaceInstUsesWith(I, ConstantBool::False);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003062 case Instruction::SetNE:
Chris Lattner03f06f12005-01-17 03:20:02 +00003063 // We're testing for inequality, and we know the values are not
3064 // equal so replace with constant True.
3065 return ReplaceInstUsesWith(I, ConstantBool::True);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003066 case Instruction::SetLE:
3067 case Instruction::SetGE:
Chris Lattner03f06f12005-01-17 03:20:02 +00003068 assert(0 && "SetLE and SetGE should be handled elsewhere");
Misha Brukmanb1c93172005-04-21 23:48:37 +00003069 default:
Chris Lattner03f06f12005-01-17 03:20:02 +00003070 assert(0 && "unknown integer comparison");
Reid Spencer279fa252004-11-28 21:31:15 +00003071 }
3072 }
3073 return 0;
3074}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003075
3076
Chris Lattnere8d6c602003-03-10 19:16:08 +00003077Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003078 assert(I.getOperand(1)->getType() == Type::UByteTy);
3079 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003080 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003081
3082 // shl X, 0 == X and shr X, 0 == X
3083 // shl 0, X == 0 and shr 0, X == 0
3084 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003085 Op0 == Constant::getNullValue(Op0->getType()))
3086 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003087
Chris Lattner81a7a232004-10-16 18:11:37 +00003088 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3089 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003090 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003091 else // undef << X -> 0 AND undef >>u X -> 0
3092 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3093 }
3094 if (isa<UndefValue>(Op1)) {
3095 if (isLeftShift || I.getType()->isUnsigned())
3096 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3097 else
3098 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3099 }
3100
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003101 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3102 if (!isLeftShift)
3103 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3104 if (CSI->isAllOnesValue())
3105 return ReplaceInstUsesWith(I, CSI);
3106
Chris Lattner183b3362004-04-09 19:05:30 +00003107 // Try to fold constant and into select arguments.
3108 if (isa<Constant>(Op0))
3109 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003110 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003111 return R;
3112
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003113 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003114 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3115 // of a signed value.
3116 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00003117 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003118 if (CUI->getValue() >= TypeBits) {
3119 if (!Op0->getType()->isSigned() || isLeftShift)
3120 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3121 else {
3122 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3123 return &I;
3124 }
3125 }
Chris Lattner55f3d942002-09-10 23:04:09 +00003126
Chris Lattnerede3fe02003-08-13 04:18:28 +00003127 // ((X*C1) << C2) == (X * (C1 << C2))
3128 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3129 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3130 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003131 return BinaryOperator::createMul(BO->getOperand(0),
3132 ConstantExpr::getShl(BOOp, CUI));
Misha Brukmanb1c93172005-04-21 23:48:37 +00003133
Chris Lattner183b3362004-04-09 19:05:30 +00003134 // Try to fold constant and into select arguments.
3135 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003136 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003137 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003138 if (isa<PHINode>(Op0))
3139 if (Instruction *NV = FoldOpIntoPhi(I))
3140 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00003141
Chris Lattner86102b82005-01-01 16:22:27 +00003142 if (Op0->hasOneUse()) {
3143 // If this is a SHL of a sign-extending cast, see if we can turn the input
3144 // into a zero extending cast (a simple strength reduction).
3145 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3146 const Type *SrcTy = CI->getOperand(0)->getType();
3147 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3148 SrcTy->getPrimitiveSize() < CI->getType()->getPrimitiveSize()) {
3149 // We can change it to a zero extension if we are shifting out all of
3150 // the sign extended bits. To check this, form a mask of all of the
3151 // sign extend bits, then shift them left and see if we have anything
3152 // left.
3153 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3154 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3155 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3156 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3157 // If the shift is nuking all of the sign bits, change this to a
3158 // zero extension cast. To do this, cast the cast input to
3159 // unsigned, then to the requested size.
3160 Value *CastOp = CI->getOperand(0);
3161 Instruction *NC =
3162 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3163 CI->getName()+".uns");
3164 NC = InsertNewInstBefore(NC, I);
3165 // Finally, insert a replacement for CI.
3166 NC = new CastInst(NC, CI->getType(), CI->getName());
3167 CI->setName("");
3168 NC = InsertNewInstBefore(NC, I);
3169 WorkList.push_back(CI); // Delete CI later.
3170 I.setOperand(0, NC);
3171 return &I; // The SHL operand was modified.
3172 }
3173 }
3174 }
3175
3176 // If the operand is an bitwise operator with a constant RHS, and the
3177 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003178 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
3179 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3180 bool isValid = true; // Valid only for And, Or, Xor
3181 bool highBitSet = false; // Transform if high bit of constant set?
3182
3183 switch (Op0BO->getOpcode()) {
3184 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003185 case Instruction::Add:
3186 isValid = isLeftShift;
3187 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003188 case Instruction::Or:
3189 case Instruction::Xor:
3190 highBitSet = false;
3191 break;
3192 case Instruction::And:
3193 highBitSet = true;
3194 break;
3195 }
3196
3197 // If this is a signed shift right, and the high bit is modified
3198 // by the logical operation, do not perform the transformation.
3199 // The highBitSet boolean indicates the value of the high bit of
3200 // the constant which would cause it to be modified for this
3201 // operation.
3202 //
3203 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3204 uint64_t Val = Op0C->getRawValue();
3205 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3206 }
3207
3208 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003209 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003210
3211 Instruction *NewShift =
3212 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3213 Op0BO->getName());
3214 Op0BO->setName("");
3215 InsertNewInstBefore(NewShift, I);
3216
3217 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3218 NewRHS);
3219 }
3220 }
Chris Lattner86102b82005-01-01 16:22:27 +00003221 }
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003222
Chris Lattner3204d4e2003-07-24 17:52:58 +00003223 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003224 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00003225 if (ConstantUInt *ShiftAmt1C =
3226 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003227 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3228 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003229
Chris Lattner3204d4e2003-07-24 17:52:58 +00003230 // Check for (A << c1) << c2 and (A >> c1) >> c2
3231 if (I.getOpcode() == Op0SI->getOpcode()) {
3232 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003233 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
3234 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00003235 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3236 ConstantUInt::get(Type::UByteTy, Amt));
3237 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003238
Chris Lattnerab780df2003-07-24 18:38:56 +00003239 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3240 // signed types, we can only support the (A >> c1) << c2 configuration,
3241 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003242 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003243 // Calculate bitmask for what gets shifted off the edge...
3244 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003245 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003246 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003247 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003248 C = ConstantExpr::getShr(C, ShiftAmt1C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003249
Chris Lattner3204d4e2003-07-24 17:52:58 +00003250 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003251 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3252 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00003253 InsertNewInstBefore(Mask, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003254
Chris Lattner3204d4e2003-07-24 17:52:58 +00003255 // Figure out what flavor of shift we should use...
3256 if (ShiftAmt1 == ShiftAmt2)
3257 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3258 else if (ShiftAmt1 < ShiftAmt2) {
3259 return new ShiftInst(I.getOpcode(), Mask,
3260 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3261 } else {
3262 return new ShiftInst(Op0SI->getOpcode(), Mask,
3263 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3264 }
3265 }
3266 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003267 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00003268
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003269 return 0;
3270}
3271
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003272enum CastType {
3273 Noop = 0,
3274 Truncate = 1,
3275 Signext = 2,
3276 Zeroext = 3
3277};
3278
3279/// getCastType - In the future, we will split the cast instruction into these
3280/// various types. Until then, we have to do the analysis here.
3281static CastType getCastType(const Type *Src, const Type *Dest) {
3282 assert(Src->isIntegral() && Dest->isIntegral() &&
3283 "Only works on integral types!");
3284 unsigned SrcSize = Src->getPrimitiveSize()*8;
3285 if (Src == Type::BoolTy) SrcSize = 1;
3286 unsigned DestSize = Dest->getPrimitiveSize()*8;
3287 if (Dest == Type::BoolTy) DestSize = 1;
3288
3289 if (SrcSize == DestSize) return Noop;
3290 if (SrcSize > DestSize) return Truncate;
3291 if (Src->isSigned()) return Signext;
3292 return Zeroext;
3293}
3294
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003295
Chris Lattner48a44f72002-05-02 17:06:02 +00003296// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3297// instruction.
3298//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003299static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00003300 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003301
Chris Lattner650b6da2002-08-02 20:00:25 +00003302 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00003303 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003304 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003305 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003306 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003307
Chris Lattner4fbad962004-07-21 04:27:24 +00003308 // If we are casting between pointer and integer types, treat pointers as
3309 // integers of the appropriate size for the code below.
3310 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3311 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3312 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003313
Chris Lattner48a44f72002-05-02 17:06:02 +00003314 // Allow free casting and conversion of sizes as long as the sign doesn't
3315 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003316 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003317 CastType FirstCast = getCastType(SrcTy, MidTy);
3318 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003319
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003320 // Capture the effect of these two casts. If the result is a legal cast,
3321 // the CastType is stored here, otherwise a special code is used.
3322 static const unsigned CastResult[] = {
3323 // First cast is noop
3324 0, 1, 2, 3,
3325 // First cast is a truncate
3326 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3327 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003328 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003329 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003330 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003331 };
3332
3333 unsigned Result = CastResult[FirstCast*4+SecondCast];
3334 switch (Result) {
3335 default: assert(0 && "Illegal table value!");
3336 case 0:
3337 case 1:
3338 case 2:
3339 case 3:
3340 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3341 // truncates, we could eliminate more casts.
3342 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3343 case 4:
3344 return false; // Not possible to eliminate this here.
3345 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00003346 // Sign or zero extend followed by truncate is always ok if the result
3347 // is a truncate or noop.
3348 CastType ResultCast = getCastType(SrcTy, DstTy);
3349 if (ResultCast == Noop || ResultCast == Truncate)
3350 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003351 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00003352 // result will match the sign/zeroextendness of the result.
3353 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00003354 }
Chris Lattner650b6da2002-08-02 20:00:25 +00003355 }
Chris Lattner48a44f72002-05-02 17:06:02 +00003356 return false;
3357}
3358
Chris Lattner11ffd592004-07-20 05:21:00 +00003359static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003360 if (V->getType() == Ty || isa<Constant>(V)) return false;
3361 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00003362 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3363 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003364 return false;
3365 return true;
3366}
3367
3368/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3369/// InsertBefore instruction. This is specialized a bit to avoid inserting
3370/// casts that are known to not do anything...
3371///
3372Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3373 Instruction *InsertBefore) {
3374 if (V->getType() == DestTy) return V;
3375 if (Constant *C = dyn_cast<Constant>(V))
3376 return ConstantExpr::getCast(C, DestTy);
3377
3378 CastInst *CI = new CastInst(V, DestTy, V->getName());
3379 InsertNewInstBefore(CI, *InsertBefore);
3380 return CI;
3381}
Chris Lattner48a44f72002-05-02 17:06:02 +00003382
3383// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00003384//
Chris Lattner113f4f42002-06-25 16:13:24 +00003385Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00003386 Value *Src = CI.getOperand(0);
3387
Chris Lattner48a44f72002-05-02 17:06:02 +00003388 // If the user is casting a value to the same type, eliminate this cast
3389 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00003390 if (CI.getType() == Src->getType())
3391 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00003392
Chris Lattner81a7a232004-10-16 18:11:37 +00003393 if (isa<UndefValue>(Src)) // cast undef -> undef
3394 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3395
Chris Lattner48a44f72002-05-02 17:06:02 +00003396 // If casting the result of another cast instruction, try to eliminate this
3397 // one!
3398 //
Chris Lattner86102b82005-01-01 16:22:27 +00003399 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3400 Value *A = CSrc->getOperand(0);
3401 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3402 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003403 // This instruction now refers directly to the cast's src operand. This
3404 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00003405 CI.setOperand(0, CSrc->getOperand(0));
3406 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00003407 }
3408
Chris Lattner650b6da2002-08-02 20:00:25 +00003409 // If this is an A->B->A cast, and we are dealing with integral types, try
3410 // to convert this into a logical 'and' instruction.
3411 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00003412 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003413 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00003414 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
3415 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()&&
3416 A->getType()->getPrimitiveSize() == CI.getType()->getPrimitiveSize()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00003417 assert(CSrc->getType() != Type::ULongTy &&
3418 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00003419 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner86102b82005-01-01 16:22:27 +00003420 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3421 AndValue);
3422 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3423 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3424 if (And->getType() != CI.getType()) {
3425 And->setName(CSrc->getName()+".mask");
3426 InsertNewInstBefore(And, CI);
3427 And = new CastInst(And, CI.getType());
3428 }
3429 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00003430 }
3431 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003432
Chris Lattner03841652004-05-25 04:29:21 +00003433 // If this is a cast to bool, turn it into the appropriate setne instruction.
3434 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003435 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00003436 Constant::getNullValue(CI.getOperand(0)->getType()));
3437
Chris Lattnerd0d51602003-06-21 23:12:02 +00003438 // If casting the result of a getelementptr instruction with no offset, turn
3439 // this into a cast of the original pointer!
3440 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00003441 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00003442 bool AllZeroOperands = true;
3443 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3444 if (!isa<Constant>(GEP->getOperand(i)) ||
3445 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3446 AllZeroOperands = false;
3447 break;
3448 }
3449 if (AllZeroOperands) {
3450 CI.setOperand(0, GEP->getOperand(0));
3451 return &CI;
3452 }
3453 }
3454
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003455 // If we are casting a malloc or alloca to a pointer to a type of the same
3456 // size, rewrite the allocation instruction to allocate the "right" type.
3457 //
3458 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00003459 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003460 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
3461 // Get the type really allocated and the type casted to...
3462 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003463 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003464 if (AllocElTy->isSized() && CastElTy->isSized()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003465 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3466 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00003467
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003468 // If the allocation is for an even multiple of the cast type size
3469 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003470 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003471 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003472 std::string Name = AI->getName(); AI->setName("");
3473 AllocationInst *New;
3474 if (isa<MallocInst>(AI))
3475 New = new MallocInst(CastElTy, Amt, Name);
3476 else
3477 New = new AllocaInst(CastElTy, Amt, Name);
3478 InsertNewInstBefore(New, *AI);
3479 return ReplaceInstUsesWith(CI, New);
3480 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003481 }
3482 }
3483
Chris Lattner86102b82005-01-01 16:22:27 +00003484 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
3485 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
3486 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003487 if (isa<PHINode>(Src))
3488 if (Instruction *NV = FoldOpIntoPhi(CI))
3489 return NV;
3490
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003491 // If the source value is an instruction with only this use, we can attempt to
3492 // propagate the cast into the instruction. Also, only handle integral types
3493 // for now.
3494 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003495 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003496 CI.getType()->isInteger()) { // Don't mess with casts to bool here
3497 const Type *DestTy = CI.getType();
3498 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
3499 unsigned DestBitSize = getTypeSizeInBits(DestTy);
3500
3501 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3502 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3503
3504 switch (SrcI->getOpcode()) {
3505 case Instruction::Add:
3506 case Instruction::Mul:
3507 case Instruction::And:
3508 case Instruction::Or:
3509 case Instruction::Xor:
3510 // If we are discarding information, or just changing the sign, rewrite.
3511 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3512 // Don't insert two casts if they cannot be eliminated. We allow two
3513 // casts to be inserted if the sizes are the same. This could only be
3514 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00003515 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3516 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003517 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3518 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3519 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3520 ->getOpcode(), Op0c, Op1c);
3521 }
3522 }
3523 break;
3524 case Instruction::Shl:
3525 // Allow changing the sign of the source operand. Do not allow changing
3526 // the size of the shift, UNLESS the shift amount is a constant. We
3527 // mush not change variable sized shifts to a smaller size, because it
3528 // is undefined to shift more bits out than exist in the value.
3529 if (DestBitSize == SrcBitSize ||
3530 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3531 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3532 return new ShiftInst(Instruction::Shl, Op0c, Op1);
3533 }
3534 break;
3535 }
3536 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003537
Chris Lattner260ab202002-04-18 17:39:14 +00003538 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00003539}
3540
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003541/// GetSelectFoldableOperands - We want to turn code that looks like this:
3542/// %C = or %A, %B
3543/// %D = select %cond, %C, %A
3544/// into:
3545/// %C = select %cond, %B, 0
3546/// %D = or %A, %C
3547///
3548/// Assuming that the specified instruction is an operand to the select, return
3549/// a bitmask indicating which operands of this instruction are foldable if they
3550/// equal the other incoming value of the select.
3551///
3552static unsigned GetSelectFoldableOperands(Instruction *I) {
3553 switch (I->getOpcode()) {
3554 case Instruction::Add:
3555 case Instruction::Mul:
3556 case Instruction::And:
3557 case Instruction::Or:
3558 case Instruction::Xor:
3559 return 3; // Can fold through either operand.
3560 case Instruction::Sub: // Can only fold on the amount subtracted.
3561 case Instruction::Shl: // Can only fold on the shift amount.
3562 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00003563 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003564 default:
3565 return 0; // Cannot fold
3566 }
3567}
3568
3569/// GetSelectFoldableConstant - For the same transformation as the previous
3570/// function, return the identity constant that goes into the select.
3571static Constant *GetSelectFoldableConstant(Instruction *I) {
3572 switch (I->getOpcode()) {
3573 default: assert(0 && "This cannot happen!"); abort();
3574 case Instruction::Add:
3575 case Instruction::Sub:
3576 case Instruction::Or:
3577 case Instruction::Xor:
3578 return Constant::getNullValue(I->getType());
3579 case Instruction::Shl:
3580 case Instruction::Shr:
3581 return Constant::getNullValue(Type::UByteTy);
3582 case Instruction::And:
3583 return ConstantInt::getAllOnesValue(I->getType());
3584 case Instruction::Mul:
3585 return ConstantInt::get(I->getType(), 1);
3586 }
3587}
3588
Chris Lattner411336f2005-01-19 21:50:18 +00003589/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
3590/// have the same opcode and only one use each. Try to simplify this.
3591Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
3592 Instruction *FI) {
3593 if (TI->getNumOperands() == 1) {
3594 // If this is a non-volatile load or a cast from the same type,
3595 // merge.
3596 if (TI->getOpcode() == Instruction::Cast) {
3597 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
3598 return 0;
3599 } else {
3600 return 0; // unknown unary op.
3601 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003602
Chris Lattner411336f2005-01-19 21:50:18 +00003603 // Fold this by inserting a select from the input values.
3604 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
3605 FI->getOperand(0), SI.getName()+".v");
3606 InsertNewInstBefore(NewSI, SI);
3607 return new CastInst(NewSI, TI->getType());
3608 }
3609
3610 // Only handle binary operators here.
3611 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
3612 return 0;
3613
3614 // Figure out if the operations have any operands in common.
3615 Value *MatchOp, *OtherOpT, *OtherOpF;
3616 bool MatchIsOpZero;
3617 if (TI->getOperand(0) == FI->getOperand(0)) {
3618 MatchOp = TI->getOperand(0);
3619 OtherOpT = TI->getOperand(1);
3620 OtherOpF = FI->getOperand(1);
3621 MatchIsOpZero = true;
3622 } else if (TI->getOperand(1) == FI->getOperand(1)) {
3623 MatchOp = TI->getOperand(1);
3624 OtherOpT = TI->getOperand(0);
3625 OtherOpF = FI->getOperand(0);
3626 MatchIsOpZero = false;
3627 } else if (!TI->isCommutative()) {
3628 return 0;
3629 } else if (TI->getOperand(0) == FI->getOperand(1)) {
3630 MatchOp = TI->getOperand(0);
3631 OtherOpT = TI->getOperand(1);
3632 OtherOpF = FI->getOperand(0);
3633 MatchIsOpZero = true;
3634 } else if (TI->getOperand(1) == FI->getOperand(0)) {
3635 MatchOp = TI->getOperand(1);
3636 OtherOpT = TI->getOperand(0);
3637 OtherOpF = FI->getOperand(1);
3638 MatchIsOpZero = true;
3639 } else {
3640 return 0;
3641 }
3642
3643 // If we reach here, they do have operations in common.
3644 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
3645 OtherOpF, SI.getName()+".v");
3646 InsertNewInstBefore(NewSI, SI);
3647
3648 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
3649 if (MatchIsOpZero)
3650 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
3651 else
3652 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
3653 } else {
3654 if (MatchIsOpZero)
3655 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
3656 else
3657 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
3658 }
3659}
3660
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003661Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00003662 Value *CondVal = SI.getCondition();
3663 Value *TrueVal = SI.getTrueValue();
3664 Value *FalseVal = SI.getFalseValue();
3665
3666 // select true, X, Y -> X
3667 // select false, X, Y -> Y
3668 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003669 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00003670 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003671 else {
3672 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00003673 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003674 }
Chris Lattner533bc492004-03-30 19:37:13 +00003675
3676 // select C, X, X -> X
3677 if (TrueVal == FalseVal)
3678 return ReplaceInstUsesWith(SI, TrueVal);
3679
Chris Lattner81a7a232004-10-16 18:11:37 +00003680 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3681 return ReplaceInstUsesWith(SI, FalseVal);
3682 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3683 return ReplaceInstUsesWith(SI, TrueVal);
3684 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3685 if (isa<Constant>(TrueVal))
3686 return ReplaceInstUsesWith(SI, TrueVal);
3687 else
3688 return ReplaceInstUsesWith(SI, FalseVal);
3689 }
3690
Chris Lattner1c631e82004-04-08 04:43:23 +00003691 if (SI.getType() == Type::BoolTy)
3692 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3693 if (C == ConstantBool::True) {
3694 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003695 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003696 } else {
3697 // Change: A = select B, false, C --> A = and !B, C
3698 Value *NotCond =
3699 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3700 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003701 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003702 }
3703 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3704 if (C == ConstantBool::False) {
3705 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003706 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003707 } else {
3708 // Change: A = select B, C, true --> A = or !B, C
3709 Value *NotCond =
3710 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3711 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003712 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003713 }
3714 }
3715
Chris Lattner183b3362004-04-09 19:05:30 +00003716 // Selecting between two integer constants?
3717 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3718 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3719 // select C, 1, 0 -> cast C to int
3720 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3721 return new CastInst(CondVal, SI.getType());
3722 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3723 // select C, 0, 1 -> cast !C to int
3724 Value *NotCond =
3725 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00003726 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00003727 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00003728 }
Chris Lattner35167c32004-06-09 07:59:58 +00003729
3730 // If one of the constants is zero (we know they can't both be) and we
3731 // have a setcc instruction with zero, and we have an 'and' with the
3732 // non-constant value, eliminate this whole mess. This corresponds to
3733 // cases like this: ((X & 27) ? 27 : 0)
3734 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3735 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3736 if ((IC->getOpcode() == Instruction::SetEQ ||
3737 IC->getOpcode() == Instruction::SetNE) &&
3738 isa<ConstantInt>(IC->getOperand(1)) &&
3739 cast<Constant>(IC->getOperand(1))->isNullValue())
3740 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3741 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00003742 isa<ConstantInt>(ICA->getOperand(1)) &&
3743 (ICA->getOperand(1) == TrueValC ||
3744 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00003745 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3746 // Okay, now we know that everything is set up, we just don't
3747 // know whether we have a setne or seteq and whether the true or
3748 // false val is the zero.
3749 bool ShouldNotVal = !TrueValC->isNullValue();
3750 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3751 Value *V = ICA;
3752 if (ShouldNotVal)
3753 V = InsertNewInstBefore(BinaryOperator::create(
3754 Instruction::Xor, V, ICA->getOperand(1)), SI);
3755 return ReplaceInstUsesWith(SI, V);
3756 }
Chris Lattner533bc492004-03-30 19:37:13 +00003757 }
Chris Lattner623fba12004-04-10 22:21:27 +00003758
3759 // See if we are selecting two values based on a comparison of the two values.
3760 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3761 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3762 // Transform (X == Y) ? X : Y -> Y
3763 if (SCI->getOpcode() == Instruction::SetEQ)
3764 return ReplaceInstUsesWith(SI, FalseVal);
3765 // Transform (X != Y) ? X : Y -> X
3766 if (SCI->getOpcode() == Instruction::SetNE)
3767 return ReplaceInstUsesWith(SI, TrueVal);
3768 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3769
3770 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3771 // Transform (X == Y) ? Y : X -> X
3772 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003773 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003774 // Transform (X != Y) ? Y : X -> Y
3775 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003776 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003777 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3778 }
3779 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003780
Chris Lattnera04c9042005-01-13 22:52:24 +00003781 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
3782 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
3783 if (TI->hasOneUse() && FI->hasOneUse()) {
3784 bool isInverse = false;
3785 Instruction *AddOp = 0, *SubOp = 0;
3786
Chris Lattner411336f2005-01-19 21:50:18 +00003787 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
3788 if (TI->getOpcode() == FI->getOpcode())
3789 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
3790 return IV;
3791
3792 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
3793 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00003794 if (TI->getOpcode() == Instruction::Sub &&
3795 FI->getOpcode() == Instruction::Add) {
3796 AddOp = FI; SubOp = TI;
3797 } else if (FI->getOpcode() == Instruction::Sub &&
3798 TI->getOpcode() == Instruction::Add) {
3799 AddOp = TI; SubOp = FI;
3800 }
3801
3802 if (AddOp) {
3803 Value *OtherAddOp = 0;
3804 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
3805 OtherAddOp = AddOp->getOperand(1);
3806 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
3807 OtherAddOp = AddOp->getOperand(0);
3808 }
3809
3810 if (OtherAddOp) {
3811 // So at this point we know we have:
3812 // select C, (add X, Y), (sub X, ?)
3813 // We can do the transform profitably if either 'Y' = '?' or '?' is
3814 // a constant.
3815 if (SubOp->getOperand(1) == AddOp ||
3816 isa<Constant>(SubOp->getOperand(1))) {
3817 Value *NegVal;
3818 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
3819 NegVal = ConstantExpr::getNeg(C);
3820 } else {
3821 NegVal = InsertNewInstBefore(
3822 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
3823 }
3824
Chris Lattner51726c42005-01-14 17:35:12 +00003825 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00003826 Value *NewFalseOp = NegVal;
3827 if (AddOp != TI)
3828 std::swap(NewTrueOp, NewFalseOp);
3829 Instruction *NewSel =
3830 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanb1c93172005-04-21 23:48:37 +00003831
Chris Lattnera04c9042005-01-13 22:52:24 +00003832 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00003833 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00003834 }
3835 }
3836 }
3837 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003838
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003839 // See if we can fold the select into one of our operands.
3840 if (SI.getType()->isInteger()) {
3841 // See the comment above GetSelectFoldableOperands for a description of the
3842 // transformation we are doing here.
3843 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3844 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3845 !isa<Constant>(FalseVal))
3846 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3847 unsigned OpToFold = 0;
3848 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3849 OpToFold = 1;
3850 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3851 OpToFold = 2;
3852 }
3853
3854 if (OpToFold) {
3855 Constant *C = GetSelectFoldableConstant(TVI);
3856 std::string Name = TVI->getName(); TVI->setName("");
3857 Instruction *NewSel =
3858 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3859 Name);
3860 InsertNewInstBefore(NewSel, SI);
3861 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3862 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3863 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3864 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3865 else {
3866 assert(0 && "Unknown instruction!!");
3867 }
3868 }
3869 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003870
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003871 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3872 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3873 !isa<Constant>(TrueVal))
3874 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3875 unsigned OpToFold = 0;
3876 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3877 OpToFold = 1;
3878 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3879 OpToFold = 2;
3880 }
3881
3882 if (OpToFold) {
3883 Constant *C = GetSelectFoldableConstant(FVI);
3884 std::string Name = FVI->getName(); FVI->setName("");
3885 Instruction *NewSel =
3886 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3887 Name);
3888 InsertNewInstBefore(NewSel, SI);
3889 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3890 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3891 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3892 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3893 else {
3894 assert(0 && "Unknown instruction!!");
3895 }
3896 }
3897 }
3898 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003899 return 0;
3900}
3901
3902
Chris Lattner970c33a2003-06-19 17:00:31 +00003903// CallInst simplification
3904//
3905Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003906 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3907 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00003908 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3909 bool Changed = false;
3910
3911 // memmove/cpy/set of zero bytes is a noop.
3912 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3913 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3914
3915 // FIXME: Increase alignment here.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003916
Chris Lattner00648e12004-10-12 04:52:52 +00003917 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3918 if (CI->getRawValue() == 1) {
3919 // Replace the instruction with just byte operations. We would
3920 // transform other cases to loads/stores, but we don't know if
3921 // alignment is sufficient.
3922 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003923 }
3924
Chris Lattner00648e12004-10-12 04:52:52 +00003925 // If we have a memmove and the source operation is a constant global,
3926 // then the source and dest pointers can't alias, so we can change this
3927 // into a call to memcpy.
3928 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3929 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3930 if (GVSrc->isConstant()) {
3931 Module *M = CI.getParent()->getParent()->getParent();
3932 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3933 CI.getCalledFunction()->getFunctionType());
3934 CI.setOperand(0, MemCpy);
3935 Changed = true;
3936 }
3937
3938 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00003939 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
3940 // If this stoppoint is at the same source location as the previous
3941 // stoppoint in the chain, it is not needed.
3942 if (DbgStopPointInst *PrevSPI =
3943 dyn_cast<DbgStopPointInst>(SPI->getChain()))
3944 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
3945 SPI->getColNo() == PrevSPI->getColNo()) {
3946 SPI->replaceAllUsesWith(PrevSPI);
3947 return EraseInstFromFunction(CI);
3948 }
Chris Lattner00648e12004-10-12 04:52:52 +00003949 }
3950
Chris Lattneraec3d942003-10-07 22:32:43 +00003951 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003952}
3953
3954// InvokeInst simplification
3955//
3956Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003957 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003958}
3959
Chris Lattneraec3d942003-10-07 22:32:43 +00003960// visitCallSite - Improvements for call and invoke instructions.
3961//
3962Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003963 bool Changed = false;
3964
3965 // If the callee is a constexpr cast of a function, attempt to move the cast
3966 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003967 if (transformConstExprCastCall(CS)) return 0;
3968
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003969 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00003970
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003971 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3972 // This instruction is not reachable, just remove it. We insert a store to
3973 // undef so that we know that this code is not reachable, despite the fact
3974 // that we can't modify the CFG here.
3975 new StoreInst(ConstantBool::True,
3976 UndefValue::get(PointerType::get(Type::BoolTy)),
3977 CS.getInstruction());
3978
3979 if (!CS.getInstruction()->use_empty())
3980 CS.getInstruction()->
3981 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3982
3983 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3984 // Don't break the CFG, insert a dummy cond branch.
3985 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3986 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00003987 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003988 return EraseInstFromFunction(*CS.getInstruction());
3989 }
Chris Lattner81a7a232004-10-16 18:11:37 +00003990
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003991 const PointerType *PTy = cast<PointerType>(Callee->getType());
3992 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3993 if (FTy->isVarArg()) {
3994 // See if we can optimize any arguments passed through the varargs area of
3995 // the call.
3996 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3997 E = CS.arg_end(); I != E; ++I)
3998 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3999 // If this cast does not effect the value passed through the varargs
4000 // area, we can eliminate the use of the cast.
4001 Value *Op = CI->getOperand(0);
4002 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4003 *I = Op;
4004 Changed = true;
4005 }
4006 }
4007 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004008
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004009 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00004010}
4011
Chris Lattner970c33a2003-06-19 17:00:31 +00004012// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4013// attempt to move the cast to the arguments of the call/invoke.
4014//
4015bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4016 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4017 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00004018 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00004019 return false;
Reid Spencer87436872004-07-18 00:38:32 +00004020 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00004021 Instruction *Caller = CS.getInstruction();
4022
4023 // Okay, this is a cast from a function to a different type. Unless doing so
4024 // would cause a type conversion of one of our arguments, change this call to
4025 // be a direct call with arguments casted to the appropriate types.
4026 //
4027 const FunctionType *FT = Callee->getFunctionType();
4028 const Type *OldRetTy = Caller->getType();
4029
Chris Lattner1f7942f2004-01-14 06:06:08 +00004030 // Check to see if we are changing the return type...
4031 if (OldRetTy != FT->getReturnType()) {
4032 if (Callee->isExternal() &&
4033 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4034 !Caller->use_empty())
4035 return false; // Cannot transform this return value...
4036
4037 // If the callsite is an invoke instruction, and the return value is used by
4038 // a PHI node in a successor, we cannot change the return type of the call
4039 // because there is no place to put the cast instruction (without breaking
4040 // the critical edge). Bail out in this case.
4041 if (!Caller->use_empty())
4042 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4043 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4044 UI != E; ++UI)
4045 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4046 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004047 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00004048 return false;
4049 }
Chris Lattner970c33a2003-06-19 17:00:31 +00004050
4051 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4052 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004053
Chris Lattner970c33a2003-06-19 17:00:31 +00004054 CallSite::arg_iterator AI = CS.arg_begin();
4055 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4056 const Type *ParamTy = FT->getParamType(i);
4057 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004058 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00004059 }
4060
4061 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4062 Callee->isExternal())
4063 return false; // Do not delete arguments unless we have a function body...
4064
4065 // Okay, we decided that this is a safe thing to do: go ahead and start
4066 // inserting cast instructions as necessary...
4067 std::vector<Value*> Args;
4068 Args.reserve(NumActualArgs);
4069
4070 AI = CS.arg_begin();
4071 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4072 const Type *ParamTy = FT->getParamType(i);
4073 if ((*AI)->getType() == ParamTy) {
4074 Args.push_back(*AI);
4075 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00004076 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4077 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00004078 }
4079 }
4080
4081 // If the function takes more arguments than the call was taking, add them
4082 // now...
4083 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4084 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4085
4086 // If we are removing arguments to the function, emit an obnoxious warning...
4087 if (FT->getNumParams() < NumActualArgs)
4088 if (!FT->isVarArg()) {
4089 std::cerr << "WARNING: While resolving call to function '"
4090 << Callee->getName() << "' arguments were dropped!\n";
4091 } else {
4092 // Add all of the arguments in their promoted form to the arg list...
4093 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4094 const Type *PTy = getPromotedType((*AI)->getType());
4095 if (PTy != (*AI)->getType()) {
4096 // Must promote to pass through va_arg area!
4097 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4098 InsertNewInstBefore(Cast, *Caller);
4099 Args.push_back(Cast);
4100 } else {
4101 Args.push_back(*AI);
4102 }
4103 }
4104 }
4105
4106 if (FT->getReturnType() == Type::VoidTy)
4107 Caller->setName(""); // Void type should not have a name...
4108
4109 Instruction *NC;
4110 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004111 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00004112 Args, Caller->getName(), Caller);
4113 } else {
4114 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
4115 }
4116
4117 // Insert a cast of the return type as necessary...
4118 Value *NV = NC;
4119 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4120 if (NV->getType() != Type::VoidTy) {
4121 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00004122
4123 // If this is an invoke instruction, we should insert it after the first
4124 // non-phi, instruction in the normal successor block.
4125 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4126 BasicBlock::iterator I = II->getNormalDest()->begin();
4127 while (isa<PHINode>(I)) ++I;
4128 InsertNewInstBefore(NC, *I);
4129 } else {
4130 // Otherwise, it's a call, just insert cast right after the call instr
4131 InsertNewInstBefore(NC, *Caller);
4132 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004133 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00004134 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00004135 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00004136 }
4137 }
4138
4139 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4140 Caller->replaceAllUsesWith(NV);
4141 Caller->getParent()->getInstList().erase(Caller);
4142 removeFromWorkList(Caller);
4143 return true;
4144}
4145
4146
Chris Lattner7515cab2004-11-14 19:13:23 +00004147// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4148// operator and they all are only used by the PHI, PHI together their
4149// inputs, and do the operation once, to the result of the PHI.
4150Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4151 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4152
4153 // Scan the instruction, looking for input operations that can be folded away.
4154 // If all input operands to the phi are the same instruction (e.g. a cast from
4155 // the same type or "+42") we can pull the operation through the PHI, reducing
4156 // code size and simplifying code.
4157 Constant *ConstantOp = 0;
4158 const Type *CastSrcTy = 0;
4159 if (isa<CastInst>(FirstInst)) {
4160 CastSrcTy = FirstInst->getOperand(0)->getType();
4161 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4162 // Can fold binop or shift if the RHS is a constant.
4163 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4164 if (ConstantOp == 0) return 0;
4165 } else {
4166 return 0; // Cannot fold this operation.
4167 }
4168
4169 // Check to see if all arguments are the same operation.
4170 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4171 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4172 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4173 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4174 return 0;
4175 if (CastSrcTy) {
4176 if (I->getOperand(0)->getType() != CastSrcTy)
4177 return 0; // Cast operation must match.
4178 } else if (I->getOperand(1) != ConstantOp) {
4179 return 0;
4180 }
4181 }
4182
4183 // Okay, they are all the same operation. Create a new PHI node of the
4184 // correct type, and PHI together all of the LHS's of the instructions.
4185 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4186 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00004187 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00004188
4189 Value *InVal = FirstInst->getOperand(0);
4190 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00004191
4192 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00004193 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4194 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4195 if (NewInVal != InVal)
4196 InVal = 0;
4197 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4198 }
4199
4200 Value *PhiVal;
4201 if (InVal) {
4202 // The new PHI unions all of the same values together. This is really
4203 // common, so we handle it intelligently here for compile-time speed.
4204 PhiVal = InVal;
4205 delete NewPN;
4206 } else {
4207 InsertNewInstBefore(NewPN, PN);
4208 PhiVal = NewPN;
4209 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004210
Chris Lattner7515cab2004-11-14 19:13:23 +00004211 // Insert and return the new operation.
4212 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004213 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00004214 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004215 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004216 else
4217 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00004218 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004219}
Chris Lattner48a44f72002-05-02 17:06:02 +00004220
Chris Lattner71536432005-01-17 05:10:15 +00004221/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4222/// that is dead.
4223static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4224 if (PN->use_empty()) return true;
4225 if (!PN->hasOneUse()) return false;
4226
4227 // Remember this node, and if we find the cycle, return.
4228 if (!PotentiallyDeadPHIs.insert(PN).second)
4229 return true;
4230
4231 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4232 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004233
Chris Lattner71536432005-01-17 05:10:15 +00004234 return false;
4235}
4236
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004237// PHINode simplification
4238//
Chris Lattner113f4f42002-06-25 16:13:24 +00004239Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnere29d6342004-10-17 21:22:38 +00004240 if (Value *V = hasConstantValue(&PN)) {
4241 // If V is an instruction, we have to be certain that it dominates PN.
4242 // However, because we don't have dom info, we can't do a perfect job.
4243 if (Instruction *I = dyn_cast<Instruction>(V)) {
4244 // We know that the instruction dominates the PHI if there are no undef
4245 // values coming in.
Chris Lattner3b92f172004-10-18 01:48:31 +00004246 if (I->getParent() != &I->getParent()->getParent()->front() ||
4247 isa<InvokeInst>(I))
Chris Lattner107c15c2004-10-17 21:31:34 +00004248 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4249 if (isa<UndefValue>(PN.getIncomingValue(i))) {
4250 V = 0;
4251 break;
4252 }
Chris Lattnere29d6342004-10-17 21:22:38 +00004253 }
4254
4255 if (V)
4256 return ReplaceInstUsesWith(PN, V);
4257 }
Chris Lattner4db2d222004-02-16 05:07:08 +00004258
4259 // If the only user of this instruction is a cast instruction, and all of the
4260 // incoming values are constants, change this PHI to merge together the casted
4261 // constants.
4262 if (PN.hasOneUse())
4263 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4264 if (CI->getType() != PN.getType()) { // noop casts will be folded
4265 bool AllConstant = true;
4266 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4267 if (!isa<Constant>(PN.getIncomingValue(i))) {
4268 AllConstant = false;
4269 break;
4270 }
4271 if (AllConstant) {
4272 // Make a new PHI with all casted values.
4273 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4274 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4275 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4276 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4277 PN.getIncomingBlock(i));
4278 }
4279
4280 // Update the cast instruction.
4281 CI->setOperand(0, New);
4282 WorkList.push_back(CI); // revisit the cast instruction to fold.
4283 WorkList.push_back(New); // Make sure to revisit the new Phi
4284 return &PN; // PN is now dead!
4285 }
4286 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004287
4288 // If all PHI operands are the same operation, pull them through the PHI,
4289 // reducing code size.
4290 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4291 PN.getIncomingValue(0)->hasOneUse())
4292 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4293 return Result;
4294
Chris Lattner71536432005-01-17 05:10:15 +00004295 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4296 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4297 // PHI)... break the cycle.
4298 if (PN.hasOneUse())
4299 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4300 std::set<PHINode*> PotentiallyDeadPHIs;
4301 PotentiallyDeadPHIs.insert(&PN);
4302 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4303 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4304 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004305
Chris Lattner91daeb52003-12-19 05:58:40 +00004306 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004307}
4308
Chris Lattner69193f92004-04-05 01:30:19 +00004309static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4310 Instruction *InsertPoint,
4311 InstCombiner *IC) {
4312 unsigned PS = IC->getTargetData().getPointerSize();
4313 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00004314 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4315 // We must insert a cast to ensure we sign-extend.
4316 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4317 V->getName()), *InsertPoint);
4318 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4319 *InsertPoint);
4320}
4321
Chris Lattner48a44f72002-05-02 17:06:02 +00004322
Chris Lattner113f4f42002-06-25 16:13:24 +00004323Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004324 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00004325 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00004326 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004327 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00004328 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004329
Chris Lattner81a7a232004-10-16 18:11:37 +00004330 if (isa<UndefValue>(GEP.getOperand(0)))
4331 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4332
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004333 bool HasZeroPointerIndex = false;
4334 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4335 HasZeroPointerIndex = C->isNullValue();
4336
4337 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00004338 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00004339
Chris Lattner69193f92004-04-05 01:30:19 +00004340 // Eliminate unneeded casts for indices.
4341 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00004342 gep_type_iterator GTI = gep_type_begin(GEP);
4343 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4344 if (isa<SequentialType>(*GTI)) {
4345 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4346 Value *Src = CI->getOperand(0);
4347 const Type *SrcTy = Src->getType();
4348 const Type *DestTy = CI->getType();
4349 if (Src->getType()->isInteger()) {
4350 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
4351 // We can always eliminate a cast from ulong or long to the other.
4352 // We can always eliminate a cast from uint to int or the other on
4353 // 32-bit pointer platforms.
4354 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
4355 MadeChange = true;
4356 GEP.setOperand(i, Src);
4357 }
4358 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4359 SrcTy->getPrimitiveSize() == 4) {
4360 // We can always eliminate a cast from int to [u]long. We can
4361 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4362 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004363 if (SrcTy->isSigned() ||
Chris Lattner2b2412d2004-04-07 18:38:20 +00004364 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
4365 MadeChange = true;
4366 GEP.setOperand(i, Src);
4367 }
Chris Lattner69193f92004-04-05 01:30:19 +00004368 }
4369 }
4370 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00004371 // If we are using a wider index than needed for this platform, shrink it
4372 // to what we need. If the incoming value needs a cast instruction,
4373 // insert it. This explicit cast can make subsequent optimizations more
4374 // obvious.
4375 Value *Op = GEP.getOperand(i);
4376 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004377 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00004378 GEP.setOperand(i, ConstantExpr::getCast(C,
4379 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004380 MadeChange = true;
4381 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004382 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4383 Op->getName()), GEP);
4384 GEP.setOperand(i, Op);
4385 MadeChange = true;
4386 }
Chris Lattner44d0b952004-07-20 01:48:15 +00004387
4388 // If this is a constant idx, make sure to canonicalize it to be a signed
4389 // operand, otherwise CSE and other optimizations are pessimized.
4390 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
4391 GEP.setOperand(i, ConstantExpr::getCast(CUI,
4392 CUI->getType()->getSignedVersion()));
4393 MadeChange = true;
4394 }
Chris Lattner69193f92004-04-05 01:30:19 +00004395 }
4396 if (MadeChange) return &GEP;
4397
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004398 // Combine Indices - If the source pointer to this getelementptr instruction
4399 // is a getelementptr instruction, combine the indices of the two
4400 // getelementptr instructions into a single instruction.
4401 //
Chris Lattner57c67b02004-03-25 22:59:29 +00004402 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00004403 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00004404 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00004405
4406 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004407 // Note that if our source is a gep chain itself that we wait for that
4408 // chain to be resolved before we perform this transformation. This
4409 // avoids us creating a TON of code in some cases.
4410 //
4411 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
4412 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
4413 return 0; // Wait until our source is folded to completion.
4414
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004415 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00004416
4417 // Find out whether the last index in the source GEP is a sequential idx.
4418 bool EndsWithSequential = false;
4419 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
4420 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00004421 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004422
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004423 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00004424 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00004425 // Replace: gep (gep %P, long B), long A, ...
4426 // With: T = long A+B; gep %P, T, ...
4427 //
Chris Lattner5f667a62004-05-07 22:09:22 +00004428 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00004429 if (SO1 == Constant::getNullValue(SO1->getType())) {
4430 Sum = GO1;
4431 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
4432 Sum = SO1;
4433 } else {
4434 // If they aren't the same type, convert both to an integer of the
4435 // target's pointer size.
4436 if (SO1->getType() != GO1->getType()) {
4437 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
4438 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
4439 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
4440 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
4441 } else {
4442 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00004443 if (SO1->getType()->getPrimitiveSize() == PS) {
4444 // Convert GO1 to SO1's type.
4445 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
4446
4447 } else if (GO1->getType()->getPrimitiveSize() == PS) {
4448 // Convert SO1 to GO1's type.
4449 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
4450 } else {
4451 const Type *PT = TD->getIntPtrType();
4452 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
4453 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
4454 }
4455 }
4456 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004457 if (isa<Constant>(SO1) && isa<Constant>(GO1))
4458 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
4459 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004460 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
4461 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00004462 }
Chris Lattner69193f92004-04-05 01:30:19 +00004463 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004464
4465 // Recycle the GEP we already have if possible.
4466 if (SrcGEPOperands.size() == 2) {
4467 GEP.setOperand(0, SrcGEPOperands[0]);
4468 GEP.setOperand(1, Sum);
4469 return &GEP;
4470 } else {
4471 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4472 SrcGEPOperands.end()-1);
4473 Indices.push_back(Sum);
4474 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
4475 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004476 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00004477 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004478 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004479 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00004480 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4481 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004482 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
4483 }
4484
4485 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00004486 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004487
Chris Lattner5f667a62004-05-07 22:09:22 +00004488 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004489 // GEP of global variable. If all of the indices for this GEP are
4490 // constants, we can promote this to a constexpr instead of an instruction.
4491
4492 // Scan for nonconstants...
4493 std::vector<Constant*> Indices;
4494 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
4495 for (; I != E && isa<Constant>(*I); ++I)
4496 Indices.push_back(cast<Constant>(*I));
4497
4498 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00004499 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004500
4501 // Replace all uses of the GEP with the new constexpr...
4502 return ReplaceInstUsesWith(GEP, CE);
4503 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004504 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004505 if (CE->getOpcode() == Instruction::Cast) {
4506 if (HasZeroPointerIndex) {
4507 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
4508 // into : GEP [10 x ubyte]* X, long 0, ...
4509 //
4510 // This occurs when the program declares an array extern like "int X[];"
4511 //
4512 Constant *X = CE->getOperand(0);
4513 const PointerType *CPTy = cast<PointerType>(CE->getType());
4514 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
4515 if (const ArrayType *XATy =
4516 dyn_cast<ArrayType>(XTy->getElementType()))
4517 if (const ArrayType *CATy =
4518 dyn_cast<ArrayType>(CPTy->getElementType()))
4519 if (CATy->getElementType() == XATy->getElementType()) {
4520 // At this point, we know that the cast source type is a pointer
4521 // to an array of the same type as the destination pointer
4522 // array. Because the array type is never stepped over (there
4523 // is a leading zero) we can fold the cast into this GEP.
4524 GEP.setOperand(0, X);
4525 return &GEP;
4526 }
Chris Lattner0798af32005-01-13 20:14:25 +00004527 } else if (GEP.getNumOperands() == 2 &&
4528 isa<PointerType>(CE->getOperand(0)->getType())) {
Chris Lattner14f3cdc2004-11-27 17:55:46 +00004529 // Transform things like:
4530 // %t = getelementptr ubyte* cast ([2 x sbyte]* %str to ubyte*), uint %V
4531 // into: %t1 = getelementptr [2 x sbyte*]* %str, int 0, uint %V; cast
4532 Constant *X = CE->getOperand(0);
4533 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4534 const Type *ResElTy =cast<PointerType>(CE->getType())->getElementType();
4535 if (isa<ArrayType>(SrcElTy) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004536 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
Chris Lattner14f3cdc2004-11-27 17:55:46 +00004537 TD->getTypeSize(ResElTy)) {
4538 Value *V = InsertNewInstBefore(
4539 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
4540 GEP.getOperand(1), GEP.getName()), GEP);
4541 return new CastInst(V, GEP.getType());
4542 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004543 }
4544 }
Chris Lattnerca081252001-12-14 16:52:21 +00004545 }
4546
Chris Lattnerca081252001-12-14 16:52:21 +00004547 return 0;
4548}
4549
Chris Lattner1085bdf2002-11-04 16:18:53 +00004550Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
4551 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
4552 if (AI.isArrayAllocation()) // Check C != 1
4553 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
4554 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004555 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00004556
4557 // Create and insert the replacement instruction...
4558 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00004559 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004560 else {
4561 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00004562 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004563 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004564
4565 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004566
Chris Lattner1085bdf2002-11-04 16:18:53 +00004567 // Scan to the end of the allocation instructions, to skip over a block of
4568 // allocas if possible...
4569 //
4570 BasicBlock::iterator It = New;
4571 while (isa<AllocationInst>(*It)) ++It;
4572
4573 // Now that I is pointing to the first non-allocation-inst in the block,
4574 // insert our getelementptr instruction...
4575 //
Chris Lattner69193f92004-04-05 01:30:19 +00004576 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00004577 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
4578
4579 // Now make everything use the getelementptr instead of the original
4580 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00004581 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00004582 } else if (isa<UndefValue>(AI.getArraySize())) {
4583 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00004584 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004585
4586 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
4587 // Note that we only do this for alloca's, because malloc should allocate and
4588 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004589 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00004590 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00004591 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
4592
Chris Lattner1085bdf2002-11-04 16:18:53 +00004593 return 0;
4594}
4595
Chris Lattner8427bff2003-12-07 01:24:23 +00004596Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
4597 Value *Op = FI.getOperand(0);
4598
4599 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
4600 if (CastInst *CI = dyn_cast<CastInst>(Op))
4601 if (isa<PointerType>(CI->getOperand(0)->getType())) {
4602 FI.setOperand(0, CI->getOperand(0));
4603 return &FI;
4604 }
4605
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004606 // free undef -> unreachable.
4607 if (isa<UndefValue>(Op)) {
4608 // Insert a new store to null because we cannot modify the CFG here.
4609 new StoreInst(ConstantBool::True,
4610 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
4611 return EraseInstFromFunction(FI);
4612 }
4613
Chris Lattnerf3a36602004-02-28 04:57:37 +00004614 // If we have 'free null' delete the instruction. This can happen in stl code
4615 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004616 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00004617 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00004618
Chris Lattner8427bff2003-12-07 01:24:23 +00004619 return 0;
4620}
4621
4622
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004623/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
4624/// constantexpr, return the constant value being addressed by the constant
4625/// expression, or null if something is funny.
4626///
4627static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00004628 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004629 return 0; // Do not allow stepping over the value!
4630
4631 // Loop over all of the operands, tracking down which value we are
4632 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00004633 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
4634 for (++I; I != E; ++I)
4635 if (const StructType *STy = dyn_cast<StructType>(*I)) {
4636 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
4637 assert(CU->getValue() < STy->getNumElements() &&
4638 "Struct index out of range!");
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004639 unsigned El = (unsigned)CU->getValue();
Chris Lattnered79d8a2004-05-27 17:30:27 +00004640 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004641 C = CS->getOperand(El);
Chris Lattnered79d8a2004-05-27 17:30:27 +00004642 } else if (isa<ConstantAggregateZero>(C)) {
Jeff Cohen82639852005-04-23 21:38:35 +00004643 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattner81a7a232004-10-16 18:11:37 +00004644 } else if (isa<UndefValue>(C)) {
Jeff Cohen82639852005-04-23 21:38:35 +00004645 C = UndefValue::get(STy->getElementType(El));
Chris Lattnered79d8a2004-05-27 17:30:27 +00004646 } else {
4647 return 0;
4648 }
4649 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
4650 const ArrayType *ATy = cast<ArrayType>(*I);
4651 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
4652 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004653 C = CA->getOperand((unsigned)CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004654 else if (isa<ConstantAggregateZero>(C))
4655 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00004656 else if (isa<UndefValue>(C))
4657 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004658 else
4659 return 0;
4660 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004661 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00004662 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004663 return C;
4664}
4665
Chris Lattner72684fe2005-01-31 05:51:45 +00004666/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00004667static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
4668 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004669 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00004670
4671 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004672 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00004673 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004674
4675 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
4676 // If the source is an array, the code below will not succeed. Check to
4677 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
4678 // constants.
4679 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
4680 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
4681 if (ASrcTy->getNumElements() != 0) {
4682 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
4683 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
4684 SrcTy = cast<PointerType>(CastOp->getType());
4685 SrcPTy = SrcTy->getElementType();
4686 }
4687
4688 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00004689 // Do not allow turning this into a load of an integer, which is then
4690 // casted to a pointer, this pessimizes pointer analysis a lot.
4691 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004692 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004693 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004694
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004695 // Okay, we are casting from one integer or pointer type to another of
4696 // the same size. Instead of casting the pointer before the load, cast
4697 // the result of the loaded value.
4698 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
4699 CI->getName(),
4700 LI.isVolatile()),LI);
4701 // Now cast the result of the load.
4702 return new CastInst(NewLoad, LI.getType());
4703 }
Chris Lattner35e24772004-07-13 01:49:43 +00004704 }
4705 }
4706 return 0;
4707}
4708
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004709/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00004710/// from this value cannot trap. If it is not obviously safe to load from the
4711/// specified pointer, we do a quick local scan of the basic block containing
4712/// ScanFrom, to determine if the address is already accessed.
4713static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
4714 // If it is an alloca or global variable, it is always safe to load from.
4715 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
4716
4717 // Otherwise, be a little bit agressive by scanning the local block where we
4718 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004719 // from/to. If so, the previous load or store would have already trapped,
4720 // so there is no harm doing an extra load (also, CSE will later eliminate
4721 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00004722 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
4723
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004724 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00004725 --BBI;
4726
4727 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
4728 if (LI->getOperand(0) == V) return true;
4729 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
4730 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004731
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004732 }
Chris Lattnere6f13092004-09-19 19:18:10 +00004733 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004734}
4735
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004736Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
4737 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00004738
Chris Lattner81a7a232004-10-16 18:11:37 +00004739 if (Constant *C = dyn_cast<Constant>(Op)) {
4740 if ((C->isNullValue() || isa<UndefValue>(C)) &&
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004741 !LI.isVolatile()) { // load null/undef -> undef
4742 // Insert a new store to null instruction before the load to indicate that
4743 // this code is not reachable. We do this instead of inserting an
4744 // unreachable instruction directly because we cannot modify the CFG.
4745 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00004746 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004747 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004748
Chris Lattner81a7a232004-10-16 18:11:37 +00004749 // Instcombine load (constant global) into the value loaded.
4750 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
4751 if (GV->isConstant() && !GV->isExternal())
4752 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00004753
Chris Lattner81a7a232004-10-16 18:11:37 +00004754 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
4755 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
4756 if (CE->getOpcode() == Instruction::GetElementPtr) {
4757 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
4758 if (GV->isConstant() && !GV->isExternal())
4759 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
4760 return ReplaceInstUsesWith(LI, V);
4761 } else if (CE->getOpcode() == Instruction::Cast) {
4762 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4763 return Res;
4764 }
4765 }
Chris Lattnere228ee52004-04-08 20:39:49 +00004766
4767 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00004768 if (CastInst *CI = dyn_cast<CastInst>(Op))
4769 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4770 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00004771
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004772 if (!LI.isVolatile() && Op->hasOneUse()) {
4773 // Change select and PHI nodes to select values instead of addresses: this
4774 // helps alias analysis out a lot, allows many others simplifications, and
4775 // exposes redundancy in the code.
4776 //
4777 // Note that we cannot do the transformation unless we know that the
4778 // introduced loads cannot trap! Something like this is valid as long as
4779 // the condition is always false: load (select bool %C, int* null, int* %G),
4780 // but it would not be valid if we transformed it to load from null
4781 // unconditionally.
4782 //
4783 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
4784 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00004785 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
4786 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004787 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00004788 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004789 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00004790 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004791 return new SelectInst(SI->getCondition(), V1, V2);
4792 }
4793
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00004794 // load (select (cond, null, P)) -> load P
4795 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
4796 if (C->isNullValue()) {
4797 LI.setOperand(0, SI->getOperand(2));
4798 return &LI;
4799 }
4800
4801 // load (select (cond, P, null)) -> load P
4802 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
4803 if (C->isNullValue()) {
4804 LI.setOperand(0, SI->getOperand(1));
4805 return &LI;
4806 }
4807
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004808 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
4809 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00004810 bool Safe = PN->getParent() == LI.getParent();
4811
4812 // Scan all of the instructions between the PHI and the load to make
4813 // sure there are no instructions that might possibly alter the value
4814 // loaded from the PHI.
4815 if (Safe) {
4816 BasicBlock::iterator I = &LI;
4817 for (--I; !isa<PHINode>(I); --I)
4818 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
4819 Safe = false;
4820 break;
4821 }
4822 }
4823
4824 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00004825 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00004826 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004827 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00004828
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004829 if (Safe) {
4830 // Create the PHI.
4831 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
4832 InsertNewInstBefore(NewPN, *PN);
4833 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
4834
4835 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4836 BasicBlock *BB = PN->getIncomingBlock(i);
4837 Value *&TheLoad = LoadMap[BB];
4838 if (TheLoad == 0) {
4839 Value *InVal = PN->getIncomingValue(i);
4840 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
4841 InVal->getName()+".val"),
4842 *BB->getTerminator());
4843 }
4844 NewPN->addIncoming(TheLoad, BB);
4845 }
4846 return ReplaceInstUsesWith(LI, NewPN);
4847 }
4848 }
4849 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004850 return 0;
4851}
4852
Chris Lattner72684fe2005-01-31 05:51:45 +00004853/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
4854/// when possible.
4855static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
4856 User *CI = cast<User>(SI.getOperand(1));
4857 Value *CastOp = CI->getOperand(0);
4858
4859 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
4860 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
4861 const Type *SrcPTy = SrcTy->getElementType();
4862
4863 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
4864 // If the source is an array, the code below will not succeed. Check to
4865 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
4866 // constants.
4867 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
4868 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
4869 if (ASrcTy->getNumElements() != 0) {
4870 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
4871 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
4872 SrcTy = cast<PointerType>(CastOp->getType());
4873 SrcPTy = SrcTy->getElementType();
4874 }
4875
4876 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004877 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00004878 IC.getTargetData().getTypeSize(DestPTy)) {
4879
4880 // Okay, we are casting from one integer or pointer type to another of
4881 // the same size. Instead of casting the pointer before the store, cast
4882 // the value to be stored.
4883 Value *NewCast;
4884 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
4885 NewCast = ConstantExpr::getCast(C, SrcPTy);
4886 else
4887 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
4888 SrcPTy,
4889 SI.getOperand(0)->getName()+".c"), SI);
4890
4891 return new StoreInst(NewCast, CastOp);
4892 }
4893 }
4894 }
4895 return 0;
4896}
4897
Chris Lattner31f486c2005-01-31 05:36:43 +00004898Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
4899 Value *Val = SI.getOperand(0);
4900 Value *Ptr = SI.getOperand(1);
4901
4902 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
4903 removeFromWorkList(&SI);
4904 SI.eraseFromParent();
4905 ++NumCombined;
4906 return 0;
4907 }
4908
4909 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
4910
4911 // store X, null -> turns into 'unreachable' in SimplifyCFG
4912 if (isa<ConstantPointerNull>(Ptr)) {
4913 if (!isa<UndefValue>(Val)) {
4914 SI.setOperand(0, UndefValue::get(Val->getType()));
4915 if (Instruction *U = dyn_cast<Instruction>(Val))
4916 WorkList.push_back(U); // Dropped a use.
4917 ++NumCombined;
4918 }
4919 return 0; // Do not modify these!
4920 }
4921
4922 // store undef, Ptr -> noop
4923 if (isa<UndefValue>(Val)) {
4924 removeFromWorkList(&SI);
4925 SI.eraseFromParent();
4926 ++NumCombined;
4927 return 0;
4928 }
4929
Chris Lattner72684fe2005-01-31 05:51:45 +00004930 // If the pointer destination is a cast, see if we can fold the cast into the
4931 // source instead.
4932 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
4933 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
4934 return Res;
4935 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
4936 if (CE->getOpcode() == Instruction::Cast)
4937 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
4938 return Res;
4939
Chris Lattner31f486c2005-01-31 05:36:43 +00004940 return 0;
4941}
4942
4943
Chris Lattner9eef8a72003-06-04 04:46:00 +00004944Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
4945 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00004946 Value *X;
4947 BasicBlock *TrueDest;
4948 BasicBlock *FalseDest;
4949 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
4950 !isa<Constant>(X)) {
4951 // Swap Destinations and condition...
4952 BI.setCondition(X);
4953 BI.setSuccessor(0, FalseDest);
4954 BI.setSuccessor(1, TrueDest);
4955 return &BI;
4956 }
4957
4958 // Cannonicalize setne -> seteq
4959 Instruction::BinaryOps Op; Value *Y;
4960 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
4961 TrueDest, FalseDest)))
4962 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
4963 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
4964 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
4965 std::string Name = I->getName(); I->setName("");
4966 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
4967 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00004968 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00004969 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00004970 BI.setSuccessor(0, FalseDest);
4971 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004972 removeFromWorkList(I);
4973 I->getParent()->getInstList().erase(I);
4974 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00004975 return &BI;
4976 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004977
Chris Lattner9eef8a72003-06-04 04:46:00 +00004978 return 0;
4979}
Chris Lattner1085bdf2002-11-04 16:18:53 +00004980
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004981Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4982 Value *Cond = SI.getCondition();
4983 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4984 if (I->getOpcode() == Instruction::Add)
4985 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4986 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4987 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00004988 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004989 AddRHS));
4990 SI.setOperand(0, I->getOperand(0));
4991 WorkList.push_back(I);
4992 return &SI;
4993 }
4994 }
4995 return 0;
4996}
4997
Chris Lattnerca081252001-12-14 16:52:21 +00004998
Chris Lattner99f48c62002-09-02 04:59:56 +00004999void InstCombiner::removeFromWorkList(Instruction *I) {
5000 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5001 WorkList.end());
5002}
5003
Chris Lattner39c98bb2004-12-08 23:43:58 +00005004
5005/// TryToSinkInstruction - Try to move the specified instruction from its
5006/// current block into the beginning of DestBlock, which can only happen if it's
5007/// safe to move the instruction past all of the instructions between it and the
5008/// end of its block.
5009static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5010 assert(I->hasOneUse() && "Invariants didn't hold!");
5011
5012 // Cannot move control-flow-involving instructions.
5013 if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005014
Chris Lattner39c98bb2004-12-08 23:43:58 +00005015 // Do not sink alloca instructions out of the entry block.
5016 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5017 return false;
5018
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005019 // We can only sink load instructions if there is nothing between the load and
5020 // the end of block that could change the value.
5021 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5022 if (LI->isVolatile()) return false; // Don't sink volatile loads.
5023
5024 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5025 Scan != E; ++Scan)
5026 if (Scan->mayWriteToMemory())
5027 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005028 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00005029
5030 BasicBlock::iterator InsertPos = DestBlock->begin();
5031 while (isa<PHINode>(InsertPos)) ++InsertPos;
5032
5033 BasicBlock *SrcBlock = I->getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00005034 DestBlock->getInstList().splice(InsertPos, SrcBlock->getInstList(), I);
Chris Lattner39c98bb2004-12-08 23:43:58 +00005035 ++NumSunkInst;
5036 return true;
5037}
5038
Chris Lattner113f4f42002-06-25 16:13:24 +00005039bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00005040 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005041 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00005042
Chris Lattnerb643a9e2004-05-01 23:19:52 +00005043 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
5044 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00005045
Chris Lattnerca081252001-12-14 16:52:21 +00005046
5047 while (!WorkList.empty()) {
5048 Instruction *I = WorkList.back(); // Get an instruction from the worklist
5049 WorkList.pop_back();
5050
Misha Brukman632df282002-10-29 23:06:16 +00005051 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00005052 // Check to see if we can DIE the instruction...
5053 if (isInstructionTriviallyDead(I)) {
5054 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005055 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00005056 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00005057 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005058
Chris Lattnercd517ff2005-01-28 19:32:01 +00005059 DEBUG(std::cerr << "IC: DCE: " << *I);
5060
5061 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005062 removeFromWorkList(I);
5063 continue;
5064 }
Chris Lattner99f48c62002-09-02 04:59:56 +00005065
Misha Brukman632df282002-10-29 23:06:16 +00005066 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00005067 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005068 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00005069 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005070 cast<Constant>(Ptr)->isNullValue() &&
5071 !isa<ConstantPointerNull>(C) &&
5072 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00005073 // If this is a constant expr gep that is effectively computing an
5074 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5075 bool isFoldableGEP = true;
5076 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5077 if (!isa<ConstantInt>(I->getOperand(i)))
5078 isFoldableGEP = false;
5079 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005080 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00005081 std::vector<Value*>(I->op_begin()+1, I->op_end()));
5082 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00005083 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00005084 C = ConstantExpr::getCast(C, I->getType());
5085 }
5086 }
5087
Chris Lattnercd517ff2005-01-28 19:32:01 +00005088 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5089
Chris Lattner99f48c62002-09-02 04:59:56 +00005090 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00005091 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00005092 ReplaceInstUsesWith(*I, C);
5093
Chris Lattner99f48c62002-09-02 04:59:56 +00005094 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005095 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00005096 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005097 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00005098 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005099
Chris Lattner39c98bb2004-12-08 23:43:58 +00005100 // See if we can trivially sink this instruction to a successor basic block.
5101 if (I->hasOneUse()) {
5102 BasicBlock *BB = I->getParent();
5103 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5104 if (UserParent != BB) {
5105 bool UserIsSuccessor = false;
5106 // See if the user is one of our successors.
5107 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5108 if (*SI == UserParent) {
5109 UserIsSuccessor = true;
5110 break;
5111 }
5112
5113 // If the user is one of our immediate successors, and if that successor
5114 // only has us as a predecessors (we'd have to split the critical edge
5115 // otherwise), we can keep going.
5116 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5117 next(pred_begin(UserParent)) == pred_end(UserParent))
5118 // Okay, the CFG is simple enough, try to sink this instruction.
5119 Changed |= TryToSinkInstruction(I, UserParent);
5120 }
5121 }
5122
Chris Lattnerca081252001-12-14 16:52:21 +00005123 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005124 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00005125 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00005126 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00005127 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005128 DEBUG(std::cerr << "IC: Old = " << *I
5129 << " New = " << *Result);
5130
Chris Lattner396dbfe2004-06-09 05:08:07 +00005131 // Everything uses the new instruction now.
5132 I->replaceAllUsesWith(Result);
5133
5134 // Push the new instruction and any users onto the worklist.
5135 WorkList.push_back(Result);
5136 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005137
5138 // Move the name to the new instruction first...
5139 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00005140 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005141
5142 // Insert the new instruction into the basic block...
5143 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00005144 BasicBlock::iterator InsertPos = I;
5145
5146 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5147 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5148 ++InsertPos;
5149
5150 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005151
Chris Lattner63d75af2004-05-01 23:27:23 +00005152 // Make sure that we reprocess all operands now that we reduced their
5153 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00005154 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5155 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5156 WorkList.push_back(OpI);
5157
Chris Lattner396dbfe2004-06-09 05:08:07 +00005158 // Instructions can end up on the worklist more than once. Make sure
5159 // we do not process an instruction that has been deleted.
5160 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005161
5162 // Erase the old instruction.
5163 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00005164 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005165 DEBUG(std::cerr << "IC: MOD = " << *I);
5166
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005167 // If the instruction was modified, it's possible that it is now dead.
5168 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00005169 if (isInstructionTriviallyDead(I)) {
5170 // Make sure we process all operands now that we are reducing their
5171 // use counts.
5172 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5173 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5174 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005175
Chris Lattner63d75af2004-05-01 23:27:23 +00005176 // Instructions may end up in the worklist more than once. Erase all
5177 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00005178 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00005179 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00005180 } else {
5181 WorkList.push_back(Result);
5182 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005183 }
Chris Lattner053c0932002-05-14 15:24:07 +00005184 }
Chris Lattner260ab202002-04-18 17:39:14 +00005185 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00005186 }
5187 }
5188
Chris Lattner260ab202002-04-18 17:39:14 +00005189 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00005190}
5191
Brian Gaeke38b79e82004-07-27 17:43:21 +00005192FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00005193 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00005194}
Brian Gaeke960707c2003-11-11 22:41:34 +00005195