blob: 6143e3c1f1f9b9820f93662edf2aa4efde0b129b [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 Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattner4ed40f72005-07-07 20:40:38 +000051#include "llvm/ADT/DepthFirstIterator.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000057
Chris Lattner260ab202002-04-18 17:39:14 +000058namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000059 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000062 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000063
Chris Lattnerc8e66542002-04-27 06:56:12 +000064 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000065 public InstVisitor<InstCombiner, Instruction*> {
66 // Worklist of all of the instructions that need to be simplified.
67 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000068 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000069
Chris Lattner51ea1272004-02-28 05:22:00 +000070 /// AddUsersToWorkList - When an instruction is simplified, add all users of
71 /// the instruction to the work lists because they might get more simplified
72 /// now.
73 ///
74 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000075 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000076 UI != UE; ++UI)
77 WorkList.push_back(cast<Instruction>(*UI));
78 }
79
Chris Lattner51ea1272004-02-28 05:22:00 +000080 /// AddUsesToWorkList - When an instruction is simplified, add operands to
81 /// the work lists because they might get more simplified now.
82 ///
83 void AddUsesToWorkList(Instruction &I) {
84 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
85 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
86 WorkList.push_back(Op);
87 }
88
Chris Lattner99f48c62002-09-02 04:59:56 +000089 // removeFromWorkList - remove all instances of I from the worklist.
90 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000091 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000092 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000093
Chris Lattnerf12cc842002-04-28 21:27:06 +000094 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000095 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000096 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000097 }
98
Chris Lattner69193f92004-04-05 01:30:19 +000099 TargetData &getTargetData() const { return *TD; }
100
Chris Lattner260ab202002-04-18 17:39:14 +0000101 // Visitation implementation - Implement instruction combining for different
102 // instruction types. The semantics are as follows:
103 // Return Value:
104 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000105 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000106 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000107 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000108 Instruction *visitAdd(BinaryOperator &I);
109 Instruction *visitSub(BinaryOperator &I);
110 Instruction *visitMul(BinaryOperator &I);
111 Instruction *visitDiv(BinaryOperator &I);
112 Instruction *visitRem(BinaryOperator &I);
113 Instruction *visitAnd(BinaryOperator &I);
114 Instruction *visitOr (BinaryOperator &I);
115 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000116 Instruction *visitSetCondInst(SetCondInst &I);
117 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
118
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 Lattner14553932006-01-06 07:12:35 +0000122 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
123 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000124 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000125 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
126 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000127 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000128 Instruction *visitCallInst(CallInst &CI);
129 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000130 Instruction *visitPHINode(PHINode &PN);
131 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000132 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000133 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000134 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000135 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000136 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000137 Instruction *visitSwitchInst(SwitchInst &SI);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000138 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattner260ab202002-04-18 17:39:14 +0000139
140 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000141 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000142
Chris Lattner970c33a2003-06-19 17:00:31 +0000143 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000144 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000145 bool transformConstExprCastCall(CallSite CS);
146
Chris Lattner69193f92004-04-05 01:30:19 +0000147 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000148 // InsertNewInstBefore - insert an instruction New before instruction Old
149 // in the program. Add the new instruction to the worklist.
150 //
Chris Lattner623826c2004-09-28 21:48:02 +0000151 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000152 assert(New && New->getParent() == 0 &&
153 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000154 BasicBlock *BB = Old.getParent();
155 BB->getInstList().insert(&Old, New); // Insert inst
156 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000157 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000158 }
159
Chris Lattner7e794272004-09-24 15:21:34 +0000160 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
161 /// This also adds the cast to the worklist. Finally, this returns the
162 /// cast.
163 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
164 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000165
Chris Lattner7e794272004-09-24 15:21:34 +0000166 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
167 WorkList.push_back(C);
168 return C;
169 }
170
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000171 // ReplaceInstUsesWith - This method is to be used when an instruction is
172 // found to be dead, replacable with another preexisting expression. Here
173 // we add all uses of I to the worklist, replace all uses of I with the new
174 // value, then return I, so that the inst combiner will know that I was
175 // modified.
176 //
177 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000178 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000179 if (&I != V) {
180 I.replaceAllUsesWith(V);
181 return &I;
182 } else {
183 // If we are replacing the instruction with itself, this must be in a
184 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000185 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000186 return &I;
187 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000188 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000189
190 // EraseInstFromFunction - When dealing with an instruction that has side
191 // effects or produces a void value, we can't rely on DCE to delete the
192 // instruction. Instead, visit methods should return the value returned by
193 // this function.
194 Instruction *EraseInstFromFunction(Instruction &I) {
195 assert(I.use_empty() && "Cannot erase instruction that is used!");
196 AddUsesToWorkList(I);
197 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000198 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000199 return 0; // Don't do anything with FI
200 }
201
202
Chris Lattner3ac7c262003-08-13 20:16:26 +0000203 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000204 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
205 /// InsertBefore instruction. This is specialized a bit to avoid inserting
206 /// casts that are known to not do anything...
207 ///
208 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
209 Instruction *InsertBefore);
210
Chris Lattner7fb29e12003-03-11 00:12:48 +0000211 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000212 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000213 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000214
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000215
216 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
217 // PHI node as operand #0, see if we can fold the instruction into the PHI
218 // (which is only possible if all operands to the PHI are constants).
219 Instruction *FoldOpIntoPhi(Instruction &I);
220
Chris Lattner7515cab2004-11-14 19:13:23 +0000221 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
222 // operator and they all are only used by the PHI, PHI together their
223 // inputs, and do the operation once, to the result of the PHI.
224 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
225
Chris Lattnerba1cb382003-09-19 17:17:26 +0000226 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
227 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000228
229 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
230 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000231 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
232 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000233 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattner260ab202002-04-18 17:39:14 +0000234 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000235
Chris Lattnerc8b70922002-07-26 21:12:46 +0000236 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000237}
238
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000239// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000240// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000241static unsigned getComplexity(Value *V) {
242 if (isa<Instruction>(V)) {
243 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000244 return 3;
245 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000246 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000247 if (isa<Argument>(V)) return 3;
248 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000249}
Chris Lattner260ab202002-04-18 17:39:14 +0000250
Chris Lattner7fb29e12003-03-11 00:12:48 +0000251// isOnlyUse - Return true if this instruction will be deleted if we stop using
252// it.
253static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000254 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000255}
256
Chris Lattnere79e8542004-02-23 06:38:22 +0000257// getPromotedType - Return the specified type promoted as it would be to pass
258// though a va_arg area...
259static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000260 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000261 case Type::SByteTyID:
262 case Type::ShortTyID: return Type::IntTy;
263 case Type::UByteTyID:
264 case Type::UShortTyID: return Type::UIntTy;
265 case Type::FloatTyID: return Type::DoubleTy;
266 default: return Ty;
267 }
268}
269
Chris Lattner567b81f2005-09-13 00:40:14 +0000270/// isCast - If the specified operand is a CastInst or a constant expr cast,
271/// return the operand value, otherwise return null.
272static Value *isCast(Value *V) {
273 if (CastInst *I = dyn_cast<CastInst>(V))
274 return I->getOperand(0);
275 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
276 if (CE->getOpcode() == Instruction::Cast)
277 return CE->getOperand(0);
278 return 0;
279}
280
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000281// SimplifyCommutative - This performs a few simplifications for commutative
282// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000283//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000284// 1. Order operands such that they are listed from right (least complex) to
285// left (most complex). This puts constants before unary operators before
286// binary operators.
287//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000288// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
289// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000290//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000291bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000292 bool Changed = false;
293 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
294 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000295
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000296 if (!I.isAssociative()) return Changed;
297 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000298 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
299 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
300 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000301 Constant *Folded = ConstantExpr::get(I.getOpcode(),
302 cast<Constant>(I.getOperand(1)),
303 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000304 I.setOperand(0, Op->getOperand(0));
305 I.setOperand(1, Folded);
306 return true;
307 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
308 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
309 isOnlyUse(Op) && isOnlyUse(Op1)) {
310 Constant *C1 = cast<Constant>(Op->getOperand(1));
311 Constant *C2 = cast<Constant>(Op1->getOperand(1));
312
313 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000314 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000315 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
316 Op1->getOperand(0),
317 Op1->getName(), &I);
318 WorkList.push_back(New);
319 I.setOperand(0, New);
320 I.setOperand(1, Folded);
321 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000322 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000323 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000324 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000325}
Chris Lattnerca081252001-12-14 16:52:21 +0000326
Chris Lattnerbb74e222003-03-10 23:06:50 +0000327// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
328// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000329//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000330static inline Value *dyn_castNegVal(Value *V) {
331 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000332 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000333
Chris Lattner9ad0d552004-12-14 20:08:06 +0000334 // Constants can be considered to be negated values if they can be folded.
335 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
336 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000337 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000338}
339
Chris Lattnerbb74e222003-03-10 23:06:50 +0000340static inline Value *dyn_castNotVal(Value *V) {
341 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000342 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000343
344 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000345 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000346 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000347 return 0;
348}
349
Chris Lattner7fb29e12003-03-11 00:12:48 +0000350// dyn_castFoldableMul - If this value is a multiply that can be folded into
351// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000352// non-constant operand of the multiply, and set CST to point to the multiplier.
353// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000354//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000355static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000356 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000357 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000358 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000359 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000360 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000361 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000362 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000363 // The multiplier is really 1 << CST.
364 Constant *One = ConstantInt::get(V->getType(), 1);
365 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
366 return I->getOperand(0);
367 }
368 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000369 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000370}
Chris Lattner31ae8632002-08-14 17:51:49 +0000371
Chris Lattner0798af32005-01-13 20:14:25 +0000372/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
373/// expression, return it.
374static User *dyn_castGetElementPtr(Value *V) {
375 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
376 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
377 if (CE->getOpcode() == Instruction::GetElementPtr)
378 return cast<User>(V);
379 return false;
380}
381
Chris Lattner623826c2004-09-28 21:48:02 +0000382// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000383static ConstantInt *AddOne(ConstantInt *C) {
384 return cast<ConstantInt>(ConstantExpr::getAdd(C,
385 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000386}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000387static ConstantInt *SubOne(ConstantInt *C) {
388 return cast<ConstantInt>(ConstantExpr::getSub(C,
389 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000390}
391
Chris Lattner0b3557f2005-09-24 23:43:33 +0000392/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
393/// this predicate to simplify operations downstream. V and Mask are known to
394/// be the same type.
Chris Lattner09efd4e2005-10-31 18:35:52 +0000395static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask,
396 unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000397 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
398 // we cannot optimize based on the assumption that it is zero without changing
399 // to to an explicit zero. If we don't change it to zero, other code could
400 // optimized based on the contradictory assumption that it is non-zero.
401 // Because instcombine aggressively folds operations with undef args anyway,
402 // this won't lose us code quality.
403 if (Mask->isNullValue())
404 return true;
405 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
406 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
Chris Lattner09efd4e2005-10-31 18:35:52 +0000407
408 if (Depth == 6) return false; // Limit search depth.
Chris Lattner0b3557f2005-09-24 23:43:33 +0000409
410 if (Instruction *I = dyn_cast<Instruction>(V)) {
411 switch (I->getOpcode()) {
Chris Lattner62010c42005-10-09 06:36:35 +0000412 case Instruction::And:
413 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
Chris Lattner03b9eb52005-10-09 22:08:50 +0000414 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1))) {
415 ConstantIntegral *C1C2 =
416 cast<ConstantIntegral>(ConstantExpr::getAnd(CI, Mask));
Chris Lattner09efd4e2005-10-31 18:35:52 +0000417 if (MaskedValueIsZero(I->getOperand(0), C1C2, Depth+1))
Chris Lattner62010c42005-10-09 06:36:35 +0000418 return true;
Chris Lattner03b9eb52005-10-09 22:08:50 +0000419 }
420 // If either the LHS or the RHS are MaskedValueIsZero, the result is zero.
Chris Lattner09efd4e2005-10-31 18:35:52 +0000421 return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) ||
422 MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000423 case Instruction::Or:
Chris Lattner03b9eb52005-10-09 22:08:50 +0000424 case Instruction::Xor:
Chris Lattner62010c42005-10-09 06:36:35 +0000425 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
Chris Lattner09efd4e2005-10-31 18:35:52 +0000426 return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) &&
427 MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000428 case Instruction::Select:
429 // If the T and F values are MaskedValueIsZero, the result is also zero.
Chris Lattner09efd4e2005-10-31 18:35:52 +0000430 return MaskedValueIsZero(I->getOperand(2), Mask, Depth+1) &&
431 MaskedValueIsZero(I->getOperand(1), Mask, Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000432 case Instruction::Cast: {
433 const Type *SrcTy = I->getOperand(0)->getType();
434 if (SrcTy == Type::BoolTy)
435 return (Mask->getRawValue() & 1) == 0;
436
437 if (SrcTy->isInteger()) {
438 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
439 if (SrcTy->isUnsigned() && // Only handle zero ext.
440 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
441 return true;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000442
Chris Lattner62010c42005-10-09 06:36:35 +0000443 // If this is a noop cast, recurse.
444 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() == I->getType())||
445 SrcTy->getSignedVersion() == I->getType()) {
446 Constant *NewMask =
447 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +0000448 return MaskedValueIsZero(I->getOperand(0),
Chris Lattner09efd4e2005-10-31 18:35:52 +0000449 cast<ConstantIntegral>(NewMask), Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000450 }
451 }
452 break;
453 }
454 case Instruction::Shl:
455 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
456 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
457 return MaskedValueIsZero(I->getOperand(0),
Chris Lattner09efd4e2005-10-31 18:35:52 +0000458 cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)),
459 Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000460 break;
461 case Instruction::Shr:
462 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
463 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
464 if (I->getType()->isUnsigned()) {
465 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
466 C1 = ConstantExpr::getShr(C1, SA);
467 C1 = ConstantExpr::getAnd(C1, Mask);
468 if (C1->isNullValue())
469 return true;
470 }
471 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000472 }
473 }
474
475 return false;
476}
477
Chris Lattner623826c2004-09-28 21:48:02 +0000478// isTrueWhenEqual - Return true if the specified setcondinst instruction is
479// true when both operands are equal...
480//
481static bool isTrueWhenEqual(Instruction &I) {
482 return I.getOpcode() == Instruction::SetEQ ||
483 I.getOpcode() == Instruction::SetGE ||
484 I.getOpcode() == Instruction::SetLE;
485}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000486
487/// AssociativeOpt - Perform an optimization on an associative operator. This
488/// function is designed to check a chain of associative operators for a
489/// potential to apply a certain optimization. Since the optimization may be
490/// applicable if the expression was reassociated, this checks the chain, then
491/// reassociates the expression as necessary to expose the optimization
492/// opportunity. This makes use of a special Functor, which must define
493/// 'shouldApply' and 'apply' methods.
494///
495template<typename Functor>
496Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
497 unsigned Opcode = Root.getOpcode();
498 Value *LHS = Root.getOperand(0);
499
500 // Quick check, see if the immediate LHS matches...
501 if (F.shouldApply(LHS))
502 return F.apply(Root);
503
504 // Otherwise, if the LHS is not of the same opcode as the root, return.
505 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000506 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000507 // Should we apply this transform to the RHS?
508 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
509
510 // If not to the RHS, check to see if we should apply to the LHS...
511 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
512 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
513 ShouldApply = true;
514 }
515
516 // If the functor wants to apply the optimization to the RHS of LHSI,
517 // reassociate the expression from ((? op A) op B) to (? op (A op B))
518 if (ShouldApply) {
519 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000520
Chris Lattnerb8b97502003-08-13 19:01:45 +0000521 // Now all of the instructions are in the current basic block, go ahead
522 // and perform the reassociation.
523 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
524
525 // First move the selected RHS to the LHS of the root...
526 Root.setOperand(0, LHSI->getOperand(1));
527
528 // Make what used to be the LHS of the root be the user of the root...
529 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000530 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000531 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
532 return 0;
533 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000534 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000535 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000536 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
537 BasicBlock::iterator ARI = &Root; ++ARI;
538 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
539 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000540
541 // Now propagate the ExtraOperand down the chain of instructions until we
542 // get to LHSI.
543 while (TmpLHSI != LHSI) {
544 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000545 // Move the instruction to immediately before the chain we are
546 // constructing to avoid breaking dominance properties.
547 NextLHSI->getParent()->getInstList().remove(NextLHSI);
548 BB->getInstList().insert(ARI, NextLHSI);
549 ARI = NextLHSI;
550
Chris Lattnerb8b97502003-08-13 19:01:45 +0000551 Value *NextOp = NextLHSI->getOperand(1);
552 NextLHSI->setOperand(1, ExtraOperand);
553 TmpLHSI = NextLHSI;
554 ExtraOperand = NextOp;
555 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000556
Chris Lattnerb8b97502003-08-13 19:01:45 +0000557 // Now that the instructions are reassociated, have the functor perform
558 // the transformation...
559 return F.apply(Root);
560 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000561
Chris Lattnerb8b97502003-08-13 19:01:45 +0000562 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
563 }
564 return 0;
565}
566
567
568// AddRHS - Implements: X + X --> X << 1
569struct AddRHS {
570 Value *RHS;
571 AddRHS(Value *rhs) : RHS(rhs) {}
572 bool shouldApply(Value *LHS) const { return LHS == RHS; }
573 Instruction *apply(BinaryOperator &Add) const {
574 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
575 ConstantInt::get(Type::UByteTy, 1));
576 }
577};
578
579// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
580// iff C1&C2 == 0
581struct AddMaskingAnd {
582 Constant *C2;
583 AddMaskingAnd(Constant *c) : C2(c) {}
584 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000585 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000586 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +0000587 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000588 }
589 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000590 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000591 }
592};
593
Chris Lattner86102b82005-01-01 16:22:27 +0000594static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000595 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +0000596 if (isa<CastInst>(I)) {
597 if (Constant *SOC = dyn_cast<Constant>(SO))
598 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000599
Chris Lattner86102b82005-01-01 16:22:27 +0000600 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
601 SO->getName() + ".cast"), I);
602 }
603
Chris Lattner183b3362004-04-09 19:05:30 +0000604 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000605 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
606 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000607
Chris Lattner183b3362004-04-09 19:05:30 +0000608 if (Constant *SOC = dyn_cast<Constant>(SO)) {
609 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +0000610 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
611 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000612 }
613
614 Value *Op0 = SO, *Op1 = ConstOperand;
615 if (!ConstIsRHS)
616 std::swap(Op0, Op1);
617 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +0000618 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
619 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
620 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
621 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000622 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000623 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000624 abort();
625 }
Chris Lattner86102b82005-01-01 16:22:27 +0000626 return IC->InsertNewInstBefore(New, I);
627}
628
629// FoldOpIntoSelect - Given an instruction with a select as one operand and a
630// constant as the other operand, try to fold the binary operator into the
631// select arguments. This also works for Cast instructions, which obviously do
632// not have a second operand.
633static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
634 InstCombiner *IC) {
635 // Don't modify shared select instructions
636 if (!SI->hasOneUse()) return 0;
637 Value *TV = SI->getOperand(1);
638 Value *FV = SI->getOperand(2);
639
640 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +0000641 // Bool selects with constant operands can be folded to logical ops.
642 if (SI->getType() == Type::BoolTy) return 0;
643
Chris Lattner86102b82005-01-01 16:22:27 +0000644 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
645 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
646
647 return new SelectInst(SI->getCondition(), SelectTrueVal,
648 SelectFalseVal);
649 }
650 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +0000651}
652
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000653
654/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
655/// node as operand #0, see if we can fold the instruction into the PHI (which
656/// is only possible if all operands to the PHI are constants).
657Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
658 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000659 unsigned NumPHIValues = PN->getNumIncomingValues();
660 if (!PN->hasOneUse() || NumPHIValues == 0 ||
661 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000662
663 // Check to see if all of the operands of the PHI are constants. If not, we
664 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000665 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000666 if (!isa<Constant>(PN->getIncomingValue(i)))
667 return 0;
668
669 // Okay, we can do the transformation: create the new PHI node.
670 PHINode *NewPN = new PHINode(I.getType(), I.getName());
671 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +0000672 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000673 InsertNewInstBefore(NewPN, *PN);
674
675 // Next, add all of the operands to the PHI.
676 if (I.getNumOperands() == 2) {
677 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000678 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000679 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
680 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
681 PN->getIncomingBlock(i));
682 }
683 } else {
684 assert(isa<CastInst>(I) && "Unary op should be a cast!");
685 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000686 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000687 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
688 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
689 PN->getIncomingBlock(i));
690 }
691 }
692 return ReplaceInstUsesWith(I, NewPN);
693}
694
Chris Lattner113f4f42002-06-25 16:13:24 +0000695Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000696 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000697 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000698
Chris Lattnercf4a9962004-04-10 22:01:55 +0000699 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000700 // X + undef -> undef
701 if (isa<UndefValue>(RHS))
702 return ReplaceInstUsesWith(I, RHS);
703
Chris Lattnercf4a9962004-04-10 22:01:55 +0000704 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +0000705 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
706 if (RHSC->isNullValue())
707 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +0000708 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
709 if (CFP->isExactlyValue(-0.0))
710 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +0000711 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000712
Chris Lattnercf4a9962004-04-10 22:01:55 +0000713 // X + (signbit) --> X ^ signbit
714 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000715 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Andrew Lenharth66229552005-11-02 18:35:40 +0000716 uint64_t Val = CI->getRawValue() & (~0ULL >> (64- NumBits));
Chris Lattner33eb9092004-11-05 04:45:43 +0000717 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000718 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000719 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000720
721 if (isa<PHINode>(LHS))
722 if (Instruction *NV = FoldOpIntoPhi(I))
723 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000724
Chris Lattner330628a2006-01-06 17:59:59 +0000725 ConstantInt *XorRHS = 0;
726 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000727 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
728 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
729 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
730 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
731
732 uint64_t C0080Val = 1ULL << 31;
733 int64_t CFF80Val = -C0080Val;
734 unsigned Size = 32;
735 do {
736 if (TySizeBits > Size) {
737 bool Found = false;
738 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
739 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
740 if (RHSSExt == CFF80Val) {
741 if (XorRHS->getZExtValue() == C0080Val)
742 Found = true;
743 } else if (RHSZExt == C0080Val) {
744 if (XorRHS->getSExtValue() == CFF80Val)
745 Found = true;
746 }
747 if (Found) {
748 // This is a sign extend if the top bits are known zero.
749 Constant *Mask = ConstantInt::getAllOnesValue(XorLHS->getType());
750 Mask = ConstantExpr::getShl(Mask,
751 ConstantInt::get(Type::UByteTy, 64-TySizeBits-Size));
752 if (!MaskedValueIsZero(XorLHS, cast<ConstantInt>(Mask)))
753 Size = 0; // Not a sign ext, but can't be any others either.
754 goto FoundSExt;
755 }
756 }
757 Size >>= 1;
758 C0080Val >>= Size;
759 CFF80Val >>= Size;
760 } while (Size >= 8);
761
762FoundSExt:
763 const Type *MiddleType = 0;
764 switch (Size) {
765 default: break;
766 case 32: MiddleType = Type::IntTy; break;
767 case 16: MiddleType = Type::ShortTy; break;
768 case 8: MiddleType = Type::SByteTy; break;
769 }
770 if (MiddleType) {
771 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
772 InsertNewInstBefore(NewTrunc, I);
773 return new CastInst(NewTrunc, I.getType());
774 }
775 }
Chris Lattnercf4a9962004-04-10 22:01:55 +0000776 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000777
Chris Lattnerb8b97502003-08-13 19:01:45 +0000778 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000779 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000780 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +0000781
782 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
783 if (RHSI->getOpcode() == Instruction::Sub)
784 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
785 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
786 }
787 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
788 if (LHSI->getOpcode() == Instruction::Sub)
789 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
790 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
791 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000792 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000793
Chris Lattner147e9752002-05-08 22:46:53 +0000794 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000795 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000796 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000797
798 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000799 if (!isa<Constant>(RHS))
800 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000801 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000802
Misha Brukmanb1c93172005-04-21 23:48:37 +0000803
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000804 ConstantInt *C2;
805 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
806 if (X == RHS) // X*C + X --> X * (C+1)
807 return BinaryOperator::createMul(RHS, AddOne(C2));
808
809 // X*C1 + X*C2 --> X * (C1+C2)
810 ConstantInt *C1;
811 if (X == dyn_castFoldableMul(RHS, C1))
812 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000813 }
814
815 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000816 if (dyn_castFoldableMul(RHS, C2) == LHS)
817 return BinaryOperator::createMul(LHS, AddOne(C2));
818
Chris Lattner57c8d992003-02-18 19:57:07 +0000819
Chris Lattnerb8b97502003-08-13 19:01:45 +0000820 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000821 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000822 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000823
Chris Lattnerb9cde762003-10-02 15:11:26 +0000824 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +0000825 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +0000826 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
827 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
828 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000829 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000830
Chris Lattnerbff91d92004-10-08 05:07:56 +0000831 // (X & FF00) + xx00 -> (X+xx00) & FF00
832 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
833 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
834 if (Anded == CRHS) {
835 // See if all bits from the first bit set in the Add RHS up are included
836 // in the mask. First, get the rightmost bit.
837 uint64_t AddRHSV = CRHS->getRawValue();
838
839 // Form a mask of all bits from the lowest bit added through the top.
840 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner2f1457f2005-04-24 17:46:05 +0000841 AddRHSHighBits &= ~0ULL >> (64-C2->getType()->getPrimitiveSizeInBits());
Chris Lattnerbff91d92004-10-08 05:07:56 +0000842
843 // See if the and mask includes all of these bits.
844 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000845
Chris Lattnerbff91d92004-10-08 05:07:56 +0000846 if (AddRHSHighBits == AddRHSHighBitsAnd) {
847 // Okay, the xform is safe. Insert the new add pronto.
848 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
849 LHS->getName()), I);
850 return BinaryOperator::createAnd(NewAdd, C2);
851 }
852 }
853 }
854
Chris Lattnerd4252a72004-07-30 07:50:03 +0000855 // Try to fold constant add into select arguments.
856 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +0000857 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +0000858 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000859 }
860
Chris Lattner113f4f42002-06-25 16:13:24 +0000861 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000862}
863
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000864// isSignBit - Return true if the value represented by the constant only has the
865// highest order bit set.
866static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000867 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +0000868 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000869}
870
Chris Lattner022167f2004-03-13 00:11:49 +0000871/// RemoveNoopCast - Strip off nonconverting casts from the value.
872///
873static Value *RemoveNoopCast(Value *V) {
874 if (CastInst *CI = dyn_cast<CastInst>(V)) {
875 const Type *CTy = CI->getType();
876 const Type *OpTy = CI->getOperand(0)->getType();
877 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000878 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +0000879 return RemoveNoopCast(CI->getOperand(0));
880 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
881 return RemoveNoopCast(CI->getOperand(0));
882 }
883 return V;
884}
885
Chris Lattner113f4f42002-06-25 16:13:24 +0000886Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000887 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000888
Chris Lattnere6794492002-08-12 21:17:25 +0000889 if (Op0 == Op1) // sub X, X -> 0
890 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000891
Chris Lattnere6794492002-08-12 21:17:25 +0000892 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000893 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000894 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000895
Chris Lattner81a7a232004-10-16 18:11:37 +0000896 if (isa<UndefValue>(Op0))
897 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
898 if (isa<UndefValue>(Op1))
899 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
900
Chris Lattner8f2f5982003-11-05 01:06:05 +0000901 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
902 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000903 if (C->isAllOnesValue())
904 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000905
Chris Lattner8f2f5982003-11-05 01:06:05 +0000906 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +0000907 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +0000908 if (match(Op1, m_Not(m_Value(X))))
909 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000910 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000911 // -((uint)X >> 31) -> ((int)X >> 31)
912 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000913 if (C->isNullValue()) {
914 Value *NoopCastedRHS = RemoveNoopCast(Op1);
915 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000916 if (SI->getOpcode() == Instruction::Shr)
917 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
918 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000919 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000920 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000921 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000922 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000923 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000924 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000925 // Ok, the transformation is safe. Insert a cast of the incoming
926 // value, then the new shift, then the new cast.
927 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
928 SI->getOperand(0)->getName());
929 Value *InV = InsertNewInstBefore(FirstCast, I);
930 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
931 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000932 if (NewShift->getType() == I.getType())
933 return NewShift;
934 else {
935 InV = InsertNewInstBefore(NewShift, I);
936 return new CastInst(NewShift, I.getType());
937 }
Chris Lattner92295c52004-03-12 23:53:13 +0000938 }
939 }
Chris Lattner022167f2004-03-13 00:11:49 +0000940 }
Chris Lattner183b3362004-04-09 19:05:30 +0000941
942 // Try to fold constant sub into select arguments.
943 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +0000944 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000945 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000946
947 if (isa<PHINode>(Op0))
948 if (Instruction *NV = FoldOpIntoPhi(I))
949 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000950 }
951
Chris Lattnera9be4492005-04-07 16:15:25 +0000952 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
953 if (Op1I->getOpcode() == Instruction::Add &&
954 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000955 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000956 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000957 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000958 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000959 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
960 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
961 // C1-(X+C2) --> (C1-C2)-X
962 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
963 Op1I->getOperand(0));
964 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000965 }
966
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000967 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000968 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
969 // is not used by anyone else...
970 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000971 if (Op1I->getOpcode() == Instruction::Sub &&
972 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000973 // Swap the two operands of the subexpr...
974 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
975 Op1I->setOperand(0, IIOp1);
976 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000977
Chris Lattner3082c5a2003-02-18 19:28:33 +0000978 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000979 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000980 }
981
982 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
983 //
984 if (Op1I->getOpcode() == Instruction::And &&
985 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
986 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
987
Chris Lattner396dbfe2004-06-09 05:08:07 +0000988 Value *NewNot =
989 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000990 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000991 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000992
Chris Lattner0aee4b72004-10-06 15:08:25 +0000993 // -(X sdiv C) -> (X sdiv -C)
994 if (Op1I->getOpcode() == Instruction::Div)
995 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +0000996 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +0000997 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +0000998 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +0000999 ConstantExpr::getNeg(DivRHS));
1000
Chris Lattner57c8d992003-02-18 19:57:07 +00001001 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001002 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001003 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001004 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001005 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001006 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001007 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001008 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001009 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001010
Chris Lattner47060462005-04-07 17:14:51 +00001011 if (!Op0->getType()->isFloatingPoint())
1012 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1013 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001014 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1015 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1016 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1017 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001018 } else if (Op0I->getOpcode() == Instruction::Sub) {
1019 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1020 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001021 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001022
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001023 ConstantInt *C1;
1024 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1025 if (X == Op1) { // X*C - X --> X * (C-1)
1026 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1027 return BinaryOperator::createMul(Op1, CP1);
1028 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001029
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001030 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1031 if (X == dyn_castFoldableMul(Op1, C2))
1032 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1033 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001034 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001035}
1036
Chris Lattnere79e8542004-02-23 06:38:22 +00001037/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1038/// really just returns true if the most significant (sign) bit is set.
1039static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1040 if (RHS->getType()->isSigned()) {
1041 // True if source is LHS < 0 or LHS <= -1
1042 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1043 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1044 } else {
1045 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1046 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1047 // the size of the integer type.
1048 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001049 return RHSC->getValue() ==
1050 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001051 if (Opcode == Instruction::SetGT)
1052 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001053 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001054 }
1055 return false;
1056}
1057
Chris Lattner113f4f42002-06-25 16:13:24 +00001058Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001059 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001060 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001061
Chris Lattner81a7a232004-10-16 18:11:37 +00001062 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1063 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1064
Chris Lattnere6794492002-08-12 21:17:25 +00001065 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001066 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1067 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001068
1069 // ((X << C1)*C2) == (X * (C2 << C1))
1070 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1071 if (SI->getOpcode() == Instruction::Shl)
1072 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001073 return BinaryOperator::createMul(SI->getOperand(0),
1074 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001075
Chris Lattnercce81be2003-09-11 22:24:54 +00001076 if (CI->isNullValue())
1077 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1078 if (CI->equalsInt(1)) // X * 1 == X
1079 return ReplaceInstUsesWith(I, Op0);
1080 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001081 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001082
Chris Lattnercce81be2003-09-11 22:24:54 +00001083 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001084 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1085 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001086 return new ShiftInst(Instruction::Shl, Op0,
1087 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001088 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001089 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001090 if (Op1F->isNullValue())
1091 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001092
Chris Lattner3082c5a2003-02-18 19:28:33 +00001093 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1094 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1095 if (Op1F->getValue() == 1.0)
1096 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1097 }
Chris Lattner183b3362004-04-09 19:05:30 +00001098
1099 // Try to fold constant mul into select arguments.
1100 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001101 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001102 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001103
1104 if (isa<PHINode>(Op0))
1105 if (Instruction *NV = FoldOpIntoPhi(I))
1106 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001107 }
1108
Chris Lattner934a64cf2003-03-10 23:23:04 +00001109 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1110 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001111 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001112
Chris Lattner2635b522004-02-23 05:39:21 +00001113 // If one of the operands of the multiply is a cast from a boolean value, then
1114 // we know the bool is either zero or one, so this is a 'masking' multiply.
1115 // See if we can simplify things based on how the boolean was originally
1116 // formed.
1117 CastInst *BoolCast = 0;
1118 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1119 if (CI->getOperand(0)->getType() == Type::BoolTy)
1120 BoolCast = CI;
1121 if (!BoolCast)
1122 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1123 if (CI->getOperand(0)->getType() == Type::BoolTy)
1124 BoolCast = CI;
1125 if (BoolCast) {
1126 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1127 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1128 const Type *SCOpTy = SCIOp0->getType();
1129
Chris Lattnere79e8542004-02-23 06:38:22 +00001130 // If the setcc is true iff the sign bit of X is set, then convert this
1131 // multiply into a shift/and combination.
1132 if (isa<ConstantInt>(SCIOp1) &&
1133 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001134 // Shift the X value right to turn it into "all signbits".
1135 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001136 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001137 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001138 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001139 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1140 SCIOp0->getName()), I);
1141 }
1142
1143 Value *V =
1144 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1145 BoolCast->getOperand(0)->getName()+
1146 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001147
1148 // If the multiply type is not the same as the source type, sign extend
1149 // or truncate to the multiply type.
1150 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001151 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001152
Chris Lattner2635b522004-02-23 05:39:21 +00001153 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001154 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001155 }
1156 }
1157 }
1158
Chris Lattner113f4f42002-06-25 16:13:24 +00001159 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001160}
1161
Chris Lattner113f4f42002-06-25 16:13:24 +00001162Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001163 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001164
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001165 if (isa<UndefValue>(Op0)) // undef / X -> 0
1166 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1167 if (isa<UndefValue>(Op1))
1168 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1169
1170 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001171 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001172 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001173 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001174
Chris Lattnere20c3342004-04-26 14:01:59 +00001175 // div X, -1 == -X
1176 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001177 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001178
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001179 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001180 if (LHS->getOpcode() == Instruction::Div)
1181 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001182 // (X / C1) / C2 -> X / (C1*C2)
1183 return BinaryOperator::createDiv(LHS->getOperand(0),
1184 ConstantExpr::getMul(RHS, LHSRHS));
1185 }
1186
Chris Lattner3082c5a2003-02-18 19:28:33 +00001187 // Check to see if this is an unsigned division with an exact power of 2,
1188 // if so, convert to a right shift.
1189 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1190 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001191 if (isPowerOf2_64(Val)) {
1192 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001193 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001194 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001195 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001196
Chris Lattner4ad08352004-10-09 02:50:40 +00001197 // -X/C -> X/-C
1198 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001199 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001200 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1201
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001202 if (!RHS->isNullValue()) {
1203 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001204 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001205 return R;
1206 if (isa<PHINode>(Op0))
1207 if (Instruction *NV = FoldOpIntoPhi(I))
1208 return NV;
1209 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001210 }
1211
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001212 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1213 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1214 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1215 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1216 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1217 if (STO->getValue() == 0) { // Couldn't be this argument.
1218 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001219 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001220 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001221 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001222 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001223 }
1224
Chris Lattner42362612005-04-08 04:03:26 +00001225 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001226 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1227 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001228 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1229 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1230 TC, SI->getName()+".t");
1231 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001232
Chris Lattner42362612005-04-08 04:03:26 +00001233 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1234 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1235 FC, SI->getName()+".f");
1236 FSI = InsertNewInstBefore(FSI, I);
1237 return new SelectInst(SI->getOperand(0), TSI, FSI);
1238 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001239 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001240
Chris Lattner3082c5a2003-02-18 19:28:33 +00001241 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001242 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001243 if (LHS->equalsInt(0))
1244 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1245
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001246 if (I.getType()->isSigned()) {
1247 // If the top bits of both operands are zero (i.e. we can prove they are
1248 // unsigned inputs), turn this into a udiv.
1249 ConstantIntegral *MaskV = ConstantSInt::getMinValue(I.getType());
1250 if (MaskedValueIsZero(Op1, MaskV) && MaskedValueIsZero(Op0, MaskV)) {
1251 const Type *NTy = Op0->getType()->getUnsignedVersion();
1252 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1253 InsertNewInstBefore(LHS, I);
1254 Value *RHS;
1255 if (Constant *R = dyn_cast<Constant>(Op1))
1256 RHS = ConstantExpr::getCast(R, NTy);
1257 else
1258 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1259 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1260 InsertNewInstBefore(Div, I);
1261 return new CastInst(Div, I.getType());
1262 }
1263 }
1264
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001265 return 0;
1266}
1267
1268
Chris Lattner113f4f42002-06-25 16:13:24 +00001269Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001270 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001271 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001272 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001273 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001274 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001275 // X % -Y -> X % Y
1276 AddUsesToWorkList(I);
1277 I.setOperand(1, RHSNeg);
1278 return &I;
1279 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001280
1281 // If the top bits of both operands are zero (i.e. we can prove they are
1282 // unsigned inputs), turn this into a urem.
1283 ConstantIntegral *MaskV = ConstantSInt::getMinValue(I.getType());
1284 if (MaskedValueIsZero(Op1, MaskV) && MaskedValueIsZero(Op0, MaskV)) {
1285 const Type *NTy = Op0->getType()->getUnsignedVersion();
1286 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1287 InsertNewInstBefore(LHS, I);
1288 Value *RHS;
1289 if (Constant *R = dyn_cast<Constant>(Op1))
1290 RHS = ConstantExpr::getCast(R, NTy);
1291 else
1292 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1293 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1294 InsertNewInstBefore(Rem, I);
1295 return new CastInst(Rem, I.getType());
1296 }
1297 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00001298
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001299 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001300 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001301 if (isa<UndefValue>(Op1))
1302 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001303
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001304 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001305 if (RHS->equalsInt(1)) // X % 1 == 0
1306 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1307
1308 // Check to see if this is an unsigned remainder with an exact power of 2,
1309 // if so, convert to a bitwise and.
1310 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1311 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001312 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001313 return BinaryOperator::createAnd(Op0,
1314 ConstantUInt::get(I.getType(), Val-1));
1315
1316 if (!RHS->isNullValue()) {
1317 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001318 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001319 return R;
1320 if (isa<PHINode>(Op0))
1321 if (Instruction *NV = FoldOpIntoPhi(I))
1322 return NV;
1323 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001324 }
1325
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001326 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1327 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1328 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1329 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1330 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1331 if (STO->getValue() == 0) { // Couldn't be this argument.
1332 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001333 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001334 } else if (SFO->getValue() == 0) {
1335 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001336 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001337 }
1338
1339 if (!(STO->getValue() & (STO->getValue()-1)) &&
1340 !(SFO->getValue() & (SFO->getValue()-1))) {
1341 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1342 SubOne(STO), SI->getName()+".t"), I);
1343 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1344 SubOne(SFO), SI->getName()+".f"), I);
1345 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1346 }
1347 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001348
Chris Lattner3082c5a2003-02-18 19:28:33 +00001349 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001350 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001351 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001352 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1353
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001354 return 0;
1355}
1356
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001357// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001358static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001359 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1360 // Calculate -1 casted to the right type...
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001361 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001362 uint64_t Val = ~0ULL; // All ones
1363 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1364 return CU->getValue() == Val-1;
1365 }
1366
1367 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001368
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001369 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001370 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001371 int64_t Val = INT64_MAX; // All ones
1372 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1373 return CS->getValue() == Val-1;
1374}
1375
1376// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001377static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001378 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1379 return CU->getValue() == 1;
1380
1381 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001382
1383 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001384 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001385 int64_t Val = -1; // All ones
1386 Val <<= TypeBits-1; // Shift over to the right spot
1387 return CS->getValue() == Val+1;
1388}
1389
Chris Lattner35167c32004-06-09 07:59:58 +00001390// isOneBitSet - Return true if there is exactly one bit set in the specified
1391// constant.
1392static bool isOneBitSet(const ConstantInt *CI) {
1393 uint64_t V = CI->getRawValue();
1394 return V && (V & (V-1)) == 0;
1395}
1396
Chris Lattner8fc5af42004-09-23 21:46:38 +00001397#if 0 // Currently unused
1398// isLowOnes - Return true if the constant is of the form 0+1+.
1399static bool isLowOnes(const ConstantInt *CI) {
1400 uint64_t V = CI->getRawValue();
1401
1402 // There won't be bits set in parts that the type doesn't contain.
1403 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1404
1405 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1406 return U && V && (U & V) == 0;
1407}
1408#endif
1409
1410// isHighOnes - Return true if the constant is of the form 1+0+.
1411// This is the same as lowones(~X).
1412static bool isHighOnes(const ConstantInt *CI) {
1413 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00001414 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00001415
1416 // There won't be bits set in parts that the type doesn't contain.
1417 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1418
1419 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1420 return U && V && (U & V) == 0;
1421}
1422
1423
Chris Lattner3ac7c262003-08-13 20:16:26 +00001424/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1425/// are carefully arranged to allow folding of expressions such as:
1426///
1427/// (A < B) | (A > B) --> (A != B)
1428///
1429/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1430/// represents that the comparison is true if A == B, and bit value '1' is true
1431/// if A < B.
1432///
1433static unsigned getSetCondCode(const SetCondInst *SCI) {
1434 switch (SCI->getOpcode()) {
1435 // False -> 0
1436 case Instruction::SetGT: return 1;
1437 case Instruction::SetEQ: return 2;
1438 case Instruction::SetGE: return 3;
1439 case Instruction::SetLT: return 4;
1440 case Instruction::SetNE: return 5;
1441 case Instruction::SetLE: return 6;
1442 // True -> 7
1443 default:
1444 assert(0 && "Invalid SetCC opcode!");
1445 return 0;
1446 }
1447}
1448
1449/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1450/// opcode and two operands into either a constant true or false, or a brand new
1451/// SetCC instruction.
1452static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1453 switch (Opcode) {
1454 case 0: return ConstantBool::False;
1455 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1456 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1457 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1458 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1459 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1460 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1461 case 7: return ConstantBool::True;
1462 default: assert(0 && "Illegal SetCCCode!"); return 0;
1463 }
1464}
1465
1466// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1467struct FoldSetCCLogical {
1468 InstCombiner &IC;
1469 Value *LHS, *RHS;
1470 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1471 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1472 bool shouldApply(Value *V) const {
1473 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1474 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1475 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1476 return false;
1477 }
1478 Instruction *apply(BinaryOperator &Log) const {
1479 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1480 if (SCI->getOperand(0) != LHS) {
1481 assert(SCI->getOperand(1) == LHS);
1482 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1483 }
1484
1485 unsigned LHSCode = getSetCondCode(SCI);
1486 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1487 unsigned Code;
1488 switch (Log.getOpcode()) {
1489 case Instruction::And: Code = LHSCode & RHSCode; break;
1490 case Instruction::Or: Code = LHSCode | RHSCode; break;
1491 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001492 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001493 }
1494
1495 Value *RV = getSetCCValue(Code, LHS, RHS);
1496 if (Instruction *I = dyn_cast<Instruction>(RV))
1497 return I;
1498 // Otherwise, it's a constant boolean value...
1499 return IC.ReplaceInstUsesWith(Log, RV);
1500 }
1501};
1502
Chris Lattnerba1cb382003-09-19 17:17:26 +00001503// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1504// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1505// guaranteed to be either a shift instruction or a binary operator.
1506Instruction *InstCombiner::OptAndOp(Instruction *Op,
1507 ConstantIntegral *OpRHS,
1508 ConstantIntegral *AndRHS,
1509 BinaryOperator &TheAnd) {
1510 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001511 Constant *Together = 0;
1512 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001513 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001514
Chris Lattnerba1cb382003-09-19 17:17:26 +00001515 switch (Op->getOpcode()) {
1516 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001517 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001518 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1519 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001520 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001521 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001522 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001523 }
1524 break;
1525 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001526 if (Together == AndRHS) // (X | C) & C --> C
1527 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001528
Chris Lattner86102b82005-01-01 16:22:27 +00001529 if (Op->hasOneUse() && Together != OpRHS) {
1530 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1531 std::string Op0Name = Op->getName(); Op->setName("");
1532 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1533 InsertNewInstBefore(Or, TheAnd);
1534 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001535 }
1536 break;
1537 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001538 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001539 // Adding a one to a single bit bit-field should be turned into an XOR
1540 // of the bit. First thing to check is to see if this AND is with a
1541 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001542 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001543
1544 // Clear bits that are not part of the constant.
Chris Lattner2f1457f2005-04-24 17:46:05 +00001545 AndRHSV &= ~0ULL >> (64-AndRHS->getType()->getPrimitiveSizeInBits());
Chris Lattnerba1cb382003-09-19 17:17:26 +00001546
1547 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001548 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001549 // Ok, at this point, we know that we are masking the result of the
1550 // ADD down to exactly one bit. If the constant we are adding has
1551 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001552 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001553
Chris Lattnerba1cb382003-09-19 17:17:26 +00001554 // Check to see if any bits below the one bit set in AndRHSV are set.
1555 if ((AddRHS & (AndRHSV-1)) == 0) {
1556 // If not, the only thing that can effect the output of the AND is
1557 // the bit specified by AndRHSV. If that bit is set, the effect of
1558 // the XOR is to toggle the bit. If it is clear, then the ADD has
1559 // no effect.
1560 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1561 TheAnd.setOperand(0, X);
1562 return &TheAnd;
1563 } else {
1564 std::string Name = Op->getName(); Op->setName("");
1565 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001566 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001567 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001568 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001569 }
1570 }
1571 }
1572 }
1573 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001574
1575 case Instruction::Shl: {
1576 // We know that the AND will not produce any of the bits shifted in, so if
1577 // the anded constant includes them, clear them now!
1578 //
1579 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001580 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1581 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001582
Chris Lattner7e794272004-09-24 15:21:34 +00001583 if (CI == ShlMask) { // Masking out bits that the shift already masks
1584 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1585 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001586 TheAnd.setOperand(1, CI);
1587 return &TheAnd;
1588 }
1589 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001590 }
Chris Lattner2da29172003-09-19 19:05:02 +00001591 case Instruction::Shr:
1592 // We know that the AND will not produce any of the bits shifted in, so if
1593 // the anded constant includes them, clear them now! This only applies to
1594 // unsigned shifts, because a signed shr may bring in set bits!
1595 //
1596 if (AndRHS->getType()->isUnsigned()) {
1597 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001598 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1599 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1600
1601 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1602 return ReplaceInstUsesWith(TheAnd, Op);
1603 } else if (CI != AndRHS) {
1604 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001605 return &TheAnd;
1606 }
Chris Lattner7e794272004-09-24 15:21:34 +00001607 } else { // Signed shr.
1608 // See if this is shifting in some sign extension, then masking it out
1609 // with an and.
1610 if (Op->hasOneUse()) {
1611 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1612 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1613 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001614 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001615 // Make the argument unsigned.
1616 Value *ShVal = Op->getOperand(0);
1617 ShVal = InsertCastBefore(ShVal,
1618 ShVal->getType()->getUnsignedVersion(),
1619 TheAnd);
1620 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1621 OpRHS, Op->getName()),
1622 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001623 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1624 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1625 TheAnd.getName()),
1626 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001627 return new CastInst(ShVal, Op->getType());
1628 }
1629 }
Chris Lattner2da29172003-09-19 19:05:02 +00001630 }
1631 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001632 }
1633 return 0;
1634}
1635
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001636
Chris Lattner6862fbd2004-09-29 17:40:11 +00001637/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1638/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1639/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1640/// insert new instructions.
1641Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1642 bool Inside, Instruction &IB) {
1643 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1644 "Lo is not <= Hi in range emission code!");
1645 if (Inside) {
1646 if (Lo == Hi) // Trivially false.
1647 return new SetCondInst(Instruction::SetNE, V, V);
1648 if (cast<ConstantIntegral>(Lo)->isMinValue())
1649 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001650
Chris Lattner6862fbd2004-09-29 17:40:11 +00001651 Constant *AddCST = ConstantExpr::getNeg(Lo);
1652 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1653 InsertNewInstBefore(Add, IB);
1654 // Convert to unsigned for the comparison.
1655 const Type *UnsType = Add->getType()->getUnsignedVersion();
1656 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1657 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1658 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1659 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1660 }
1661
1662 if (Lo == Hi) // Trivially true.
1663 return new SetCondInst(Instruction::SetEQ, V, V);
1664
1665 Hi = SubOne(cast<ConstantInt>(Hi));
1666 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1667 return new SetCondInst(Instruction::SetGT, V, Hi);
1668
1669 // Emit X-Lo > Hi-Lo-1
1670 Constant *AddCST = ConstantExpr::getNeg(Lo);
1671 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1672 InsertNewInstBefore(Add, IB);
1673 // Convert to unsigned for the comparison.
1674 const Type *UnsType = Add->getType()->getUnsignedVersion();
1675 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1676 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1677 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1678 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1679}
1680
Chris Lattnerb4b25302005-09-18 07:22:02 +00001681// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1682// any number of 0s on either side. The 1s are allowed to wrap from LSB to
1683// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1684// not, since all 1s are not contiguous.
1685static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
1686 uint64_t V = Val->getRawValue();
1687 if (!isShiftedMask_64(V)) return false;
1688
1689 // look for the first zero bit after the run of ones
1690 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
1691 // look for the first non-zero bit
1692 ME = 64-CountLeadingZeros_64(V);
1693 return true;
1694}
1695
1696
1697
1698/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1699/// where isSub determines whether the operator is a sub. If we can fold one of
1700/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00001701///
1702/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1703/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1704/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1705///
1706/// return (A +/- B).
1707///
1708Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1709 ConstantIntegral *Mask, bool isSub,
1710 Instruction &I) {
1711 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1712 if (!LHSI || LHSI->getNumOperands() != 2 ||
1713 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1714
1715 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1716
1717 switch (LHSI->getOpcode()) {
1718 default: return 0;
1719 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001720 if (ConstantExpr::getAnd(N, Mask) == Mask) {
1721 // If the AndRHS is a power of two minus one (0+1+), this is simple.
1722 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
1723 break;
1724
1725 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1726 // part, we don't need any explicit masks to take them out of A. If that
1727 // is all N is, ignore it.
1728 unsigned MB, ME;
1729 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
1730 Constant *Mask = ConstantInt::getAllOnesValue(RHS->getType());
1731 Mask = ConstantExpr::getUShr(Mask,
1732 ConstantInt::get(Type::UByteTy,
1733 (64-MB+1)));
1734 if (MaskedValueIsZero(RHS, cast<ConstantIntegral>(Mask)))
1735 break;
1736 }
1737 }
Chris Lattneraf517572005-09-18 04:24:45 +00001738 return 0;
1739 case Instruction::Or:
1740 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001741 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
1742 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
1743 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00001744 break;
1745 return 0;
1746 }
1747
1748 Instruction *New;
1749 if (isSub)
1750 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
1751 else
1752 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
1753 return InsertNewInstBefore(New, I);
1754}
1755
Chris Lattner113f4f42002-06-25 16:13:24 +00001756Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001757 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001758 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001759
Chris Lattner81a7a232004-10-16 18:11:37 +00001760 if (isa<UndefValue>(Op1)) // X & undef -> 0
1761 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1762
Chris Lattner86102b82005-01-01 16:22:27 +00001763 // and X, X = X
1764 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00001765 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001766
Chris Lattner86102b82005-01-01 16:22:27 +00001767 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001768 // and X, -1 == X
1769 if (AndRHS->isAllOnesValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001770 return ReplaceInstUsesWith(I, Op0);
Chris Lattner38a1b002005-10-26 17:18:16 +00001771
1772 // and (and X, c1), c2 -> and (x, c1&c2). Handle this case here, before
1773 // calling MaskedValueIsZero, to avoid inefficient cases where we traipse
1774 // through many levels of ands.
1775 {
Chris Lattner330628a2006-01-06 17:59:59 +00001776 Value *X = 0; ConstantInt *C1 = 0;
Chris Lattner38a1b002005-10-26 17:18:16 +00001777 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))))
1778 return BinaryOperator::createAnd(X, ConstantExpr::getAnd(C1, AndRHS));
1779 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001780
Chris Lattner86102b82005-01-01 16:22:27 +00001781 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1782 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1783
1784 // If the mask is not masking out any bits, there is no reason to do the
1785 // and in the first place.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001786 ConstantIntegral *NotAndRHS =
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001787 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001788 if (MaskedValueIsZero(Op0, NotAndRHS))
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001789 return ReplaceInstUsesWith(I, Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001790
Chris Lattnerba1cb382003-09-19 17:17:26 +00001791 // Optimize a variety of ((val OP C1) & C2) combinations...
1792 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1793 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001794 Value *Op0LHS = Op0I->getOperand(0);
1795 Value *Op0RHS = Op0I->getOperand(1);
1796 switch (Op0I->getOpcode()) {
1797 case Instruction::Xor:
1798 case Instruction::Or:
1799 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1800 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1801 if (MaskedValueIsZero(Op0LHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001802 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattner86102b82005-01-01 16:22:27 +00001803 if (MaskedValueIsZero(Op0RHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001804 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001805
1806 // If the mask is only needed on one incoming arm, push it up.
1807 if (Op0I->hasOneUse()) {
1808 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1809 // Not masking anything out for the LHS, move to RHS.
1810 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1811 Op0RHS->getName()+".masked");
1812 InsertNewInstBefore(NewRHS, I);
1813 return BinaryOperator::create(
1814 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001815 }
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001816 if (!isa<Constant>(NotAndRHS) &&
1817 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1818 // Not masking anything out for the RHS, move to LHS.
1819 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1820 Op0LHS->getName()+".masked");
1821 InsertNewInstBefore(NewLHS, I);
1822 return BinaryOperator::create(
1823 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1824 }
1825 }
1826
Chris Lattner86102b82005-01-01 16:22:27 +00001827 break;
1828 case Instruction::And:
1829 // (X & V) & C2 --> 0 iff (V & C2) == 0
1830 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1831 MaskedValueIsZero(Op0RHS, AndRHS))
1832 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1833 break;
Chris Lattneraf517572005-09-18 04:24:45 +00001834 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001835 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1836 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1837 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1838 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1839 return BinaryOperator::createAnd(V, AndRHS);
1840 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1841 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00001842 break;
1843
1844 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001845 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1846 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1847 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1848 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1849 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00001850 break;
Chris Lattner86102b82005-01-01 16:22:27 +00001851 }
1852
Chris Lattner16464b32003-07-23 19:25:52 +00001853 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00001854 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001855 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00001856 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1857 const Type *SrcTy = CI->getOperand(0)->getType();
1858
Chris Lattner2c14cf72005-08-07 07:03:10 +00001859 // If this is an integer truncation or change from signed-to-unsigned, and
1860 // if the source is an and/or with immediate, transform it. This
1861 // frequently occurs for bitfield accesses.
1862 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
1863 if (SrcTy->getPrimitiveSizeInBits() >=
1864 I.getType()->getPrimitiveSizeInBits() &&
1865 CastOp->getNumOperands() == 2)
1866 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
1867 if (CastOp->getOpcode() == Instruction::And) {
1868 // Change: and (cast (and X, C1) to T), C2
1869 // into : and (cast X to T), trunc(C1)&C2
1870 // This will folds the two ands together, which may allow other
1871 // simplifications.
1872 Instruction *NewCast =
1873 new CastInst(CastOp->getOperand(0), I.getType(),
1874 CastOp->getName()+".shrunk");
1875 NewCast = InsertNewInstBefore(NewCast, I);
1876
1877 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1878 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
1879 return BinaryOperator::createAnd(NewCast, C3);
1880 } else if (CastOp->getOpcode() == Instruction::Or) {
1881 // Change: and (cast (or X, C1) to T), C2
1882 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
1883 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1884 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
1885 return ReplaceInstUsesWith(I, AndRHS);
1886 }
1887 }
1888
1889
Chris Lattner86102b82005-01-01 16:22:27 +00001890 // If this is an integer sign or zero extension instruction.
1891 if (SrcTy->isIntegral() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001892 SrcTy->getPrimitiveSizeInBits() <
1893 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00001894
1895 if (SrcTy->isUnsigned()) {
1896 // See if this and is clearing out bits that are known to be zero
1897 // anyway (due to the zero extension).
1898 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1899 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1900 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1901 if (Result == Mask) // The "and" isn't doing anything, remove it.
1902 return ReplaceInstUsesWith(I, CI);
1903 if (Result != AndRHS) { // Reduce the and RHS constant.
1904 I.setOperand(1, Result);
1905 return &I;
1906 }
1907
1908 } else {
1909 if (CI->hasOneUse() && SrcTy->isInteger()) {
1910 // We can only do this if all of the sign bits brought in are masked
1911 // out. Compute this by first getting 0000011111, then inverting
1912 // it.
1913 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1914 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1915 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1916 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1917 // If the and is clearing all of the sign bits, change this to a
1918 // zero extension cast. To do this, cast the cast input to
1919 // unsigned, then to the requested size.
1920 Value *CastOp = CI->getOperand(0);
1921 Instruction *NC =
1922 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1923 CI->getName()+".uns");
1924 NC = InsertNewInstBefore(NC, I);
1925 // Finally, insert a replacement for CI.
1926 NC = new CastInst(NC, CI->getType(), CI->getName());
1927 CI->setName("");
1928 NC = InsertNewInstBefore(NC, I);
1929 WorkList.push_back(CI); // Delete CI later.
1930 I.setOperand(0, NC);
1931 return &I; // The AND operand was modified.
1932 }
1933 }
1934 }
1935 }
Chris Lattner33217db2003-07-23 19:36:21 +00001936 }
Chris Lattner183b3362004-04-09 19:05:30 +00001937
1938 // Try to fold constant and into select arguments.
1939 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001940 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001941 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001942 if (isa<PHINode>(Op0))
1943 if (Instruction *NV = FoldOpIntoPhi(I))
1944 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001945 }
1946
Chris Lattnerbb74e222003-03-10 23:06:50 +00001947 Value *Op0NotVal = dyn_castNotVal(Op0);
1948 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001949
Chris Lattner023a4832004-06-18 06:07:51 +00001950 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1951 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1952
Misha Brukman9c003d82004-07-30 12:50:08 +00001953 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001954 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001955 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1956 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001957 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001958 return BinaryOperator::createNot(Or);
1959 }
1960
Chris Lattner623826c2004-09-28 21:48:02 +00001961 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1962 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001963 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1964 return R;
1965
Chris Lattner623826c2004-09-28 21:48:02 +00001966 Value *LHSVal, *RHSVal;
1967 ConstantInt *LHSCst, *RHSCst;
1968 Instruction::BinaryOps LHSCC, RHSCC;
1969 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1970 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1971 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1972 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001973 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00001974 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1975 // Ensure that the larger constant is on the RHS.
1976 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1977 SetCondInst *LHS = cast<SetCondInst>(Op0);
1978 if (cast<ConstantBool>(Cmp)->getValue()) {
1979 std::swap(LHS, RHS);
1980 std::swap(LHSCst, RHSCst);
1981 std::swap(LHSCC, RHSCC);
1982 }
1983
1984 // At this point, we know we have have two setcc instructions
1985 // comparing a value against two constants and and'ing the result
1986 // together. Because of the above check, we know that we only have
1987 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1988 // FoldSetCCLogical check above), that the two constants are not
1989 // equal.
1990 assert(LHSCst != RHSCst && "Compares not folded above?");
1991
1992 switch (LHSCC) {
1993 default: assert(0 && "Unknown integer condition code!");
1994 case Instruction::SetEQ:
1995 switch (RHSCC) {
1996 default: assert(0 && "Unknown integer condition code!");
1997 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1998 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1999 return ReplaceInstUsesWith(I, ConstantBool::False);
2000 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2001 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2002 return ReplaceInstUsesWith(I, LHS);
2003 }
2004 case Instruction::SetNE:
2005 switch (RHSCC) {
2006 default: assert(0 && "Unknown integer condition code!");
2007 case Instruction::SetLT:
2008 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2009 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2010 break; // (X != 13 & X < 15) -> no change
2011 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2012 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2013 return ReplaceInstUsesWith(I, RHS);
2014 case Instruction::SetNE:
2015 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2016 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2017 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2018 LHSVal->getName()+".off");
2019 InsertNewInstBefore(Add, I);
2020 const Type *UnsType = Add->getType()->getUnsignedVersion();
2021 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2022 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2023 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2024 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2025 }
2026 break; // (X != 13 & X != 15) -> no change
2027 }
2028 break;
2029 case Instruction::SetLT:
2030 switch (RHSCC) {
2031 default: assert(0 && "Unknown integer condition code!");
2032 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2033 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2034 return ReplaceInstUsesWith(I, ConstantBool::False);
2035 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2036 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2037 return ReplaceInstUsesWith(I, LHS);
2038 }
2039 case Instruction::SetGT:
2040 switch (RHSCC) {
2041 default: assert(0 && "Unknown integer condition code!");
2042 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2043 return ReplaceInstUsesWith(I, LHS);
2044 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2045 return ReplaceInstUsesWith(I, RHS);
2046 case Instruction::SetNE:
2047 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2048 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2049 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002050 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2051 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002052 }
2053 }
2054 }
2055 }
2056
Chris Lattner113f4f42002-06-25 16:13:24 +00002057 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002058}
2059
Chris Lattner113f4f42002-06-25 16:13:24 +00002060Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002061 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002062 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002063
Chris Lattner81a7a232004-10-16 18:11:37 +00002064 if (isa<UndefValue>(Op1))
2065 return ReplaceInstUsesWith(I, // X | undef -> -1
2066 ConstantIntegral::getAllOnesValue(I.getType()));
2067
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002068 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00002069 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2070 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002071
2072 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00002073 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00002074 // If X is known to only contain bits that already exist in RHS, just
2075 // replace this instruction with RHS directly.
2076 if (MaskedValueIsZero(Op0,
2077 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
2078 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002079
Chris Lattner330628a2006-01-06 17:59:59 +00002080 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002081 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2082 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002083 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2084 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00002085 InsertNewInstBefore(Or, I);
2086 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2087 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00002088
Chris Lattnerd4252a72004-07-30 07:50:03 +00002089 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2090 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2091 std::string Op0Name = Op0->getName(); Op0->setName("");
2092 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2093 InsertNewInstBefore(Or, I);
2094 return BinaryOperator::createXor(Or,
2095 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00002096 }
Chris Lattner183b3362004-04-09 19:05:30 +00002097
2098 // Try to fold constant and into select arguments.
2099 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002100 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002101 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002102 if (isa<PHINode>(Op0))
2103 if (Instruction *NV = FoldOpIntoPhi(I))
2104 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00002105 }
2106
Chris Lattner330628a2006-01-06 17:59:59 +00002107 Value *A = 0, *B = 0;
2108 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00002109
2110 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2111 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2112 return ReplaceInstUsesWith(I, Op1);
2113 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2114 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2115 return ReplaceInstUsesWith(I, Op0);
2116
Chris Lattnerb62f5082005-05-09 04:58:36 +00002117 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2118 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2119 MaskedValueIsZero(Op1, C1)) {
2120 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2121 Op0->setName("");
2122 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2123 }
2124
2125 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2126 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2127 MaskedValueIsZero(Op0, C1)) {
2128 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2129 Op0->setName("");
2130 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2131 }
2132
Chris Lattner15212982005-09-18 03:42:07 +00002133 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00002134 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00002135 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2136
2137 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2138 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2139
2140
Chris Lattner01f56c62005-09-18 06:02:59 +00002141 // If we have: ((V + N) & C1) | (V & C2)
2142 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2143 // replace with V+N.
2144 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002145 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00002146 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2147 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2148 // Add commutes, try both ways.
2149 if (V1 == B && MaskedValueIsZero(V2, C2))
2150 return ReplaceInstUsesWith(I, A);
2151 if (V2 == B && MaskedValueIsZero(V1, C2))
2152 return ReplaceInstUsesWith(I, A);
2153 }
2154 // Or commutes, try both ways.
2155 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2156 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2157 // Add commutes, try both ways.
2158 if (V1 == A && MaskedValueIsZero(V2, C1))
2159 return ReplaceInstUsesWith(I, B);
2160 if (V2 == A && MaskedValueIsZero(V1, C1))
2161 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00002162 }
2163 }
2164 }
Chris Lattner812aab72003-08-12 19:11:07 +00002165
Chris Lattnerd4252a72004-07-30 07:50:03 +00002166 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2167 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00002168 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002169 ConstantIntegral::getAllOnesValue(I.getType()));
2170 } else {
2171 A = 0;
2172 }
Chris Lattner4294cec2005-05-07 23:49:08 +00002173 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00002174 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2175 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00002176 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002177 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00002178
Misha Brukman9c003d82004-07-30 12:50:08 +00002179 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00002180 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2181 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2182 I.getName()+".demorgan"), I);
2183 return BinaryOperator::createNot(And);
2184 }
Chris Lattner3e327a42003-03-10 23:13:59 +00002185 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002186
Chris Lattner3ac7c262003-08-13 20:16:26 +00002187 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002188 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002189 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2190 return R;
2191
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002192 Value *LHSVal, *RHSVal;
2193 ConstantInt *LHSCst, *RHSCst;
2194 Instruction::BinaryOps LHSCC, RHSCC;
2195 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2196 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2197 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2198 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002199 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002200 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2201 // Ensure that the larger constant is on the RHS.
2202 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2203 SetCondInst *LHS = cast<SetCondInst>(Op0);
2204 if (cast<ConstantBool>(Cmp)->getValue()) {
2205 std::swap(LHS, RHS);
2206 std::swap(LHSCst, RHSCst);
2207 std::swap(LHSCC, RHSCC);
2208 }
2209
2210 // At this point, we know we have have two setcc instructions
2211 // comparing a value against two constants and or'ing the result
2212 // together. Because of the above check, we know that we only have
2213 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2214 // FoldSetCCLogical check above), that the two constants are not
2215 // equal.
2216 assert(LHSCst != RHSCst && "Compares not folded above?");
2217
2218 switch (LHSCC) {
2219 default: assert(0 && "Unknown integer condition code!");
2220 case Instruction::SetEQ:
2221 switch (RHSCC) {
2222 default: assert(0 && "Unknown integer condition code!");
2223 case Instruction::SetEQ:
2224 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2225 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2226 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2227 LHSVal->getName()+".off");
2228 InsertNewInstBefore(Add, I);
2229 const Type *UnsType = Add->getType()->getUnsignedVersion();
2230 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2231 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2232 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2233 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2234 }
2235 break; // (X == 13 | X == 15) -> no change
2236
Chris Lattner5c219462005-04-19 06:04:18 +00002237 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2238 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002239 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2240 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2241 return ReplaceInstUsesWith(I, RHS);
2242 }
2243 break;
2244 case Instruction::SetNE:
2245 switch (RHSCC) {
2246 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002247 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2248 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2249 return ReplaceInstUsesWith(I, LHS);
2250 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00002251 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002252 return ReplaceInstUsesWith(I, ConstantBool::True);
2253 }
2254 break;
2255 case Instruction::SetLT:
2256 switch (RHSCC) {
2257 default: assert(0 && "Unknown integer condition code!");
2258 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2259 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002260 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2261 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002262 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2263 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2264 return ReplaceInstUsesWith(I, RHS);
2265 }
2266 break;
2267 case Instruction::SetGT:
2268 switch (RHSCC) {
2269 default: assert(0 && "Unknown integer condition code!");
2270 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2271 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2272 return ReplaceInstUsesWith(I, LHS);
2273 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2274 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2275 return ReplaceInstUsesWith(I, ConstantBool::True);
2276 }
2277 }
2278 }
2279 }
Chris Lattner15212982005-09-18 03:42:07 +00002280
Chris Lattner113f4f42002-06-25 16:13:24 +00002281 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002282}
2283
Chris Lattnerc2076352004-02-16 01:20:27 +00002284// XorSelf - Implements: X ^ X --> 0
2285struct XorSelf {
2286 Value *RHS;
2287 XorSelf(Value *rhs) : RHS(rhs) {}
2288 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2289 Instruction *apply(BinaryOperator &Xor) const {
2290 return &Xor;
2291 }
2292};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002293
2294
Chris Lattner113f4f42002-06-25 16:13:24 +00002295Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002296 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002297 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002298
Chris Lattner81a7a232004-10-16 18:11:37 +00002299 if (isa<UndefValue>(Op1))
2300 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2301
Chris Lattnerc2076352004-02-16 01:20:27 +00002302 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2303 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2304 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002305 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002306 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002307
Chris Lattner97638592003-07-23 21:37:07 +00002308 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002309 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00002310 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00002311 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002312
Chris Lattner97638592003-07-23 21:37:07 +00002313 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002314 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002315 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002316 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002317 return new SetCondInst(SCI->getInverseCondition(),
2318 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002319
Chris Lattner8f2f5982003-11-05 01:06:05 +00002320 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002321 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2322 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002323 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2324 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002325 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002326 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002327 }
Chris Lattner023a4832004-06-18 06:07:51 +00002328
2329 // ~(~X & Y) --> (X | ~Y)
2330 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2331 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2332 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2333 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002334 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002335 Op0I->getOperand(1)->getName()+".not");
2336 InsertNewInstBefore(NotY, I);
2337 return BinaryOperator::createOr(Op0NotVal, NotY);
2338 }
2339 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002340
Chris Lattner97638592003-07-23 21:37:07 +00002341 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002342 switch (Op0I->getOpcode()) {
2343 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002344 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002345 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002346 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2347 return BinaryOperator::createSub(
2348 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002349 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002350 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002351 }
Chris Lattnere5806662003-11-04 23:50:51 +00002352 break;
2353 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002354 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002355 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2356 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002357 break;
2358 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002359 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002360 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002361 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002362 break;
2363 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002364 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002365 }
Chris Lattner183b3362004-04-09 19:05:30 +00002366
2367 // Try to fold constant and into select arguments.
2368 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002369 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002370 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002371 if (isa<PHINode>(Op0))
2372 if (Instruction *NV = FoldOpIntoPhi(I))
2373 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002374 }
2375
Chris Lattnerbb74e222003-03-10 23:06:50 +00002376 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002377 if (X == Op1)
2378 return ReplaceInstUsesWith(I,
2379 ConstantIntegral::getAllOnesValue(I.getType()));
2380
Chris Lattnerbb74e222003-03-10 23:06:50 +00002381 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002382 if (X == Op0)
2383 return ReplaceInstUsesWith(I,
2384 ConstantIntegral::getAllOnesValue(I.getType()));
2385
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002386 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002387 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002388 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2389 cast<BinaryOperator>(Op1I)->swapOperands();
2390 I.swapOperands();
2391 std::swap(Op0, Op1);
2392 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2393 I.swapOperands();
2394 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002395 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002396 } else if (Op1I->getOpcode() == Instruction::Xor) {
2397 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2398 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2399 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2400 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2401 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002402
2403 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002404 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002405 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2406 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002407 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002408 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2409 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002410 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002411 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002412 } else if (Op0I->getOpcode() == Instruction::Xor) {
2413 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2414 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2415 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2416 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002417 }
2418
Chris Lattner7aa2d472004-08-01 19:42:59 +00002419 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner330628a2006-01-06 17:59:59 +00002420 ConstantInt *C1 = 0, *C2 = 0;
2421 if (match(Op0, m_And(m_Value(), m_ConstantInt(C1))) &&
2422 match(Op1, m_And(m_Value(), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002423 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002424 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002425
Chris Lattner3ac7c262003-08-13 20:16:26 +00002426 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2427 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2428 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2429 return R;
2430
Chris Lattner113f4f42002-06-25 16:13:24 +00002431 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002432}
2433
Chris Lattner6862fbd2004-09-29 17:40:11 +00002434/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2435/// overflowed for this type.
2436static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2437 ConstantInt *In2) {
2438 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2439 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2440}
2441
2442static bool isPositive(ConstantInt *C) {
2443 return cast<ConstantSInt>(C)->getValue() >= 0;
2444}
2445
2446/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2447/// overflowed for this type.
2448static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2449 ConstantInt *In2) {
2450 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2451
2452 if (In1->getType()->isUnsigned())
2453 return cast<ConstantUInt>(Result)->getValue() <
2454 cast<ConstantUInt>(In1)->getValue();
2455 if (isPositive(In1) != isPositive(In2))
2456 return false;
2457 if (isPositive(In1))
2458 return cast<ConstantSInt>(Result)->getValue() <
2459 cast<ConstantSInt>(In1)->getValue();
2460 return cast<ConstantSInt>(Result)->getValue() >
2461 cast<ConstantSInt>(In1)->getValue();
2462}
2463
Chris Lattner0798af32005-01-13 20:14:25 +00002464/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2465/// code necessary to compute the offset from the base pointer (without adding
2466/// in the base pointer). Return the result as a signed integer of intptr size.
2467static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2468 TargetData &TD = IC.getTargetData();
2469 gep_type_iterator GTI = gep_type_begin(GEP);
2470 const Type *UIntPtrTy = TD.getIntPtrType();
2471 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2472 Value *Result = Constant::getNullValue(SIntPtrTy);
2473
2474 // Build a mask for high order bits.
2475 uint64_t PtrSizeMask = ~0ULL;
2476 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2477
Chris Lattner0798af32005-01-13 20:14:25 +00002478 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2479 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002480 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002481 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2482 SIntPtrTy);
2483 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2484 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002485 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002486 Scale = ConstantExpr::getMul(OpC, Scale);
2487 if (Constant *RC = dyn_cast<Constant>(Result))
2488 Result = ConstantExpr::getAdd(RC, Scale);
2489 else {
2490 // Emit an add instruction.
2491 Result = IC.InsertNewInstBefore(
2492 BinaryOperator::createAdd(Result, Scale,
2493 GEP->getName()+".offs"), I);
2494 }
2495 }
2496 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002497 // Convert to correct type.
2498 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2499 Op->getName()+".c"), I);
2500 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002501 // We'll let instcombine(mul) convert this to a shl if possible.
2502 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2503 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002504
2505 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002506 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002507 GEP->getName()+".offs"), I);
2508 }
2509 }
2510 return Result;
2511}
2512
2513/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2514/// else. At this point we know that the GEP is on the LHS of the comparison.
2515Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2516 Instruction::BinaryOps Cond,
2517 Instruction &I) {
2518 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002519
2520 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2521 if (isa<PointerType>(CI->getOperand(0)->getType()))
2522 RHS = CI->getOperand(0);
2523
Chris Lattner0798af32005-01-13 20:14:25 +00002524 Value *PtrBase = GEPLHS->getOperand(0);
2525 if (PtrBase == RHS) {
2526 // As an optimization, we don't actually have to compute the actual value of
2527 // OFFSET if this is a seteq or setne comparison, just return whether each
2528 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002529 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2530 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002531 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2532 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00002533 bool EmitIt = true;
2534 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2535 if (isa<UndefValue>(C)) // undef index -> undef.
2536 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2537 if (C->isNullValue())
2538 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002539 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2540 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00002541 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00002542 return ReplaceInstUsesWith(I, // No comparison is needed here.
2543 ConstantBool::get(Cond == Instruction::SetNE));
2544 }
2545
2546 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002547 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00002548 new SetCondInst(Cond, GEPLHS->getOperand(i),
2549 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2550 if (InVal == 0)
2551 InVal = Comp;
2552 else {
2553 InVal = InsertNewInstBefore(InVal, I);
2554 InsertNewInstBefore(Comp, I);
2555 if (Cond == Instruction::SetNE) // True if any are unequal
2556 InVal = BinaryOperator::createOr(InVal, Comp);
2557 else // True if all are equal
2558 InVal = BinaryOperator::createAnd(InVal, Comp);
2559 }
2560 }
2561 }
2562
2563 if (InVal)
2564 return InVal;
2565 else
2566 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2567 ConstantBool::get(Cond == Instruction::SetEQ));
2568 }
Chris Lattner0798af32005-01-13 20:14:25 +00002569
2570 // Only lower this if the setcc is the only user of the GEP or if we expect
2571 // the result to fold to a constant!
2572 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2573 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2574 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2575 return new SetCondInst(Cond, Offset,
2576 Constant::getNullValue(Offset->getType()));
2577 }
2578 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002579 // If the base pointers are different, but the indices are the same, just
2580 // compare the base pointer.
2581 if (PtrBase != GEPRHS->getOperand(0)) {
2582 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002583 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00002584 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002585 if (IndicesTheSame)
2586 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2587 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2588 IndicesTheSame = false;
2589 break;
2590 }
2591
2592 // If all indices are the same, just compare the base pointers.
2593 if (IndicesTheSame)
2594 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2595 GEPRHS->getOperand(0));
2596
2597 // Otherwise, the base pointers are different and the indices are
2598 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00002599 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002600 }
Chris Lattner0798af32005-01-13 20:14:25 +00002601
Chris Lattner81e84172005-01-13 22:25:21 +00002602 // If one of the GEPs has all zero indices, recurse.
2603 bool AllZeros = true;
2604 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2605 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2606 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2607 AllZeros = false;
2608 break;
2609 }
2610 if (AllZeros)
2611 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2612 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00002613
2614 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00002615 AllZeros = true;
2616 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2617 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2618 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2619 AllZeros = false;
2620 break;
2621 }
2622 if (AllZeros)
2623 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2624
Chris Lattner4fa89822005-01-14 00:20:05 +00002625 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2626 // If the GEPs only differ by one index, compare it.
2627 unsigned NumDifferences = 0; // Keep track of # differences.
2628 unsigned DiffOperand = 0; // The operand that differs.
2629 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2630 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002631 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2632 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002633 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00002634 NumDifferences = 2;
2635 break;
2636 } else {
2637 if (NumDifferences++) break;
2638 DiffOperand = i;
2639 }
2640 }
2641
2642 if (NumDifferences == 0) // SAME GEP?
2643 return ReplaceInstUsesWith(I, // No comparison is needed here.
2644 ConstantBool::get(Cond == Instruction::SetEQ));
2645 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002646 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2647 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00002648
2649 // Convert the operands to signed values to make sure to perform a
2650 // signed comparison.
2651 const Type *NewTy = LHSV->getType()->getSignedVersion();
2652 if (LHSV->getType() != NewTy)
2653 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2654 LHSV->getName()), I);
2655 if (RHSV->getType() != NewTy)
2656 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2657 RHSV->getName()), I);
2658 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00002659 }
2660 }
2661
Chris Lattner0798af32005-01-13 20:14:25 +00002662 // Only lower this if the setcc is the only user of the GEP or if we expect
2663 // the result to fold to a constant!
2664 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2665 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2666 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2667 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2668 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2669 return new SetCondInst(Cond, L, R);
2670 }
2671 }
2672 return 0;
2673}
2674
2675
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002676Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002677 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002678 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2679 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002680
2681 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002682 if (Op0 == Op1)
2683 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002684
Chris Lattner81a7a232004-10-16 18:11:37 +00002685 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2686 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2687
Chris Lattner15ff1e12004-11-14 07:33:16 +00002688 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2689 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002690 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2691 isa<ConstantPointerNull>(Op0)) &&
2692 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00002693 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002694 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2695
2696 // setcc's with boolean values can always be turned into bitwise operations
2697 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002698 switch (I.getOpcode()) {
2699 default: assert(0 && "Invalid setcc instruction!");
2700 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002701 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002702 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002703 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002704 }
Chris Lattner4456da62004-08-11 00:50:51 +00002705 case Instruction::SetNE:
2706 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002707
Chris Lattner4456da62004-08-11 00:50:51 +00002708 case Instruction::SetGT:
2709 std::swap(Op0, Op1); // Change setgt -> setlt
2710 // FALL THROUGH
2711 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2712 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2713 InsertNewInstBefore(Not, I);
2714 return BinaryOperator::createAnd(Not, Op1);
2715 }
2716 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002717 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002718 // FALL THROUGH
2719 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2720 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2721 InsertNewInstBefore(Not, I);
2722 return BinaryOperator::createOr(Not, Op1);
2723 }
2724 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002725 }
2726
Chris Lattner2dd01742004-06-09 04:24:29 +00002727 // See if we are doing a comparison between a constant and an instruction that
2728 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002729 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002730 // Check to see if we are comparing against the minimum or maximum value...
2731 if (CI->isMinValue()) {
2732 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2733 return ReplaceInstUsesWith(I, ConstantBool::False);
2734 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2735 return ReplaceInstUsesWith(I, ConstantBool::True);
2736 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2737 return BinaryOperator::createSetEQ(Op0, Op1);
2738 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2739 return BinaryOperator::createSetNE(Op0, Op1);
2740
2741 } else if (CI->isMaxValue()) {
2742 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2743 return ReplaceInstUsesWith(I, ConstantBool::False);
2744 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2745 return ReplaceInstUsesWith(I, ConstantBool::True);
2746 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2747 return BinaryOperator::createSetEQ(Op0, Op1);
2748 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2749 return BinaryOperator::createSetNE(Op0, Op1);
2750
2751 // Comparing against a value really close to min or max?
2752 } else if (isMinValuePlusOne(CI)) {
2753 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2754 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2755 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2756 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2757
2758 } else if (isMaxValueMinusOne(CI)) {
2759 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2760 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2761 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2762 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2763 }
2764
2765 // If we still have a setle or setge instruction, turn it into the
2766 // appropriate setlt or setgt instruction. Since the border cases have
2767 // already been handled above, this requires little checking.
2768 //
2769 if (I.getOpcode() == Instruction::SetLE)
2770 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2771 if (I.getOpcode() == Instruction::SetGE)
2772 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2773
Chris Lattnere1e10e12004-05-25 06:32:08 +00002774 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002775 switch (LHSI->getOpcode()) {
2776 case Instruction::And:
2777 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2778 LHSI->getOperand(0)->hasOneUse()) {
2779 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2780 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2781 // happens a LOT in code produced by the C front-end, for bitfield
2782 // access.
2783 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2784 ConstantUInt *ShAmt;
2785 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2786 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2787 const Type *Ty = LHSI->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002788
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002789 // We can fold this as long as we can't shift unknown bits
2790 // into the mask. This can only happen with signed shift
2791 // rights, as they sign-extend.
2792 if (ShAmt) {
2793 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002794 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002795 if (!CanFold) {
2796 // To test for the bad case of the signed shr, see if any
2797 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00002798 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2799 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2800
2801 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002802 Constant *ShVal =
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002803 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2804 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2805 CanFold = true;
2806 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002807
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002808 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002809 Constant *NewCst;
2810 if (Shift->getOpcode() == Instruction::Shl)
2811 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2812 else
2813 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002814
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002815 // Check to see if we are shifting out any of the bits being
2816 // compared.
2817 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2818 // If we shifted bits out, the fold is not going to work out.
2819 // As a special case, check to see if this means that the
2820 // result is always true or false now.
2821 if (I.getOpcode() == Instruction::SetEQ)
2822 return ReplaceInstUsesWith(I, ConstantBool::False);
2823 if (I.getOpcode() == Instruction::SetNE)
2824 return ReplaceInstUsesWith(I, ConstantBool::True);
2825 } else {
2826 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002827 Constant *NewAndCST;
2828 if (Shift->getOpcode() == Instruction::Shl)
2829 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2830 else
2831 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2832 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002833 LHSI->setOperand(0, Shift->getOperand(0));
2834 WorkList.push_back(Shift); // Shift is dead.
2835 AddUsesToWorkList(I);
2836 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002837 }
2838 }
Chris Lattner35167c32004-06-09 07:59:58 +00002839 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002840 }
2841 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002842
Chris Lattner272d5ca2004-09-28 18:22:15 +00002843 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2844 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2845 switch (I.getOpcode()) {
2846 default: break;
2847 case Instruction::SetEQ:
2848 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002849 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2850
2851 // Check that the shift amount is in range. If not, don't perform
2852 // undefined shifts. When the shift is visited it will be
2853 // simplified.
2854 if (ShAmt->getValue() >= TypeBits)
2855 break;
2856
Chris Lattner272d5ca2004-09-28 18:22:15 +00002857 // If we are comparing against bits always shifted out, the
2858 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002859 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00002860 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2861 if (Comp != CI) {// Comparing against a bit that we know is zero.
2862 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2863 Constant *Cst = ConstantBool::get(IsSetNE);
2864 return ReplaceInstUsesWith(I, Cst);
2865 }
2866
2867 if (LHSI->hasOneUse()) {
2868 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002869 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002870 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2871
2872 Constant *Mask;
2873 if (CI->getType()->isUnsigned()) {
2874 Mask = ConstantUInt::get(CI->getType(), Val);
2875 } else if (ShAmtVal != 0) {
2876 Mask = ConstantSInt::get(CI->getType(), Val);
2877 } else {
2878 Mask = ConstantInt::getAllOnesValue(CI->getType());
2879 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002880
Chris Lattner272d5ca2004-09-28 18:22:15 +00002881 Instruction *AndI =
2882 BinaryOperator::createAnd(LHSI->getOperand(0),
2883 Mask, LHSI->getName()+".mask");
2884 Value *And = InsertNewInstBefore(AndI, I);
2885 return new SetCondInst(I.getOpcode(), And,
2886 ConstantExpr::getUShr(CI, ShAmt));
2887 }
2888 }
2889 }
2890 }
2891 break;
2892
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002893 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002894 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002895 switch (I.getOpcode()) {
2896 default: break;
2897 case Instruction::SetEQ:
2898 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002899
2900 // Check that the shift amount is in range. If not, don't perform
2901 // undefined shifts. When the shift is visited it will be
2902 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00002903 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00002904 if (ShAmt->getValue() >= TypeBits)
2905 break;
2906
Chris Lattner1023b872004-09-27 16:18:50 +00002907 // If we are comparing against bits always shifted out, the
2908 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002909 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00002910 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002911
Chris Lattner1023b872004-09-27 16:18:50 +00002912 if (Comp != CI) {// Comparing against a bit that we know is zero.
2913 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2914 Constant *Cst = ConstantBool::get(IsSetNE);
2915 return ReplaceInstUsesWith(I, Cst);
2916 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002917
Chris Lattner1023b872004-09-27 16:18:50 +00002918 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002919 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002920
Chris Lattner1023b872004-09-27 16:18:50 +00002921 // Otherwise strength reduce the shift into an and.
2922 uint64_t Val = ~0ULL; // All ones.
2923 Val <<= ShAmtVal; // Shift over to the right spot.
2924
2925 Constant *Mask;
2926 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00002927 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00002928 Mask = ConstantUInt::get(CI->getType(), Val);
2929 } else {
2930 Mask = ConstantSInt::get(CI->getType(), Val);
2931 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002932
Chris Lattner1023b872004-09-27 16:18:50 +00002933 Instruction *AndI =
2934 BinaryOperator::createAnd(LHSI->getOperand(0),
2935 Mask, LHSI->getName()+".mask");
2936 Value *And = InsertNewInstBefore(AndI, I);
2937 return new SetCondInst(I.getOpcode(), And,
2938 ConstantExpr::getShl(CI, ShAmt));
2939 }
2940 break;
2941 }
2942 }
2943 }
2944 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002945
Chris Lattner6862fbd2004-09-29 17:40:11 +00002946 case Instruction::Div:
2947 // Fold: (div X, C1) op C2 -> range check
2948 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2949 // Fold this div into the comparison, producing a range check.
2950 // Determine, based on the divide type, what the range is being
2951 // checked. If there is an overflow on the low or high side, remember
2952 // it, otherwise compute the range [low, hi) bounding the new value.
2953 bool LoOverflow = false, HiOverflow = 0;
2954 ConstantInt *LoBound = 0, *HiBound = 0;
2955
2956 ConstantInt *Prod;
2957 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2958
Chris Lattnera92af962004-10-11 19:40:04 +00002959 Instruction::BinaryOps Opcode = I.getOpcode();
2960
Chris Lattner6862fbd2004-09-29 17:40:11 +00002961 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2962 } else if (LHSI->getType()->isUnsigned()) { // udiv
2963 LoBound = Prod;
2964 LoOverflow = ProdOV;
2965 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2966 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2967 if (CI->isNullValue()) { // (X / pos) op 0
2968 // Can't overflow.
2969 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2970 HiBound = DivRHS;
2971 } else if (isPositive(CI)) { // (X / pos) op pos
2972 LoBound = Prod;
2973 LoOverflow = ProdOV;
2974 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2975 } else { // (X / pos) op neg
2976 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2977 LoOverflow = AddWithOverflow(LoBound, Prod,
2978 cast<ConstantInt>(DivRHSH));
2979 HiBound = Prod;
2980 HiOverflow = ProdOV;
2981 }
2982 } else { // Divisor is < 0.
2983 if (CI->isNullValue()) { // (X / neg) op 0
2984 LoBound = AddOne(DivRHS);
2985 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00002986 if (HiBound == DivRHS)
2987 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00002988 } else if (isPositive(CI)) { // (X / neg) op pos
2989 HiOverflow = LoOverflow = ProdOV;
2990 if (!LoOverflow)
2991 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2992 HiBound = AddOne(Prod);
2993 } else { // (X / neg) op neg
2994 LoBound = Prod;
2995 LoOverflow = HiOverflow = ProdOV;
2996 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2997 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002998
Chris Lattnera92af962004-10-11 19:40:04 +00002999 // Dividing by a negate swaps the condition.
3000 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003001 }
3002
3003 if (LoBound) {
3004 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00003005 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003006 default: assert(0 && "Unhandled setcc opcode!");
3007 case Instruction::SetEQ:
3008 if (LoOverflow && HiOverflow)
3009 return ReplaceInstUsesWith(I, ConstantBool::False);
3010 else if (HiOverflow)
3011 return new SetCondInst(Instruction::SetGE, X, LoBound);
3012 else if (LoOverflow)
3013 return new SetCondInst(Instruction::SetLT, X, HiBound);
3014 else
3015 return InsertRangeTest(X, LoBound, HiBound, true, I);
3016 case Instruction::SetNE:
3017 if (LoOverflow && HiOverflow)
3018 return ReplaceInstUsesWith(I, ConstantBool::True);
3019 else if (HiOverflow)
3020 return new SetCondInst(Instruction::SetLT, X, LoBound);
3021 else if (LoOverflow)
3022 return new SetCondInst(Instruction::SetGE, X, HiBound);
3023 else
3024 return InsertRangeTest(X, LoBound, HiBound, false, I);
3025 case Instruction::SetLT:
3026 if (LoOverflow)
3027 return ReplaceInstUsesWith(I, ConstantBool::False);
3028 return new SetCondInst(Instruction::SetLT, X, LoBound);
3029 case Instruction::SetGT:
3030 if (HiOverflow)
3031 return ReplaceInstUsesWith(I, ConstantBool::False);
3032 return new SetCondInst(Instruction::SetGE, X, HiBound);
3033 }
3034 }
3035 }
3036 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003037 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003038
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003039 // Simplify seteq and setne instructions...
3040 if (I.getOpcode() == Instruction::SetEQ ||
3041 I.getOpcode() == Instruction::SetNE) {
3042 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3043
Chris Lattnercfbce7c2003-07-23 17:26:36 +00003044 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003045 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00003046 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3047 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00003048 case Instruction::Rem:
3049 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3050 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3051 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00003052 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3053 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3054 if (isPowerOf2_64(V)) {
3055 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00003056 const Type *UTy = BO->getType()->getUnsignedVersion();
3057 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3058 UTy, "tmp"), I);
3059 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3060 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3061 RHSCst, BO->getName()), I);
3062 return BinaryOperator::create(I.getOpcode(), NewRem,
3063 Constant::getNullValue(UTy));
3064 }
Chris Lattner22d00a82005-08-02 19:16:58 +00003065 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003066 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00003067
Chris Lattnerc992add2003-08-13 05:33:12 +00003068 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00003069 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3070 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00003071 if (BO->hasOneUse())
3072 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3073 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00003074 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003075 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3076 // efficiently invertible, or if the add has just this one use.
3077 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003078
Chris Lattnerc992add2003-08-13 05:33:12 +00003079 if (Value *NegVal = dyn_castNegVal(BOp1))
3080 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3081 else if (Value *NegVal = dyn_castNegVal(BOp0))
3082 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003083 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003084 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3085 BO->setName("");
3086 InsertNewInstBefore(Neg, I);
3087 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3088 }
3089 }
3090 break;
3091 case Instruction::Xor:
3092 // For the xor case, we can xor two constants together, eliminating
3093 // the explicit xor.
3094 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3095 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003096 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00003097
3098 // FALLTHROUGH
3099 case Instruction::Sub:
3100 // Replace (([sub|xor] A, B) != 0) with (A != B)
3101 if (CI->isNullValue())
3102 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3103 BO->getOperand(1));
3104 break;
3105
3106 case Instruction::Or:
3107 // If bits are being or'd in that are not present in the constant we
3108 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003109 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003110 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003111 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003112 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003113 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003114 break;
3115
3116 case Instruction::And:
3117 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003118 // If bits are being compared against that are and'd out, then the
3119 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003120 if (!ConstantExpr::getAnd(CI,
3121 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003122 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00003123
Chris Lattner35167c32004-06-09 07:59:58 +00003124 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00003125 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00003126 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3127 Instruction::SetNE, Op0,
3128 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00003129
Chris Lattnerc992add2003-08-13 05:33:12 +00003130 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3131 // to be a signed value as appropriate.
3132 if (isSignBit(BOC)) {
3133 Value *X = BO->getOperand(0);
3134 // If 'X' is not signed, insert a cast now...
3135 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00003136 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003137 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00003138 }
3139 return new SetCondInst(isSetNE ? Instruction::SetLT :
3140 Instruction::SetGE, X,
3141 Constant::getNullValue(X->getType()));
3142 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003143
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003144 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00003145 if (CI->isNullValue() && isHighOnes(BOC)) {
3146 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003147 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003148
3149 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003150 if (NegX->getType()->isSigned()) {
3151 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3152 X = InsertCastBefore(X, DestTy, I);
3153 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003154 }
3155
3156 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003157 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003158 }
3159
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003160 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003161 default: break;
3162 }
3163 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00003164 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00003165 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00003166 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3167 Value *CastOp = Cast->getOperand(0);
3168 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003169 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00003170 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003171 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003172 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00003173 "Source and destination signednesses should differ!");
3174 if (Cast->getType()->isSigned()) {
3175 // If this is a signed comparison, check for comparisons in the
3176 // vicinity of zero.
3177 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3178 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003179 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003180 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003181 else if (I.getOpcode() == Instruction::SetGT &&
3182 cast<ConstantSInt>(CI)->getValue() == -1)
3183 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003184 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003185 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003186 } else {
3187 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3188 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003189 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00003190 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003191 return BinaryOperator::createSetGT(CastOp,
3192 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003193 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003194 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00003195 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003196 return BinaryOperator::createSetLT(CastOp,
3197 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003198 }
3199 }
3200 }
Chris Lattnere967b342003-06-04 05:10:11 +00003201 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003202 }
3203
Chris Lattner77c32c32005-04-23 15:31:55 +00003204 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3205 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3206 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3207 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00003208 case Instruction::GetElementPtr:
3209 if (RHSC->isNullValue()) {
3210 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3211 bool isAllZeros = true;
3212 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3213 if (!isa<Constant>(LHSI->getOperand(i)) ||
3214 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3215 isAllZeros = false;
3216 break;
3217 }
3218 if (isAllZeros)
3219 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3220 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3221 }
3222 break;
3223
Chris Lattner77c32c32005-04-23 15:31:55 +00003224 case Instruction::PHI:
3225 if (Instruction *NV = FoldOpIntoPhi(I))
3226 return NV;
3227 break;
3228 case Instruction::Select:
3229 // If either operand of the select is a constant, we can fold the
3230 // comparison into the select arms, which will cause one to be
3231 // constant folded and the select turned into a bitwise or.
3232 Value *Op1 = 0, *Op2 = 0;
3233 if (LHSI->hasOneUse()) {
3234 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3235 // Fold the known value into the constant operand.
3236 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3237 // Insert a new SetCC of the other select operand.
3238 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3239 LHSI->getOperand(2), RHSC,
3240 I.getName()), I);
3241 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3242 // Fold the known value into the constant operand.
3243 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3244 // Insert a new SetCC of the other select operand.
3245 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3246 LHSI->getOperand(1), RHSC,
3247 I.getName()), I);
3248 }
3249 }
Jeff Cohen82639852005-04-23 21:38:35 +00003250
Chris Lattner77c32c32005-04-23 15:31:55 +00003251 if (Op1)
3252 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3253 break;
3254 }
3255 }
3256
Chris Lattner0798af32005-01-13 20:14:25 +00003257 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3258 if (User *GEP = dyn_castGetElementPtr(Op0))
3259 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3260 return NI;
3261 if (User *GEP = dyn_castGetElementPtr(Op1))
3262 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3263 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3264 return NI;
3265
Chris Lattner16930792003-11-03 04:25:02 +00003266 // Test to see if the operands of the setcc are casted versions of other
3267 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00003268 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3269 Value *CastOp0 = CI->getOperand(0);
3270 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00003271 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00003272 (I.getOpcode() == Instruction::SetEQ ||
3273 I.getOpcode() == Instruction::SetNE)) {
3274 // We keep moving the cast from the left operand over to the right
3275 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00003276 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003277
Chris Lattner16930792003-11-03 04:25:02 +00003278 // If operand #1 is a cast instruction, see if we can eliminate it as
3279 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00003280 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3281 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00003282 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00003283 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003284
Chris Lattner16930792003-11-03 04:25:02 +00003285 // If Op1 is a constant, we can fold the cast into the constant.
3286 if (Op1->getType() != Op0->getType())
3287 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3288 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3289 } else {
3290 // Otherwise, cast the RHS right before the setcc
3291 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3292 InsertNewInstBefore(cast<Instruction>(Op1), I);
3293 }
3294 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3295 }
3296
Chris Lattner6444c372003-11-03 05:17:03 +00003297 // Handle the special case of: setcc (cast bool to X), <cst>
3298 // This comes up when you have code like
3299 // int X = A < B;
3300 // if (X) ...
3301 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003302 // with a constant or another cast from the same type.
3303 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3304 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3305 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00003306 }
Chris Lattner113f4f42002-06-25 16:13:24 +00003307 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003308}
3309
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003310// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3311// We only handle extending casts so far.
3312//
3313Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3314 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3315 const Type *SrcTy = LHSCIOp->getType();
3316 const Type *DestTy = SCI.getOperand(0)->getType();
3317 Value *RHSCIOp;
3318
3319 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00003320 return 0;
3321
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003322 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3323 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3324 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3325
3326 // Is this a sign or zero extension?
3327 bool isSignSrc = SrcTy->isSigned();
3328 bool isSignDest = DestTy->isSigned();
3329
3330 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3331 // Not an extension from the same type?
3332 RHSCIOp = CI->getOperand(0);
3333 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3334 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3335 // Compute the constant that would happen if we truncated to SrcTy then
3336 // reextended to DestTy.
3337 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3338
3339 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3340 RHSCIOp = Res;
3341 } else {
3342 // If the value cannot be represented in the shorter type, we cannot emit
3343 // a simple comparison.
3344 if (SCI.getOpcode() == Instruction::SetEQ)
3345 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3346 if (SCI.getOpcode() == Instruction::SetNE)
3347 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3348
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003349 // Evaluate the comparison for LT.
3350 Value *Result;
3351 if (DestTy->isSigned()) {
3352 // We're performing a signed comparison.
3353 if (isSignSrc) {
3354 // Signed extend and signed comparison.
3355 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3356 Result = ConstantBool::False;
3357 else
3358 Result = ConstantBool::True; // X < (large) --> true
3359 } else {
3360 // Unsigned extend and signed comparison.
3361 if (cast<ConstantSInt>(CI)->getValue() < 0)
3362 Result = ConstantBool::False;
3363 else
3364 Result = ConstantBool::True;
3365 }
3366 } else {
3367 // We're performing an unsigned comparison.
3368 if (!isSignSrc) {
3369 // Unsigned extend & compare -> always true.
3370 Result = ConstantBool::True;
3371 } else {
3372 // We're performing an unsigned comp with a sign extended value.
3373 // This is true if the input is >= 0. [aka >s -1]
3374 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3375 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3376 NegOne, SCI.getName()), SCI);
3377 }
Reid Spencer279fa252004-11-28 21:31:15 +00003378 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003379
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003380 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003381 if (SCI.getOpcode() == Instruction::SetLT) {
3382 return ReplaceInstUsesWith(SCI, Result);
3383 } else {
3384 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3385 if (Constant *CI = dyn_cast<Constant>(Result))
3386 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3387 else
3388 return BinaryOperator::createNot(Result);
3389 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003390 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003391 } else {
3392 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00003393 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003394
Chris Lattner252a8452005-06-16 03:00:08 +00003395 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003396 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3397}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003398
Chris Lattnere8d6c602003-03-10 19:16:08 +00003399Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003400 assert(I.getOperand(1)->getType() == Type::UByteTy);
3401 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003402 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003403
3404 // shl X, 0 == X and shr X, 0 == X
3405 // shl 0, X == 0 and shr 0, X == 0
3406 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003407 Op0 == Constant::getNullValue(Op0->getType()))
3408 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003409
Chris Lattner81a7a232004-10-16 18:11:37 +00003410 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3411 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003412 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003413 else // undef << X -> 0 AND undef >>u X -> 0
3414 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3415 }
3416 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00003417 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00003418 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3419 else
3420 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3421 }
3422
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003423 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3424 if (!isLeftShift)
3425 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3426 if (CSI->isAllOnesValue())
3427 return ReplaceInstUsesWith(I, CSI);
3428
Chris Lattner183b3362004-04-09 19:05:30 +00003429 // Try to fold constant and into select arguments.
3430 if (isa<Constant>(Op0))
3431 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003432 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003433 return R;
3434
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00003435 // See if we can turn a signed shr into an unsigned shr.
3436 if (!isLeftShift && I.getType()->isSigned()) {
3437 if (MaskedValueIsZero(Op0, ConstantInt::getMinValue(I.getType()))) {
3438 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3439 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3440 I.getName()), I);
3441 return new CastInst(V, I.getType());
3442 }
3443 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003444
Chris Lattner14553932006-01-06 07:12:35 +00003445 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
3446 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
3447 return Res;
3448 return 0;
3449}
3450
3451Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
3452 ShiftInst &I) {
3453 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00003454 bool isSignedShift = Op0->getType()->isSigned();
3455 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00003456
3457 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3458 // of a signed value.
3459 //
3460 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
3461 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00003462 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00003463 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3464 else {
3465 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3466 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003467 }
Chris Lattner14553932006-01-06 07:12:35 +00003468 }
3469
3470 // ((X*C1) << C2) == (X * (C1 << C2))
3471 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3472 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3473 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
3474 return BinaryOperator::createMul(BO->getOperand(0),
3475 ConstantExpr::getShl(BOOp, Op1));
3476
3477 // Try to fold constant and into select arguments.
3478 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3479 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3480 return R;
3481 if (isa<PHINode>(Op0))
3482 if (Instruction *NV = FoldOpIntoPhi(I))
3483 return NV;
3484
3485 if (Op0->hasOneUse()) {
3486 // If this is a SHL of a sign-extending cast, see if we can turn the input
3487 // into a zero extending cast (a simple strength reduction).
3488 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3489 const Type *SrcTy = CI->getOperand(0)->getType();
3490 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3491 SrcTy->getPrimitiveSizeInBits() <
3492 CI->getType()->getPrimitiveSizeInBits()) {
3493 // We can change it to a zero extension if we are shifting out all of
3494 // the sign extended bits. To check this, form a mask of all of the
3495 // sign extend bits, then shift them left and see if we have anything
3496 // left.
3497 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3498 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3499 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3500 if (ConstantExpr::getShl(Mask, Op1)->isNullValue()) {
3501 // If the shift is nuking all of the sign bits, change this to a
3502 // zero extension cast. To do this, cast the cast input to
3503 // unsigned, then to the requested size.
3504 Value *CastOp = CI->getOperand(0);
3505 Instruction *NC =
3506 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3507 CI->getName()+".uns");
3508 NC = InsertNewInstBefore(NC, I);
3509 // Finally, insert a replacement for CI.
3510 NC = new CastInst(NC, CI->getType(), CI->getName());
3511 CI->setName("");
3512 NC = InsertNewInstBefore(NC, I);
3513 WorkList.push_back(CI); // Delete CI later.
3514 I.setOperand(0, NC);
3515 return &I; // The SHL operand was modified.
Chris Lattner86102b82005-01-01 16:22:27 +00003516 }
3517 }
Chris Lattner14553932006-01-06 07:12:35 +00003518 }
3519
3520 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3521 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3522 Value *V1, *V2;
3523 ConstantInt *CC;
3524 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00003525 default: break;
3526 case Instruction::Add:
3527 case Instruction::And:
3528 case Instruction::Or:
3529 case Instruction::Xor:
3530 // These operators commute.
3531 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003532 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3533 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00003534 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00003535 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003536 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003537 Op0BO->getName());
3538 InsertNewInstBefore(YS, I); // (Y << C)
3539 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3540 V1,
Chris Lattner14553932006-01-06 07:12:35 +00003541 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00003542 InsertNewInstBefore(X, I); // (X + (Y << C))
3543 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00003544 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00003545 return BinaryOperator::createAnd(X, C2);
3546 }
Chris Lattner14553932006-01-06 07:12:35 +00003547
Chris Lattner797dee72005-09-18 06:30:59 +00003548 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
3549 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3550 match(Op0BO->getOperand(1),
3551 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00003552 m_ConstantInt(CC))) && V2 == Op1 &&
3553 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00003554 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003555 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003556 Op0BO->getName());
3557 InsertNewInstBefore(YS, I); // (Y << C)
3558 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00003559 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00003560 V1->getName()+".mask");
3561 InsertNewInstBefore(XM, I); // X & (CC << C)
3562
3563 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3564 }
Chris Lattner14553932006-01-06 07:12:35 +00003565
Chris Lattner797dee72005-09-18 06:30:59 +00003566 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00003567 case Instruction::Sub:
3568 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003569 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3570 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00003571 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00003572 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003573 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003574 Op0BO->getName());
3575 InsertNewInstBefore(YS, I); // (Y << C)
3576 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3577 V1,
Chris Lattner14553932006-01-06 07:12:35 +00003578 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00003579 InsertNewInstBefore(X, I); // (X + (Y << C))
3580 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00003581 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00003582 return BinaryOperator::createAnd(X, C2);
3583 }
Chris Lattner14553932006-01-06 07:12:35 +00003584
Chris Lattner797dee72005-09-18 06:30:59 +00003585 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3586 match(Op0BO->getOperand(0),
3587 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00003588 m_ConstantInt(CC))) && V2 == Op1 &&
3589 cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00003590 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003591 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003592 Op0BO->getName());
3593 InsertNewInstBefore(YS, I); // (Y << C)
3594 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00003595 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00003596 V1->getName()+".mask");
3597 InsertNewInstBefore(XM, I); // X & (CC << C)
3598
3599 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3600 }
Chris Lattner14553932006-01-06 07:12:35 +00003601
Chris Lattner27cb9db2005-09-18 05:12:10 +00003602 break;
Chris Lattner14553932006-01-06 07:12:35 +00003603 }
3604
3605
3606 // If the operand is an bitwise operator with a constant RHS, and the
3607 // shift is the only use, we can pull it out of the shift.
3608 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3609 bool isValid = true; // Valid only for And, Or, Xor
3610 bool highBitSet = false; // Transform if high bit of constant set?
3611
3612 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003613 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003614 case Instruction::Add:
3615 isValid = isLeftShift;
3616 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003617 case Instruction::Or:
3618 case Instruction::Xor:
3619 highBitSet = false;
3620 break;
3621 case Instruction::And:
3622 highBitSet = true;
3623 break;
Chris Lattner14553932006-01-06 07:12:35 +00003624 }
3625
3626 // If this is a signed shift right, and the high bit is modified
3627 // by the logical operation, do not perform the transformation.
3628 // The highBitSet boolean indicates the value of the high bit of
3629 // the constant which would cause it to be modified for this
3630 // operation.
3631 //
Chris Lattnerb3309392006-01-06 07:22:22 +00003632 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00003633 uint64_t Val = Op0C->getRawValue();
3634 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3635 }
3636
3637 if (isValid) {
3638 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
3639
3640 Instruction *NewShift =
3641 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
3642 Op0BO->getName());
3643 Op0BO->setName("");
3644 InsertNewInstBefore(NewShift, I);
3645
3646 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3647 NewRHS);
3648 }
3649 }
3650 }
3651 }
3652
Chris Lattnereb372a02006-01-06 07:52:12 +00003653 // Find out if this is a shift of a shift by a constant.
3654 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00003655 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00003656 ShiftOp = Op0SI;
3657 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3658 // If this is a noop-integer case of a shift instruction, use the shift.
3659 if (CI->getOperand(0)->getType()->isInteger() &&
3660 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3661 CI->getType()->getPrimitiveSizeInBits() &&
3662 isa<ShiftInst>(CI->getOperand(0))) {
3663 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
3664 }
3665 }
3666
3667 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
3668 // Find the operands and properties of the input shift. Note that the
3669 // signedness of the input shift may differ from the current shift if there
3670 // is a noop cast between the two.
3671 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
3672 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003673 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00003674
3675 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
3676
3677 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3678 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
3679
3680 // Check for (A << c1) << c2 and (A >> c1) >> c2.
3681 if (isLeftShift == isShiftOfLeftShift) {
3682 // Do not fold these shifts if the first one is signed and the second one
3683 // is unsigned and this is a right shift. Further, don't do any folding
3684 // on them.
3685 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
3686 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00003687
Chris Lattnereb372a02006-01-06 07:52:12 +00003688 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
3689 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
3690 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00003691
Chris Lattnereb372a02006-01-06 07:52:12 +00003692 Value *Op = ShiftOp->getOperand(0);
3693 if (isShiftOfSignedShift != isSignedShift)
3694 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
3695 return new ShiftInst(I.getOpcode(), Op,
3696 ConstantUInt::get(Type::UByteTy, Amt));
3697 }
3698
3699 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
3700 // signed types, we can only support the (A >> c1) << c2 configuration,
3701 // because it can not turn an arbitrary bit of A into a sign bit.
3702 if (isUnsignedShift || isLeftShift) {
3703 // Calculate bitmask for what gets shifted off the edge.
3704 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
3705 if (isLeftShift)
3706 C = ConstantExpr::getShl(C, ShiftAmt1C);
3707 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003708 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00003709
3710 Value *Op = ShiftOp->getOperand(0);
3711 if (isShiftOfSignedShift != isSignedShift)
3712 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
3713
3714 Instruction *Mask =
3715 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
3716 InsertNewInstBefore(Mask, I);
3717
3718 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003719 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00003720 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003721 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00003722 return new ShiftInst(I.getOpcode(), Mask,
3723 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003724 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
3725 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
3726 // Make sure to emit an unsigned shift right, not a signed one.
3727 Mask = InsertNewInstBefore(new CastInst(Mask,
3728 Mask->getType()->getUnsignedVersion(),
3729 Op->getName()), I);
3730 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00003731 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003732 InsertNewInstBefore(Mask, I);
3733 return new CastInst(Mask, I.getType());
3734 } else {
3735 return new ShiftInst(ShiftOp->getOpcode(), Mask,
3736 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3737 }
3738 } else {
3739 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
3740 Op = InsertNewInstBefore(new CastInst(Mask,
3741 I.getType()->getSignedVersion(),
3742 Mask->getName()), I);
3743 Instruction *Shift =
3744 new ShiftInst(ShiftOp->getOpcode(), Op,
3745 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3746 InsertNewInstBefore(Shift, I);
3747
3748 C = ConstantIntegral::getAllOnesValue(Shift->getType());
3749 C = ConstantExpr::getShl(C, Op1);
3750 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
3751 InsertNewInstBefore(Mask, I);
3752 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00003753 }
3754 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003755 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00003756 // this case, C1 == C2 and C1 is 8, 16, or 32.
3757 if (ShiftAmt1 == ShiftAmt2) {
3758 const Type *SExtType = 0;
3759 switch (ShiftAmt1) {
3760 case 8 : SExtType = Type::SByteTy; break;
3761 case 16: SExtType = Type::ShortTy; break;
3762 case 32: SExtType = Type::IntTy; break;
3763 }
3764
3765 if (SExtType) {
3766 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
3767 SExtType, "sext");
3768 InsertNewInstBefore(NewTrunc, I);
3769 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003770 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00003771 }
Chris Lattner86102b82005-01-01 16:22:27 +00003772 }
Chris Lattnereb372a02006-01-06 07:52:12 +00003773 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003774 return 0;
3775}
3776
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003777enum CastType {
3778 Noop = 0,
3779 Truncate = 1,
3780 Signext = 2,
3781 Zeroext = 3
3782};
3783
3784/// getCastType - In the future, we will split the cast instruction into these
3785/// various types. Until then, we have to do the analysis here.
3786static CastType getCastType(const Type *Src, const Type *Dest) {
3787 assert(Src->isIntegral() && Dest->isIntegral() &&
3788 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003789 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3790 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003791
3792 if (SrcSize == DestSize) return Noop;
3793 if (SrcSize > DestSize) return Truncate;
3794 if (Src->isSigned()) return Signext;
3795 return Zeroext;
3796}
3797
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003798
Chris Lattner48a44f72002-05-02 17:06:02 +00003799// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3800// instruction.
3801//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003802static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00003803 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003804
Chris Lattner650b6da2002-08-02 20:00:25 +00003805 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00003806 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003807 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003808 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003809 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003810
Chris Lattner4fbad962004-07-21 04:27:24 +00003811 // If we are casting between pointer and integer types, treat pointers as
3812 // integers of the appropriate size for the code below.
3813 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3814 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3815 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003816
Chris Lattner48a44f72002-05-02 17:06:02 +00003817 // Allow free casting and conversion of sizes as long as the sign doesn't
3818 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003819 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003820 CastType FirstCast = getCastType(SrcTy, MidTy);
3821 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003822
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003823 // Capture the effect of these two casts. If the result is a legal cast,
3824 // the CastType is stored here, otherwise a special code is used.
3825 static const unsigned CastResult[] = {
3826 // First cast is noop
3827 0, 1, 2, 3,
3828 // First cast is a truncate
3829 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3830 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003831 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003832 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003833 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003834 };
3835
3836 unsigned Result = CastResult[FirstCast*4+SecondCast];
3837 switch (Result) {
3838 default: assert(0 && "Illegal table value!");
3839 case 0:
3840 case 1:
3841 case 2:
3842 case 3:
3843 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3844 // truncates, we could eliminate more casts.
3845 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3846 case 4:
3847 return false; // Not possible to eliminate this here.
3848 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00003849 // Sign or zero extend followed by truncate is always ok if the result
3850 // is a truncate or noop.
3851 CastType ResultCast = getCastType(SrcTy, DstTy);
3852 if (ResultCast == Noop || ResultCast == Truncate)
3853 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003854 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00003855 // result will match the sign/zeroextendness of the result.
3856 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00003857 }
Chris Lattner650b6da2002-08-02 20:00:25 +00003858 }
Chris Lattner48a44f72002-05-02 17:06:02 +00003859 return false;
3860}
3861
Chris Lattner11ffd592004-07-20 05:21:00 +00003862static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003863 if (V->getType() == Ty || isa<Constant>(V)) return false;
3864 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00003865 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3866 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003867 return false;
3868 return true;
3869}
3870
3871/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3872/// InsertBefore instruction. This is specialized a bit to avoid inserting
3873/// casts that are known to not do anything...
3874///
3875Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3876 Instruction *InsertBefore) {
3877 if (V->getType() == DestTy) return V;
3878 if (Constant *C = dyn_cast<Constant>(V))
3879 return ConstantExpr::getCast(C, DestTy);
3880
3881 CastInst *CI = new CastInst(V, DestTy, V->getName());
3882 InsertNewInstBefore(CI, *InsertBefore);
3883 return CI;
3884}
Chris Lattner48a44f72002-05-02 17:06:02 +00003885
Chris Lattner8f663e82005-10-29 04:36:15 +00003886/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
3887/// expression. If so, decompose it, returning some value X, such that Val is
3888/// X*Scale+Offset.
3889///
3890static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
3891 unsigned &Offset) {
3892 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
3893 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
3894 Offset = CI->getValue();
3895 Scale = 1;
3896 return ConstantUInt::get(Type::UIntTy, 0);
3897 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
3898 if (I->getNumOperands() == 2) {
3899 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
3900 if (I->getOpcode() == Instruction::Shl) {
3901 // This is a value scaled by '1 << the shift amt'.
3902 Scale = 1U << CUI->getValue();
3903 Offset = 0;
3904 return I->getOperand(0);
3905 } else if (I->getOpcode() == Instruction::Mul) {
3906 // This value is scaled by 'CUI'.
3907 Scale = CUI->getValue();
3908 Offset = 0;
3909 return I->getOperand(0);
3910 } else if (I->getOpcode() == Instruction::Add) {
3911 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
3912 // divisible by C2.
3913 unsigned SubScale;
3914 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
3915 Offset);
3916 Offset += CUI->getValue();
3917 if (SubScale > 1 && (Offset % SubScale == 0)) {
3918 Scale = SubScale;
3919 return SubVal;
3920 }
3921 }
3922 }
3923 }
3924 }
3925
3926 // Otherwise, we can't look past this.
3927 Scale = 1;
3928 Offset = 0;
3929 return Val;
3930}
3931
3932
Chris Lattner216be912005-10-24 06:03:58 +00003933/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
3934/// try to eliminate the cast by moving the type information into the alloc.
3935Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
3936 AllocationInst &AI) {
3937 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00003938 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00003939
Chris Lattnerac87beb2005-10-24 06:22:12 +00003940 // Remove any uses of AI that are dead.
3941 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
3942 std::vector<Instruction*> DeadUsers;
3943 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
3944 Instruction *User = cast<Instruction>(*UI++);
3945 if (isInstructionTriviallyDead(User)) {
3946 while (UI != E && *UI == User)
3947 ++UI; // If this instruction uses AI more than once, don't break UI.
3948
3949 // Add operands to the worklist.
3950 AddUsesToWorkList(*User);
3951 ++NumDeadInst;
3952 DEBUG(std::cerr << "IC: DCE: " << *User);
3953
3954 User->eraseFromParent();
3955 removeFromWorkList(User);
3956 }
3957 }
3958
Chris Lattner216be912005-10-24 06:03:58 +00003959 // Get the type really allocated and the type casted to.
3960 const Type *AllocElTy = AI.getAllocatedType();
3961 const Type *CastElTy = PTy->getElementType();
3962 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00003963
3964 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
3965 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
3966 if (CastElTyAlign < AllocElTyAlign) return 0;
3967
Chris Lattner46705b22005-10-24 06:35:18 +00003968 // If the allocation has multiple uses, only promote it if we are strictly
3969 // increasing the alignment of the resultant allocation. If we keep it the
3970 // same, we open the door to infinite loops of various kinds.
3971 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
3972
Chris Lattner216be912005-10-24 06:03:58 +00003973 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3974 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00003975 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00003976
Chris Lattner8270c332005-10-29 03:19:53 +00003977 // See if we can satisfy the modulus by pulling a scale out of the array
3978 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00003979 unsigned ArraySizeScale, ArrayOffset;
3980 Value *NumElements = // See if the array size is a decomposable linear expr.
3981 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
3982
Chris Lattner8270c332005-10-29 03:19:53 +00003983 // If we can now satisfy the modulus, by using a non-1 scale, we really can
3984 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00003985 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
3986 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00003987
Chris Lattner8270c332005-10-29 03:19:53 +00003988 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
3989 Value *Amt = 0;
3990 if (Scale == 1) {
3991 Amt = NumElements;
3992 } else {
3993 Amt = ConstantUInt::get(Type::UIntTy, Scale);
3994 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
3995 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
3996 else if (Scale != 1) {
3997 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
3998 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00003999 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004000 }
4001
Chris Lattner8f663e82005-10-29 04:36:15 +00004002 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4003 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4004 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4005 Amt = InsertNewInstBefore(Tmp, AI);
4006 }
4007
Chris Lattner216be912005-10-24 06:03:58 +00004008 std::string Name = AI.getName(); AI.setName("");
4009 AllocationInst *New;
4010 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00004011 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004012 else
Nate Begeman848622f2005-11-05 09:21:28 +00004013 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004014 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00004015
4016 // If the allocation has multiple uses, insert a cast and change all things
4017 // that used it to use the new cast. This will also hack on CI, but it will
4018 // die soon.
4019 if (!AI.hasOneUse()) {
4020 AddUsesToWorkList(AI);
4021 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4022 InsertNewInstBefore(NewCast, AI);
4023 AI.replaceAllUsesWith(NewCast);
4024 }
Chris Lattner216be912005-10-24 06:03:58 +00004025 return ReplaceInstUsesWith(CI, New);
4026}
4027
4028
Chris Lattner48a44f72002-05-02 17:06:02 +00004029// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00004030//
Chris Lattner113f4f42002-06-25 16:13:24 +00004031Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00004032 Value *Src = CI.getOperand(0);
4033
Chris Lattner48a44f72002-05-02 17:06:02 +00004034 // If the user is casting a value to the same type, eliminate this cast
4035 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00004036 if (CI.getType() == Src->getType())
4037 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00004038
Chris Lattner81a7a232004-10-16 18:11:37 +00004039 if (isa<UndefValue>(Src)) // cast undef -> undef
4040 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4041
Chris Lattner48a44f72002-05-02 17:06:02 +00004042 // If casting the result of another cast instruction, try to eliminate this
4043 // one!
4044 //
Chris Lattner86102b82005-01-01 16:22:27 +00004045 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4046 Value *A = CSrc->getOperand(0);
4047 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4048 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004049 // This instruction now refers directly to the cast's src operand. This
4050 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00004051 CI.setOperand(0, CSrc->getOperand(0));
4052 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00004053 }
4054
Chris Lattner650b6da2002-08-02 20:00:25 +00004055 // If this is an A->B->A cast, and we are dealing with integral types, try
4056 // to convert this into a logical 'and' instruction.
4057 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00004058 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004059 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00004060 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004061 CSrc->getType()->getPrimitiveSizeInBits() <
4062 CI.getType()->getPrimitiveSizeInBits()&&
4063 A->getType()->getPrimitiveSizeInBits() ==
4064 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00004065 assert(CSrc->getType() != Type::ULongTy &&
4066 "Cannot have type bigger than ulong!");
Chris Lattner2f1457f2005-04-24 17:46:05 +00004067 uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
Chris Lattner86102b82005-01-01 16:22:27 +00004068 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4069 AndValue);
4070 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4071 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4072 if (And->getType() != CI.getType()) {
4073 And->setName(CSrc->getName()+".mask");
4074 InsertNewInstBefore(And, CI);
4075 And = new CastInst(And, CI.getType());
4076 }
4077 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00004078 }
4079 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004080
Chris Lattner03841652004-05-25 04:29:21 +00004081 // If this is a cast to bool, turn it into the appropriate setne instruction.
4082 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004083 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00004084 Constant::getNullValue(CI.getOperand(0)->getType()));
4085
Chris Lattnerd0d51602003-06-21 23:12:02 +00004086 // If casting the result of a getelementptr instruction with no offset, turn
4087 // this into a cast of the original pointer!
4088 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00004089 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00004090 bool AllZeroOperands = true;
4091 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4092 if (!isa<Constant>(GEP->getOperand(i)) ||
4093 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4094 AllZeroOperands = false;
4095 break;
4096 }
4097 if (AllZeroOperands) {
4098 CI.setOperand(0, GEP->getOperand(0));
4099 return &CI;
4100 }
4101 }
4102
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004103 // If we are casting a malloc or alloca to a pointer to a type of the same
4104 // size, rewrite the allocation instruction to allocate the "right" type.
4105 //
4106 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00004107 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4108 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004109
Chris Lattner86102b82005-01-01 16:22:27 +00004110 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4111 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4112 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004113 if (isa<PHINode>(Src))
4114 if (Instruction *NV = FoldOpIntoPhi(CI))
4115 return NV;
4116
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004117 // If the source value is an instruction with only this use, we can attempt to
4118 // propagate the cast into the instruction. Also, only handle integral types
4119 // for now.
4120 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004121 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004122 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4123 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004124 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4125 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004126
4127 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4128 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4129
4130 switch (SrcI->getOpcode()) {
4131 case Instruction::Add:
4132 case Instruction::Mul:
4133 case Instruction::And:
4134 case Instruction::Or:
4135 case Instruction::Xor:
4136 // If we are discarding information, or just changing the sign, rewrite.
4137 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4138 // Don't insert two casts if they cannot be eliminated. We allow two
4139 // casts to be inserted if the sizes are the same. This could only be
4140 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00004141 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4142 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004143 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4144 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4145 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4146 ->getOpcode(), Op0c, Op1c);
4147 }
4148 }
Chris Lattner72086162005-05-06 02:07:39 +00004149
4150 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4151 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4152 Op1 == ConstantBool::True &&
4153 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4154 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4155 return BinaryOperator::createXor(New,
4156 ConstantInt::get(CI.getType(), 1));
4157 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004158 break;
4159 case Instruction::Shl:
4160 // Allow changing the sign of the source operand. Do not allow changing
4161 // the size of the shift, UNLESS the shift amount is a constant. We
4162 // mush not change variable sized shifts to a smaller size, because it
4163 // is undefined to shift more bits out than exist in the value.
4164 if (DestBitSize == SrcBitSize ||
4165 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4166 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4167 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4168 }
4169 break;
Chris Lattner87380412005-05-06 04:18:52 +00004170 case Instruction::Shr:
4171 // If this is a signed shr, and if all bits shifted in are about to be
4172 // truncated off, turn it into an unsigned shr to allow greater
4173 // simplifications.
4174 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4175 isa<ConstantInt>(Op1)) {
4176 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4177 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4178 // Convert to unsigned.
4179 Value *N1 = InsertOperandCastBefore(Op0,
4180 Op0->getType()->getUnsignedVersion(), &CI);
4181 // Insert the new shift, which is now unsigned.
4182 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4183 Op1, Src->getName()), CI);
4184 return new CastInst(N1, CI.getType());
4185 }
4186 }
4187 break;
4188
Chris Lattner809dfac2005-05-04 19:10:26 +00004189 case Instruction::SetNE:
Chris Lattner809dfac2005-05-04 19:10:26 +00004190 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004191 if (Op1C->getRawValue() == 0) {
4192 // If the input only has the low bit set, simplify directly.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004193 Constant *Not1 =
Chris Lattner809dfac2005-05-04 19:10:26 +00004194 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattner4c2d3782005-05-06 01:53:19 +00004195 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattner809dfac2005-05-04 19:10:26 +00004196 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4197 if (CI.getType() == Op0->getType())
4198 return ReplaceInstUsesWith(CI, Op0);
4199 else
4200 return new CastInst(Op0, CI.getType());
4201 }
Chris Lattner4c2d3782005-05-06 01:53:19 +00004202
4203 // If the input is an and with a single bit, shift then simplify.
4204 ConstantInt *AndRHS;
4205 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
4206 if (AndRHS->getRawValue() &&
4207 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattner22d00a82005-08-02 19:16:58 +00004208 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattner4c2d3782005-05-06 01:53:19 +00004209 // Perform an unsigned shr by shiftamt. Convert input to
4210 // unsigned if it is signed.
4211 Value *In = Op0;
4212 if (In->getType()->isSigned())
4213 In = InsertNewInstBefore(new CastInst(In,
4214 In->getType()->getUnsignedVersion(), In->getName()),CI);
4215 // Insert the shift to put the result in the low bit.
4216 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4217 ConstantInt::get(Type::UByteTy, ShiftAmt),
4218 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00004219 if (CI.getType() == In->getType())
4220 return ReplaceInstUsesWith(CI, In);
4221 else
4222 return new CastInst(In, CI.getType());
4223 }
4224 }
4225 }
4226 break;
4227 case Instruction::SetEQ:
4228 // We if we are just checking for a seteq of a single bit and casting it
4229 // to an integer. If so, shift the bit to the appropriate place then
4230 // cast to integer to avoid the comparison.
4231 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4232 // Is Op1C a power of two or zero?
4233 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
4234 // cast (X == 1) to int -> X iff X has only the low bit set.
4235 if (Op1C->getRawValue() == 1) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004236 Constant *Not1 =
Chris Lattner4c2d3782005-05-06 01:53:19 +00004237 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
4238 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4239 if (CI.getType() == Op0->getType())
4240 return ReplaceInstUsesWith(CI, Op0);
4241 else
4242 return new CastInst(Op0, CI.getType());
4243 }
4244 }
Chris Lattner809dfac2005-05-04 19:10:26 +00004245 }
4246 }
4247 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004248 }
4249 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004250
Chris Lattner260ab202002-04-18 17:39:14 +00004251 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00004252}
4253
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004254/// GetSelectFoldableOperands - We want to turn code that looks like this:
4255/// %C = or %A, %B
4256/// %D = select %cond, %C, %A
4257/// into:
4258/// %C = select %cond, %B, 0
4259/// %D = or %A, %C
4260///
4261/// Assuming that the specified instruction is an operand to the select, return
4262/// a bitmask indicating which operands of this instruction are foldable if they
4263/// equal the other incoming value of the select.
4264///
4265static unsigned GetSelectFoldableOperands(Instruction *I) {
4266 switch (I->getOpcode()) {
4267 case Instruction::Add:
4268 case Instruction::Mul:
4269 case Instruction::And:
4270 case Instruction::Or:
4271 case Instruction::Xor:
4272 return 3; // Can fold through either operand.
4273 case Instruction::Sub: // Can only fold on the amount subtracted.
4274 case Instruction::Shl: // Can only fold on the shift amount.
4275 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00004276 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004277 default:
4278 return 0; // Cannot fold
4279 }
4280}
4281
4282/// GetSelectFoldableConstant - For the same transformation as the previous
4283/// function, return the identity constant that goes into the select.
4284static Constant *GetSelectFoldableConstant(Instruction *I) {
4285 switch (I->getOpcode()) {
4286 default: assert(0 && "This cannot happen!"); abort();
4287 case Instruction::Add:
4288 case Instruction::Sub:
4289 case Instruction::Or:
4290 case Instruction::Xor:
4291 return Constant::getNullValue(I->getType());
4292 case Instruction::Shl:
4293 case Instruction::Shr:
4294 return Constant::getNullValue(Type::UByteTy);
4295 case Instruction::And:
4296 return ConstantInt::getAllOnesValue(I->getType());
4297 case Instruction::Mul:
4298 return ConstantInt::get(I->getType(), 1);
4299 }
4300}
4301
Chris Lattner411336f2005-01-19 21:50:18 +00004302/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4303/// have the same opcode and only one use each. Try to simplify this.
4304Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4305 Instruction *FI) {
4306 if (TI->getNumOperands() == 1) {
4307 // If this is a non-volatile load or a cast from the same type,
4308 // merge.
4309 if (TI->getOpcode() == Instruction::Cast) {
4310 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4311 return 0;
4312 } else {
4313 return 0; // unknown unary op.
4314 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004315
Chris Lattner411336f2005-01-19 21:50:18 +00004316 // Fold this by inserting a select from the input values.
4317 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4318 FI->getOperand(0), SI.getName()+".v");
4319 InsertNewInstBefore(NewSI, SI);
4320 return new CastInst(NewSI, TI->getType());
4321 }
4322
4323 // Only handle binary operators here.
4324 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4325 return 0;
4326
4327 // Figure out if the operations have any operands in common.
4328 Value *MatchOp, *OtherOpT, *OtherOpF;
4329 bool MatchIsOpZero;
4330 if (TI->getOperand(0) == FI->getOperand(0)) {
4331 MatchOp = TI->getOperand(0);
4332 OtherOpT = TI->getOperand(1);
4333 OtherOpF = FI->getOperand(1);
4334 MatchIsOpZero = true;
4335 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4336 MatchOp = TI->getOperand(1);
4337 OtherOpT = TI->getOperand(0);
4338 OtherOpF = FI->getOperand(0);
4339 MatchIsOpZero = false;
4340 } else if (!TI->isCommutative()) {
4341 return 0;
4342 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4343 MatchOp = TI->getOperand(0);
4344 OtherOpT = TI->getOperand(1);
4345 OtherOpF = FI->getOperand(0);
4346 MatchIsOpZero = true;
4347 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4348 MatchOp = TI->getOperand(1);
4349 OtherOpT = TI->getOperand(0);
4350 OtherOpF = FI->getOperand(1);
4351 MatchIsOpZero = true;
4352 } else {
4353 return 0;
4354 }
4355
4356 // If we reach here, they do have operations in common.
4357 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4358 OtherOpF, SI.getName()+".v");
4359 InsertNewInstBefore(NewSI, SI);
4360
4361 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4362 if (MatchIsOpZero)
4363 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4364 else
4365 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4366 } else {
4367 if (MatchIsOpZero)
4368 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4369 else
4370 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4371 }
4372}
4373
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004374Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00004375 Value *CondVal = SI.getCondition();
4376 Value *TrueVal = SI.getTrueValue();
4377 Value *FalseVal = SI.getFalseValue();
4378
4379 // select true, X, Y -> X
4380 // select false, X, Y -> Y
4381 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004382 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00004383 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004384 else {
4385 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00004386 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004387 }
Chris Lattner533bc492004-03-30 19:37:13 +00004388
4389 // select C, X, X -> X
4390 if (TrueVal == FalseVal)
4391 return ReplaceInstUsesWith(SI, TrueVal);
4392
Chris Lattner81a7a232004-10-16 18:11:37 +00004393 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4394 return ReplaceInstUsesWith(SI, FalseVal);
4395 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4396 return ReplaceInstUsesWith(SI, TrueVal);
4397 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4398 if (isa<Constant>(TrueVal))
4399 return ReplaceInstUsesWith(SI, TrueVal);
4400 else
4401 return ReplaceInstUsesWith(SI, FalseVal);
4402 }
4403
Chris Lattner1c631e82004-04-08 04:43:23 +00004404 if (SI.getType() == Type::BoolTy)
4405 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4406 if (C == ConstantBool::True) {
4407 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004408 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004409 } else {
4410 // Change: A = select B, false, C --> A = and !B, C
4411 Value *NotCond =
4412 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4413 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004414 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004415 }
4416 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4417 if (C == ConstantBool::False) {
4418 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004419 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004420 } else {
4421 // Change: A = select B, C, true --> A = or !B, C
4422 Value *NotCond =
4423 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4424 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004425 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004426 }
4427 }
4428
Chris Lattner183b3362004-04-09 19:05:30 +00004429 // Selecting between two integer constants?
4430 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4431 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4432 // select C, 1, 0 -> cast C to int
4433 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4434 return new CastInst(CondVal, SI.getType());
4435 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4436 // select C, 0, 1 -> cast !C to int
4437 Value *NotCond =
4438 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00004439 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00004440 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00004441 }
Chris Lattner35167c32004-06-09 07:59:58 +00004442
4443 // If one of the constants is zero (we know they can't both be) and we
4444 // have a setcc instruction with zero, and we have an 'and' with the
4445 // non-constant value, eliminate this whole mess. This corresponds to
4446 // cases like this: ((X & 27) ? 27 : 0)
4447 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4448 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4449 if ((IC->getOpcode() == Instruction::SetEQ ||
4450 IC->getOpcode() == Instruction::SetNE) &&
4451 isa<ConstantInt>(IC->getOperand(1)) &&
4452 cast<Constant>(IC->getOperand(1))->isNullValue())
4453 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4454 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004455 isa<ConstantInt>(ICA->getOperand(1)) &&
4456 (ICA->getOperand(1) == TrueValC ||
4457 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00004458 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4459 // Okay, now we know that everything is set up, we just don't
4460 // know whether we have a setne or seteq and whether the true or
4461 // false val is the zero.
4462 bool ShouldNotVal = !TrueValC->isNullValue();
4463 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4464 Value *V = ICA;
4465 if (ShouldNotVal)
4466 V = InsertNewInstBefore(BinaryOperator::create(
4467 Instruction::Xor, V, ICA->getOperand(1)), SI);
4468 return ReplaceInstUsesWith(SI, V);
4469 }
Chris Lattner533bc492004-03-30 19:37:13 +00004470 }
Chris Lattner623fba12004-04-10 22:21:27 +00004471
4472 // See if we are selecting two values based on a comparison of the two values.
4473 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4474 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4475 // Transform (X == Y) ? X : Y -> Y
4476 if (SCI->getOpcode() == Instruction::SetEQ)
4477 return ReplaceInstUsesWith(SI, FalseVal);
4478 // Transform (X != Y) ? X : Y -> X
4479 if (SCI->getOpcode() == Instruction::SetNE)
4480 return ReplaceInstUsesWith(SI, TrueVal);
4481 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4482
4483 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4484 // Transform (X == Y) ? Y : X -> X
4485 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00004486 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004487 // Transform (X != Y) ? Y : X -> Y
4488 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00004489 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004490 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4491 }
4492 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004493
Chris Lattnera04c9042005-01-13 22:52:24 +00004494 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4495 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4496 if (TI->hasOneUse() && FI->hasOneUse()) {
4497 bool isInverse = false;
4498 Instruction *AddOp = 0, *SubOp = 0;
4499
Chris Lattner411336f2005-01-19 21:50:18 +00004500 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4501 if (TI->getOpcode() == FI->getOpcode())
4502 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4503 return IV;
4504
4505 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4506 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00004507 if (TI->getOpcode() == Instruction::Sub &&
4508 FI->getOpcode() == Instruction::Add) {
4509 AddOp = FI; SubOp = TI;
4510 } else if (FI->getOpcode() == Instruction::Sub &&
4511 TI->getOpcode() == Instruction::Add) {
4512 AddOp = TI; SubOp = FI;
4513 }
4514
4515 if (AddOp) {
4516 Value *OtherAddOp = 0;
4517 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4518 OtherAddOp = AddOp->getOperand(1);
4519 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4520 OtherAddOp = AddOp->getOperand(0);
4521 }
4522
4523 if (OtherAddOp) {
4524 // So at this point we know we have:
4525 // select C, (add X, Y), (sub X, ?)
4526 // We can do the transform profitably if either 'Y' = '?' or '?' is
4527 // a constant.
4528 if (SubOp->getOperand(1) == AddOp ||
4529 isa<Constant>(SubOp->getOperand(1))) {
4530 Value *NegVal;
4531 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4532 NegVal = ConstantExpr::getNeg(C);
4533 } else {
4534 NegVal = InsertNewInstBefore(
4535 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4536 }
4537
Chris Lattner51726c42005-01-14 17:35:12 +00004538 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00004539 Value *NewFalseOp = NegVal;
4540 if (AddOp != TI)
4541 std::swap(NewTrueOp, NewFalseOp);
4542 Instruction *NewSel =
4543 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanb1c93172005-04-21 23:48:37 +00004544
Chris Lattnera04c9042005-01-13 22:52:24 +00004545 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00004546 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00004547 }
4548 }
4549 }
4550 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004551
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004552 // See if we can fold the select into one of our operands.
4553 if (SI.getType()->isInteger()) {
4554 // See the comment above GetSelectFoldableOperands for a description of the
4555 // transformation we are doing here.
4556 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4557 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4558 !isa<Constant>(FalseVal))
4559 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4560 unsigned OpToFold = 0;
4561 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4562 OpToFold = 1;
4563 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4564 OpToFold = 2;
4565 }
4566
4567 if (OpToFold) {
4568 Constant *C = GetSelectFoldableConstant(TVI);
4569 std::string Name = TVI->getName(); TVI->setName("");
4570 Instruction *NewSel =
4571 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4572 Name);
4573 InsertNewInstBefore(NewSel, SI);
4574 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4575 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4576 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4577 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4578 else {
4579 assert(0 && "Unknown instruction!!");
4580 }
4581 }
4582 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00004583
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004584 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4585 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4586 !isa<Constant>(TrueVal))
4587 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4588 unsigned OpToFold = 0;
4589 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4590 OpToFold = 1;
4591 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4592 OpToFold = 2;
4593 }
4594
4595 if (OpToFold) {
4596 Constant *C = GetSelectFoldableConstant(FVI);
4597 std::string Name = FVI->getName(); FVI->setName("");
4598 Instruction *NewSel =
4599 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4600 Name);
4601 InsertNewInstBefore(NewSel, SI);
4602 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4603 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4604 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4605 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4606 else {
4607 assert(0 && "Unknown instruction!!");
4608 }
4609 }
4610 }
4611 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00004612
4613 if (BinaryOperator::isNot(CondVal)) {
4614 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4615 SI.setOperand(1, FalseVal);
4616 SI.setOperand(2, TrueVal);
4617 return &SI;
4618 }
4619
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004620 return 0;
4621}
4622
4623
Chris Lattnerc66b2232006-01-13 20:11:04 +00004624/// visitCallInst - CallInst simplification. This mostly only handles folding
4625/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
4626/// the heavy lifting.
4627///
Chris Lattner970c33a2003-06-19 17:00:31 +00004628Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00004629 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
4630 if (!II) return visitCallSite(&CI);
4631
Chris Lattner51ea1272004-02-28 05:22:00 +00004632 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4633 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00004634 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00004635 bool Changed = false;
4636
4637 // memmove/cpy/set of zero bytes is a noop.
4638 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4639 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4640
4641 // FIXME: Increase alignment here.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004642
Chris Lattner00648e12004-10-12 04:52:52 +00004643 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4644 if (CI->getRawValue() == 1) {
4645 // Replace the instruction with just byte operations. We would
4646 // transform other cases to loads/stores, but we don't know if
4647 // alignment is sufficient.
4648 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004649 }
4650
Chris Lattner00648e12004-10-12 04:52:52 +00004651 // If we have a memmove and the source operation is a constant global,
4652 // then the source and dest pointers can't alias, so we can change this
4653 // into a call to memcpy.
Chris Lattnerc66b2232006-01-13 20:11:04 +00004654 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II))
Chris Lattner00648e12004-10-12 04:52:52 +00004655 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4656 if (GVSrc->isConstant()) {
4657 Module *M = CI.getParent()->getParent()->getParent();
4658 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4659 CI.getCalledFunction()->getFunctionType());
4660 CI.setOperand(0, MemCpy);
4661 Changed = true;
4662 }
4663
Chris Lattnerc66b2232006-01-13 20:11:04 +00004664 if (Changed) return II;
4665 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(II)) {
Chris Lattner95307542004-11-18 21:41:39 +00004666 // If this stoppoint is at the same source location as the previous
4667 // stoppoint in the chain, it is not needed.
4668 if (DbgStopPointInst *PrevSPI =
4669 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4670 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4671 SPI->getColNo() == PrevSPI->getColNo()) {
4672 SPI->replaceAllUsesWith(PrevSPI);
4673 return EraseInstFromFunction(CI);
4674 }
Chris Lattner503221f2006-01-13 21:28:09 +00004675 } else {
4676 switch (II->getIntrinsicID()) {
4677 default: break;
4678 case Intrinsic::stackrestore: {
4679 // If the save is right next to the restore, remove the restore. This can
4680 // happen when variable allocas are DCE'd.
4681 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
4682 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
4683 BasicBlock::iterator BI = SS;
4684 if (&*++BI == II)
4685 return EraseInstFromFunction(CI);
4686 }
4687 }
4688
4689 // If the stack restore is in a return/unwind block and if there are no
4690 // allocas or calls between the restore and the return, nuke the restore.
4691 TerminatorInst *TI = II->getParent()->getTerminator();
4692 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
4693 BasicBlock::iterator BI = II;
4694 bool CannotRemove = false;
4695 for (++BI; &*BI != TI; ++BI) {
4696 if (isa<AllocaInst>(BI) ||
4697 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
4698 CannotRemove = true;
4699 break;
4700 }
4701 }
4702 if (!CannotRemove)
4703 return EraseInstFromFunction(CI);
4704 }
4705 break;
4706 }
4707 }
Chris Lattner00648e12004-10-12 04:52:52 +00004708 }
4709
Chris Lattnerc66b2232006-01-13 20:11:04 +00004710 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00004711}
4712
4713// InvokeInst simplification
4714//
4715Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00004716 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00004717}
4718
Chris Lattneraec3d942003-10-07 22:32:43 +00004719// visitCallSite - Improvements for call and invoke instructions.
4720//
4721Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004722 bool Changed = false;
4723
4724 // If the callee is a constexpr cast of a function, attempt to move the cast
4725 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00004726 if (transformConstExprCastCall(CS)) return 0;
4727
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004728 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00004729
Chris Lattner61d9d812005-05-13 07:09:09 +00004730 if (Function *CalleeF = dyn_cast<Function>(Callee))
4731 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4732 Instruction *OldCall = CS.getInstruction();
4733 // If the call and callee calling conventions don't match, this call must
4734 // be unreachable, as the call is undefined.
4735 new StoreInst(ConstantBool::True,
4736 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4737 if (!OldCall->use_empty())
4738 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4739 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4740 return EraseInstFromFunction(*OldCall);
4741 return 0;
4742 }
4743
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004744 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4745 // This instruction is not reachable, just remove it. We insert a store to
4746 // undef so that we know that this code is not reachable, despite the fact
4747 // that we can't modify the CFG here.
4748 new StoreInst(ConstantBool::True,
4749 UndefValue::get(PointerType::get(Type::BoolTy)),
4750 CS.getInstruction());
4751
4752 if (!CS.getInstruction()->use_empty())
4753 CS.getInstruction()->
4754 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4755
4756 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4757 // Don't break the CFG, insert a dummy cond branch.
4758 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4759 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00004760 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004761 return EraseInstFromFunction(*CS.getInstruction());
4762 }
Chris Lattner81a7a232004-10-16 18:11:37 +00004763
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004764 const PointerType *PTy = cast<PointerType>(Callee->getType());
4765 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4766 if (FTy->isVarArg()) {
4767 // See if we can optimize any arguments passed through the varargs area of
4768 // the call.
4769 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4770 E = CS.arg_end(); I != E; ++I)
4771 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4772 // If this cast does not effect the value passed through the varargs
4773 // area, we can eliminate the use of the cast.
4774 Value *Op = CI->getOperand(0);
4775 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4776 *I = Op;
4777 Changed = true;
4778 }
4779 }
4780 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004781
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004782 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00004783}
4784
Chris Lattner970c33a2003-06-19 17:00:31 +00004785// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4786// attempt to move the cast to the arguments of the call/invoke.
4787//
4788bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4789 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4790 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00004791 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00004792 return false;
Reid Spencer87436872004-07-18 00:38:32 +00004793 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00004794 Instruction *Caller = CS.getInstruction();
4795
4796 // Okay, this is a cast from a function to a different type. Unless doing so
4797 // would cause a type conversion of one of our arguments, change this call to
4798 // be a direct call with arguments casted to the appropriate types.
4799 //
4800 const FunctionType *FT = Callee->getFunctionType();
4801 const Type *OldRetTy = Caller->getType();
4802
Chris Lattner1f7942f2004-01-14 06:06:08 +00004803 // Check to see if we are changing the return type...
4804 if (OldRetTy != FT->getReturnType()) {
4805 if (Callee->isExternal() &&
4806 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4807 !Caller->use_empty())
4808 return false; // Cannot transform this return value...
4809
4810 // If the callsite is an invoke instruction, and the return value is used by
4811 // a PHI node in a successor, we cannot change the return type of the call
4812 // because there is no place to put the cast instruction (without breaking
4813 // the critical edge). Bail out in this case.
4814 if (!Caller->use_empty())
4815 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4816 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4817 UI != E; ++UI)
4818 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4819 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004820 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00004821 return false;
4822 }
Chris Lattner970c33a2003-06-19 17:00:31 +00004823
4824 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4825 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004826
Chris Lattner970c33a2003-06-19 17:00:31 +00004827 CallSite::arg_iterator AI = CS.arg_begin();
4828 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4829 const Type *ParamTy = FT->getParamType(i);
4830 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004831 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00004832 }
4833
4834 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4835 Callee->isExternal())
4836 return false; // Do not delete arguments unless we have a function body...
4837
4838 // Okay, we decided that this is a safe thing to do: go ahead and start
4839 // inserting cast instructions as necessary...
4840 std::vector<Value*> Args;
4841 Args.reserve(NumActualArgs);
4842
4843 AI = CS.arg_begin();
4844 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4845 const Type *ParamTy = FT->getParamType(i);
4846 if ((*AI)->getType() == ParamTy) {
4847 Args.push_back(*AI);
4848 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00004849 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4850 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00004851 }
4852 }
4853
4854 // If the function takes more arguments than the call was taking, add them
4855 // now...
4856 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4857 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4858
4859 // If we are removing arguments to the function, emit an obnoxious warning...
4860 if (FT->getNumParams() < NumActualArgs)
4861 if (!FT->isVarArg()) {
4862 std::cerr << "WARNING: While resolving call to function '"
4863 << Callee->getName() << "' arguments were dropped!\n";
4864 } else {
4865 // Add all of the arguments in their promoted form to the arg list...
4866 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4867 const Type *PTy = getPromotedType((*AI)->getType());
4868 if (PTy != (*AI)->getType()) {
4869 // Must promote to pass through va_arg area!
4870 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4871 InsertNewInstBefore(Cast, *Caller);
4872 Args.push_back(Cast);
4873 } else {
4874 Args.push_back(*AI);
4875 }
4876 }
4877 }
4878
4879 if (FT->getReturnType() == Type::VoidTy)
4880 Caller->setName(""); // Void type should not have a name...
4881
4882 Instruction *NC;
4883 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004884 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00004885 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00004886 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004887 } else {
4888 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00004889 if (cast<CallInst>(Caller)->isTailCall())
4890 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00004891 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004892 }
4893
4894 // Insert a cast of the return type as necessary...
4895 Value *NV = NC;
4896 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4897 if (NV->getType() != Type::VoidTy) {
4898 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00004899
4900 // If this is an invoke instruction, we should insert it after the first
4901 // non-phi, instruction in the normal successor block.
4902 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4903 BasicBlock::iterator I = II->getNormalDest()->begin();
4904 while (isa<PHINode>(I)) ++I;
4905 InsertNewInstBefore(NC, *I);
4906 } else {
4907 // Otherwise, it's a call, just insert cast right after the call instr
4908 InsertNewInstBefore(NC, *Caller);
4909 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004910 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00004911 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00004912 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00004913 }
4914 }
4915
4916 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4917 Caller->replaceAllUsesWith(NV);
4918 Caller->getParent()->getInstList().erase(Caller);
4919 removeFromWorkList(Caller);
4920 return true;
4921}
4922
4923
Chris Lattner7515cab2004-11-14 19:13:23 +00004924// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4925// operator and they all are only used by the PHI, PHI together their
4926// inputs, and do the operation once, to the result of the PHI.
4927Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4928 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4929
4930 // Scan the instruction, looking for input operations that can be folded away.
4931 // If all input operands to the phi are the same instruction (e.g. a cast from
4932 // the same type or "+42") we can pull the operation through the PHI, reducing
4933 // code size and simplifying code.
4934 Constant *ConstantOp = 0;
4935 const Type *CastSrcTy = 0;
4936 if (isa<CastInst>(FirstInst)) {
4937 CastSrcTy = FirstInst->getOperand(0)->getType();
4938 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4939 // Can fold binop or shift if the RHS is a constant.
4940 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4941 if (ConstantOp == 0) return 0;
4942 } else {
4943 return 0; // Cannot fold this operation.
4944 }
4945
4946 // Check to see if all arguments are the same operation.
4947 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4948 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4949 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4950 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4951 return 0;
4952 if (CastSrcTy) {
4953 if (I->getOperand(0)->getType() != CastSrcTy)
4954 return 0; // Cast operation must match.
4955 } else if (I->getOperand(1) != ConstantOp) {
4956 return 0;
4957 }
4958 }
4959
4960 // Okay, they are all the same operation. Create a new PHI node of the
4961 // correct type, and PHI together all of the LHS's of the instructions.
4962 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4963 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00004964 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00004965
4966 Value *InVal = FirstInst->getOperand(0);
4967 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00004968
4969 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00004970 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4971 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4972 if (NewInVal != InVal)
4973 InVal = 0;
4974 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4975 }
4976
4977 Value *PhiVal;
4978 if (InVal) {
4979 // The new PHI unions all of the same values together. This is really
4980 // common, so we handle it intelligently here for compile-time speed.
4981 PhiVal = InVal;
4982 delete NewPN;
4983 } else {
4984 InsertNewInstBefore(NewPN, PN);
4985 PhiVal = NewPN;
4986 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004987
Chris Lattner7515cab2004-11-14 19:13:23 +00004988 // Insert and return the new operation.
4989 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004990 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00004991 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004992 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004993 else
4994 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00004995 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004996}
Chris Lattner48a44f72002-05-02 17:06:02 +00004997
Chris Lattner71536432005-01-17 05:10:15 +00004998/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4999/// that is dead.
5000static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5001 if (PN->use_empty()) return true;
5002 if (!PN->hasOneUse()) return false;
5003
5004 // Remember this node, and if we find the cycle, return.
5005 if (!PotentiallyDeadPHIs.insert(PN).second)
5006 return true;
5007
5008 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5009 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005010
Chris Lattner71536432005-01-17 05:10:15 +00005011 return false;
5012}
5013
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005014// PHINode simplification
5015//
Chris Lattner113f4f42002-06-25 16:13:24 +00005016Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00005017 if (Value *V = PN.hasConstantValue())
5018 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00005019
5020 // If the only user of this instruction is a cast instruction, and all of the
5021 // incoming values are constants, change this PHI to merge together the casted
5022 // constants.
5023 if (PN.hasOneUse())
5024 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5025 if (CI->getType() != PN.getType()) { // noop casts will be folded
5026 bool AllConstant = true;
5027 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5028 if (!isa<Constant>(PN.getIncomingValue(i))) {
5029 AllConstant = false;
5030 break;
5031 }
5032 if (AllConstant) {
5033 // Make a new PHI with all casted values.
5034 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5035 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5036 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5037 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5038 PN.getIncomingBlock(i));
5039 }
5040
5041 // Update the cast instruction.
5042 CI->setOperand(0, New);
5043 WorkList.push_back(CI); // revisit the cast instruction to fold.
5044 WorkList.push_back(New); // Make sure to revisit the new Phi
5045 return &PN; // PN is now dead!
5046 }
5047 }
Chris Lattner7515cab2004-11-14 19:13:23 +00005048
5049 // If all PHI operands are the same operation, pull them through the PHI,
5050 // reducing code size.
5051 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5052 PN.getIncomingValue(0)->hasOneUse())
5053 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5054 return Result;
5055
Chris Lattner71536432005-01-17 05:10:15 +00005056 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5057 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5058 // PHI)... break the cycle.
5059 if (PN.hasOneUse())
5060 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5061 std::set<PHINode*> PotentiallyDeadPHIs;
5062 PotentiallyDeadPHIs.insert(&PN);
5063 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5064 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5065 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005066
Chris Lattner91daeb52003-12-19 05:58:40 +00005067 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005068}
5069
Chris Lattner69193f92004-04-05 01:30:19 +00005070static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5071 Instruction *InsertPoint,
5072 InstCombiner *IC) {
5073 unsigned PS = IC->getTargetData().getPointerSize();
5074 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00005075 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5076 // We must insert a cast to ensure we sign-extend.
5077 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5078 V->getName()), *InsertPoint);
5079 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5080 *InsertPoint);
5081}
5082
Chris Lattner48a44f72002-05-02 17:06:02 +00005083
Chris Lattner113f4f42002-06-25 16:13:24 +00005084Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005085 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00005086 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00005087 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005088 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00005089 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005090
Chris Lattner81a7a232004-10-16 18:11:37 +00005091 if (isa<UndefValue>(GEP.getOperand(0)))
5092 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5093
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005094 bool HasZeroPointerIndex = false;
5095 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5096 HasZeroPointerIndex = C->isNullValue();
5097
5098 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00005099 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00005100
Chris Lattner69193f92004-04-05 01:30:19 +00005101 // Eliminate unneeded casts for indices.
5102 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00005103 gep_type_iterator GTI = gep_type_begin(GEP);
5104 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5105 if (isa<SequentialType>(*GTI)) {
5106 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5107 Value *Src = CI->getOperand(0);
5108 const Type *SrcTy = Src->getType();
5109 const Type *DestTy = CI->getType();
5110 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005111 if (SrcTy->getPrimitiveSizeInBits() ==
5112 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005113 // We can always eliminate a cast from ulong or long to the other.
5114 // We can always eliminate a cast from uint to int or the other on
5115 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005116 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00005117 MadeChange = true;
5118 GEP.setOperand(i, Src);
5119 }
5120 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5121 SrcTy->getPrimitiveSize() == 4) {
5122 // We can always eliminate a cast from int to [u]long. We can
5123 // eliminate a cast from uint to [u]long iff the target is a 32-bit
5124 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005125 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005126 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005127 MadeChange = true;
5128 GEP.setOperand(i, Src);
5129 }
Chris Lattner69193f92004-04-05 01:30:19 +00005130 }
5131 }
5132 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00005133 // If we are using a wider index than needed for this platform, shrink it
5134 // to what we need. If the incoming value needs a cast instruction,
5135 // insert it. This explicit cast can make subsequent optimizations more
5136 // obvious.
5137 Value *Op = GEP.getOperand(i);
5138 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005139 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00005140 GEP.setOperand(i, ConstantExpr::getCast(C,
5141 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005142 MadeChange = true;
5143 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005144 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5145 Op->getName()), GEP);
5146 GEP.setOperand(i, Op);
5147 MadeChange = true;
5148 }
Chris Lattner44d0b952004-07-20 01:48:15 +00005149
5150 // If this is a constant idx, make sure to canonicalize it to be a signed
5151 // operand, otherwise CSE and other optimizations are pessimized.
5152 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5153 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5154 CUI->getType()->getSignedVersion()));
5155 MadeChange = true;
5156 }
Chris Lattner69193f92004-04-05 01:30:19 +00005157 }
5158 if (MadeChange) return &GEP;
5159
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005160 // Combine Indices - If the source pointer to this getelementptr instruction
5161 // is a getelementptr instruction, combine the indices of the two
5162 // getelementptr instructions into a single instruction.
5163 //
Chris Lattner57c67b02004-03-25 22:59:29 +00005164 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00005165 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00005166 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00005167
5168 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005169 // Note that if our source is a gep chain itself that we wait for that
5170 // chain to be resolved before we perform this transformation. This
5171 // avoids us creating a TON of code in some cases.
5172 //
5173 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5174 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5175 return 0; // Wait until our source is folded to completion.
5176
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005177 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00005178
5179 // Find out whether the last index in the source GEP is a sequential idx.
5180 bool EndsWithSequential = false;
5181 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5182 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00005183 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005184
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005185 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00005186 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00005187 // Replace: gep (gep %P, long B), long A, ...
5188 // With: T = long A+B; gep %P, T, ...
5189 //
Chris Lattner5f667a62004-05-07 22:09:22 +00005190 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00005191 if (SO1 == Constant::getNullValue(SO1->getType())) {
5192 Sum = GO1;
5193 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5194 Sum = SO1;
5195 } else {
5196 // If they aren't the same type, convert both to an integer of the
5197 // target's pointer size.
5198 if (SO1->getType() != GO1->getType()) {
5199 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5200 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5201 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5202 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5203 } else {
5204 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00005205 if (SO1->getType()->getPrimitiveSize() == PS) {
5206 // Convert GO1 to SO1's type.
5207 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5208
5209 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5210 // Convert SO1 to GO1's type.
5211 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5212 } else {
5213 const Type *PT = TD->getIntPtrType();
5214 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5215 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5216 }
5217 }
5218 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005219 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5220 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5221 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005222 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5223 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00005224 }
Chris Lattner69193f92004-04-05 01:30:19 +00005225 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005226
5227 // Recycle the GEP we already have if possible.
5228 if (SrcGEPOperands.size() == 2) {
5229 GEP.setOperand(0, SrcGEPOperands[0]);
5230 GEP.setOperand(1, Sum);
5231 return &GEP;
5232 } else {
5233 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5234 SrcGEPOperands.end()-1);
5235 Indices.push_back(Sum);
5236 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5237 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005238 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00005239 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005240 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005241 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00005242 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5243 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005244 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5245 }
5246
5247 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00005248 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005249
Chris Lattner5f667a62004-05-07 22:09:22 +00005250 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005251 // GEP of global variable. If all of the indices for this GEP are
5252 // constants, we can promote this to a constexpr instead of an instruction.
5253
5254 // Scan for nonconstants...
5255 std::vector<Constant*> Indices;
5256 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5257 for (; I != E && isa<Constant>(*I); ++I)
5258 Indices.push_back(cast<Constant>(*I));
5259
5260 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00005261 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005262
5263 // Replace all uses of the GEP with the new constexpr...
5264 return ReplaceInstUsesWith(GEP, CE);
5265 }
Chris Lattner567b81f2005-09-13 00:40:14 +00005266 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5267 if (!isa<PointerType>(X->getType())) {
5268 // Not interesting. Source pointer must be a cast from pointer.
5269 } else if (HasZeroPointerIndex) {
5270 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5271 // into : GEP [10 x ubyte]* X, long 0, ...
5272 //
5273 // This occurs when the program declares an array extern like "int X[];"
5274 //
5275 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5276 const PointerType *XTy = cast<PointerType>(X->getType());
5277 if (const ArrayType *XATy =
5278 dyn_cast<ArrayType>(XTy->getElementType()))
5279 if (const ArrayType *CATy =
5280 dyn_cast<ArrayType>(CPTy->getElementType()))
5281 if (CATy->getElementType() == XATy->getElementType()) {
5282 // At this point, we know that the cast source type is a pointer
5283 // to an array of the same type as the destination pointer
5284 // array. Because the array type is never stepped over (there
5285 // is a leading zero) we can fold the cast into this GEP.
5286 GEP.setOperand(0, X);
5287 return &GEP;
5288 }
5289 } else if (GEP.getNumOperands() == 2) {
5290 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00005291 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5292 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00005293 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5294 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5295 if (isa<ArrayType>(SrcElTy) &&
5296 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5297 TD->getTypeSize(ResElTy)) {
5298 Value *V = InsertNewInstBefore(
5299 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5300 GEP.getOperand(1), GEP.getName()), GEP);
5301 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005302 }
Chris Lattner2a893292005-09-13 18:36:04 +00005303
5304 // Transform things like:
5305 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5306 // (where tmp = 8*tmp2) into:
5307 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5308
5309 if (isa<ArrayType>(SrcElTy) &&
5310 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5311 uint64_t ArrayEltSize =
5312 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5313
5314 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5315 // allow either a mul, shift, or constant here.
5316 Value *NewIdx = 0;
5317 ConstantInt *Scale = 0;
5318 if (ArrayEltSize == 1) {
5319 NewIdx = GEP.getOperand(1);
5320 Scale = ConstantInt::get(NewIdx->getType(), 1);
5321 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00005322 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00005323 Scale = CI;
5324 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5325 if (Inst->getOpcode() == Instruction::Shl &&
5326 isa<ConstantInt>(Inst->getOperand(1))) {
5327 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5328 if (Inst->getType()->isSigned())
5329 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5330 else
5331 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5332 NewIdx = Inst->getOperand(0);
5333 } else if (Inst->getOpcode() == Instruction::Mul &&
5334 isa<ConstantInt>(Inst->getOperand(1))) {
5335 Scale = cast<ConstantInt>(Inst->getOperand(1));
5336 NewIdx = Inst->getOperand(0);
5337 }
5338 }
5339
5340 // If the index will be to exactly the right offset with the scale taken
5341 // out, perform the transformation.
5342 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5343 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5344 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00005345 (int64_t)C->getRawValue() /
5346 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00005347 else
5348 Scale = ConstantUInt::get(Scale->getType(),
5349 Scale->getRawValue() / ArrayEltSize);
5350 if (Scale->getRawValue() != 1) {
5351 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5352 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5353 NewIdx = InsertNewInstBefore(Sc, GEP);
5354 }
5355
5356 // Insert the new GEP instruction.
5357 Instruction *Idx =
5358 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5359 NewIdx, GEP.getName());
5360 Idx = InsertNewInstBefore(Idx, GEP);
5361 return new CastInst(Idx, GEP.getType());
5362 }
5363 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005364 }
Chris Lattnerca081252001-12-14 16:52:21 +00005365 }
5366
Chris Lattnerca081252001-12-14 16:52:21 +00005367 return 0;
5368}
5369
Chris Lattner1085bdf2002-11-04 16:18:53 +00005370Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5371 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5372 if (AI.isArrayAllocation()) // Check C != 1
5373 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5374 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005375 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00005376
5377 // Create and insert the replacement instruction...
5378 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005379 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005380 else {
5381 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00005382 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005383 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005384
5385 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005386
Chris Lattner1085bdf2002-11-04 16:18:53 +00005387 // Scan to the end of the allocation instructions, to skip over a block of
5388 // allocas if possible...
5389 //
5390 BasicBlock::iterator It = New;
5391 while (isa<AllocationInst>(*It)) ++It;
5392
5393 // Now that I is pointing to the first non-allocation-inst in the block,
5394 // insert our getelementptr instruction...
5395 //
Chris Lattner809dfac2005-05-04 19:10:26 +00005396 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5397 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5398 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00005399
5400 // Now make everything use the getelementptr instead of the original
5401 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00005402 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00005403 } else if (isa<UndefValue>(AI.getArraySize())) {
5404 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00005405 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005406
5407 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5408 // Note that we only do this for alloca's, because malloc should allocate and
5409 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005410 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00005411 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00005412 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5413
Chris Lattner1085bdf2002-11-04 16:18:53 +00005414 return 0;
5415}
5416
Chris Lattner8427bff2003-12-07 01:24:23 +00005417Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5418 Value *Op = FI.getOperand(0);
5419
5420 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5421 if (CastInst *CI = dyn_cast<CastInst>(Op))
5422 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5423 FI.setOperand(0, CI->getOperand(0));
5424 return &FI;
5425 }
5426
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005427 // free undef -> unreachable.
5428 if (isa<UndefValue>(Op)) {
5429 // Insert a new store to null because we cannot modify the CFG here.
5430 new StoreInst(ConstantBool::True,
5431 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5432 return EraseInstFromFunction(FI);
5433 }
5434
Chris Lattnerf3a36602004-02-28 04:57:37 +00005435 // If we have 'free null' delete the instruction. This can happen in stl code
5436 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005437 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00005438 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00005439
Chris Lattner8427bff2003-12-07 01:24:23 +00005440 return 0;
5441}
5442
5443
Chris Lattner72684fe2005-01-31 05:51:45 +00005444/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00005445static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5446 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005447 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00005448
5449 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005450 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00005451 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005452
5453 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5454 // If the source is an array, the code below will not succeed. Check to
5455 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5456 // constants.
5457 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5458 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5459 if (ASrcTy->getNumElements() != 0) {
5460 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5461 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5462 SrcTy = cast<PointerType>(CastOp->getType());
5463 SrcPTy = SrcTy->getElementType();
5464 }
5465
5466 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00005467 // Do not allow turning this into a load of an integer, which is then
5468 // casted to a pointer, this pessimizes pointer analysis a lot.
5469 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005470 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005471 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00005472
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005473 // Okay, we are casting from one integer or pointer type to another of
5474 // the same size. Instead of casting the pointer before the load, cast
5475 // the result of the loaded value.
5476 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5477 CI->getName(),
5478 LI.isVolatile()),LI);
5479 // Now cast the result of the load.
5480 return new CastInst(NewLoad, LI.getType());
5481 }
Chris Lattner35e24772004-07-13 01:49:43 +00005482 }
5483 }
5484 return 0;
5485}
5486
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005487/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00005488/// from this value cannot trap. If it is not obviously safe to load from the
5489/// specified pointer, we do a quick local scan of the basic block containing
5490/// ScanFrom, to determine if the address is already accessed.
5491static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5492 // If it is an alloca or global variable, it is always safe to load from.
5493 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5494
5495 // Otherwise, be a little bit agressive by scanning the local block where we
5496 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005497 // from/to. If so, the previous load or store would have already trapped,
5498 // so there is no harm doing an extra load (also, CSE will later eliminate
5499 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00005500 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5501
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005502 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00005503 --BBI;
5504
5505 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5506 if (LI->getOperand(0) == V) return true;
5507 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5508 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005509
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005510 }
Chris Lattnere6f13092004-09-19 19:18:10 +00005511 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005512}
5513
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005514Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5515 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00005516
Chris Lattnera9d84e32005-05-01 04:24:53 +00005517 // load (cast X) --> cast (load X) iff safe
5518 if (CastInst *CI = dyn_cast<CastInst>(Op))
5519 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5520 return Res;
5521
5522 // None of the following transforms are legal for volatile loads.
5523 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005524
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005525 if (&LI.getParent()->front() != &LI) {
5526 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005527 // If the instruction immediately before this is a store to the same
5528 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005529 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5530 if (SI->getOperand(1) == LI.getOperand(0))
5531 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005532 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5533 if (LIB->getOperand(0) == LI.getOperand(0))
5534 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005535 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00005536
5537 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5538 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5539 isa<UndefValue>(GEPI->getOperand(0))) {
5540 // Insert a new store to null instruction before the load to indicate
5541 // that this code is not reachable. We do this instead of inserting
5542 // an unreachable instruction directly because we cannot modify the
5543 // CFG.
5544 new StoreInst(UndefValue::get(LI.getType()),
5545 Constant::getNullValue(Op->getType()), &LI);
5546 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5547 }
5548
Chris Lattner81a7a232004-10-16 18:11:37 +00005549 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00005550 // load null/undef -> undef
5551 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005552 // Insert a new store to null instruction before the load to indicate that
5553 // this code is not reachable. We do this instead of inserting an
5554 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00005555 new StoreInst(UndefValue::get(LI.getType()),
5556 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00005557 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005558 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005559
Chris Lattner81a7a232004-10-16 18:11:37 +00005560 // Instcombine load (constant global) into the value loaded.
5561 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5562 if (GV->isConstant() && !GV->isExternal())
5563 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00005564
Chris Lattner81a7a232004-10-16 18:11:37 +00005565 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5566 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5567 if (CE->getOpcode() == Instruction::GetElementPtr) {
5568 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5569 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00005570 if (Constant *V =
5571 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00005572 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00005573 if (CE->getOperand(0)->isNullValue()) {
5574 // Insert a new store to null instruction before the load to indicate
5575 // that this code is not reachable. We do this instead of inserting
5576 // an unreachable instruction directly because we cannot modify the
5577 // CFG.
5578 new StoreInst(UndefValue::get(LI.getType()),
5579 Constant::getNullValue(Op->getType()), &LI);
5580 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5581 }
5582
Chris Lattner81a7a232004-10-16 18:11:37 +00005583 } else if (CE->getOpcode() == Instruction::Cast) {
5584 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5585 return Res;
5586 }
5587 }
Chris Lattnere228ee52004-04-08 20:39:49 +00005588
Chris Lattnera9d84e32005-05-01 04:24:53 +00005589 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005590 // Change select and PHI nodes to select values instead of addresses: this
5591 // helps alias analysis out a lot, allows many others simplifications, and
5592 // exposes redundancy in the code.
5593 //
5594 // Note that we cannot do the transformation unless we know that the
5595 // introduced loads cannot trap! Something like this is valid as long as
5596 // the condition is always false: load (select bool %C, int* null, int* %G),
5597 // but it would not be valid if we transformed it to load from null
5598 // unconditionally.
5599 //
5600 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5601 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00005602 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5603 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005604 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00005605 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005606 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00005607 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005608 return new SelectInst(SI->getCondition(), V1, V2);
5609 }
5610
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00005611 // load (select (cond, null, P)) -> load P
5612 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5613 if (C->isNullValue()) {
5614 LI.setOperand(0, SI->getOperand(2));
5615 return &LI;
5616 }
5617
5618 // load (select (cond, P, null)) -> load P
5619 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5620 if (C->isNullValue()) {
5621 LI.setOperand(0, SI->getOperand(1));
5622 return &LI;
5623 }
5624
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005625 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5626 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00005627 bool Safe = PN->getParent() == LI.getParent();
5628
5629 // Scan all of the instructions between the PHI and the load to make
5630 // sure there are no instructions that might possibly alter the value
5631 // loaded from the PHI.
5632 if (Safe) {
5633 BasicBlock::iterator I = &LI;
5634 for (--I; !isa<PHINode>(I); --I)
5635 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5636 Safe = false;
5637 break;
5638 }
5639 }
5640
5641 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00005642 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00005643 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005644 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00005645
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005646 if (Safe) {
5647 // Create the PHI.
5648 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5649 InsertNewInstBefore(NewPN, *PN);
5650 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5651
5652 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5653 BasicBlock *BB = PN->getIncomingBlock(i);
5654 Value *&TheLoad = LoadMap[BB];
5655 if (TheLoad == 0) {
5656 Value *InVal = PN->getIncomingValue(i);
5657 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5658 InVal->getName()+".val"),
5659 *BB->getTerminator());
5660 }
5661 NewPN->addIncoming(TheLoad, BB);
5662 }
5663 return ReplaceInstUsesWith(LI, NewPN);
5664 }
5665 }
5666 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005667 return 0;
5668}
5669
Chris Lattner72684fe2005-01-31 05:51:45 +00005670/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5671/// when possible.
5672static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5673 User *CI = cast<User>(SI.getOperand(1));
5674 Value *CastOp = CI->getOperand(0);
5675
5676 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5677 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5678 const Type *SrcPTy = SrcTy->getElementType();
5679
5680 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5681 // If the source is an array, the code below will not succeed. Check to
5682 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5683 // constants.
5684 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5685 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5686 if (ASrcTy->getNumElements() != 0) {
5687 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5688 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5689 SrcTy = cast<PointerType>(CastOp->getType());
5690 SrcPTy = SrcTy->getElementType();
5691 }
5692
5693 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005694 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00005695 IC.getTargetData().getTypeSize(DestPTy)) {
5696
5697 // Okay, we are casting from one integer or pointer type to another of
5698 // the same size. Instead of casting the pointer before the store, cast
5699 // the value to be stored.
5700 Value *NewCast;
5701 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5702 NewCast = ConstantExpr::getCast(C, SrcPTy);
5703 else
5704 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5705 SrcPTy,
5706 SI.getOperand(0)->getName()+".c"), SI);
5707
5708 return new StoreInst(NewCast, CastOp);
5709 }
5710 }
5711 }
5712 return 0;
5713}
5714
Chris Lattner31f486c2005-01-31 05:36:43 +00005715Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5716 Value *Val = SI.getOperand(0);
5717 Value *Ptr = SI.getOperand(1);
5718
5719 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5720 removeFromWorkList(&SI);
5721 SI.eraseFromParent();
5722 ++NumCombined;
5723 return 0;
5724 }
5725
5726 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5727
5728 // store X, null -> turns into 'unreachable' in SimplifyCFG
5729 if (isa<ConstantPointerNull>(Ptr)) {
5730 if (!isa<UndefValue>(Val)) {
5731 SI.setOperand(0, UndefValue::get(Val->getType()));
5732 if (Instruction *U = dyn_cast<Instruction>(Val))
5733 WorkList.push_back(U); // Dropped a use.
5734 ++NumCombined;
5735 }
5736 return 0; // Do not modify these!
5737 }
5738
5739 // store undef, Ptr -> noop
5740 if (isa<UndefValue>(Val)) {
5741 removeFromWorkList(&SI);
5742 SI.eraseFromParent();
5743 ++NumCombined;
5744 return 0;
5745 }
5746
Chris Lattner72684fe2005-01-31 05:51:45 +00005747 // If the pointer destination is a cast, see if we can fold the cast into the
5748 // source instead.
5749 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5750 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5751 return Res;
5752 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5753 if (CE->getOpcode() == Instruction::Cast)
5754 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5755 return Res;
5756
Chris Lattner219175c2005-09-12 23:23:25 +00005757
5758 // If this store is the last instruction in the basic block, and if the block
5759 // ends with an unconditional branch, try to move it to the successor block.
5760 BasicBlock::iterator BBI = &SI; ++BBI;
5761 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5762 if (BI->isUnconditional()) {
5763 // Check to see if the successor block has exactly two incoming edges. If
5764 // so, see if the other predecessor contains a store to the same location.
5765 // if so, insert a PHI node (if needed) and move the stores down.
5766 BasicBlock *Dest = BI->getSuccessor(0);
5767
5768 pred_iterator PI = pred_begin(Dest);
5769 BasicBlock *Other = 0;
5770 if (*PI != BI->getParent())
5771 Other = *PI;
5772 ++PI;
5773 if (PI != pred_end(Dest)) {
5774 if (*PI != BI->getParent())
5775 if (Other)
5776 Other = 0;
5777 else
5778 Other = *PI;
5779 if (++PI != pred_end(Dest))
5780 Other = 0;
5781 }
5782 if (Other) { // If only one other pred...
5783 BBI = Other->getTerminator();
5784 // Make sure this other block ends in an unconditional branch and that
5785 // there is an instruction before the branch.
5786 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5787 BBI != Other->begin()) {
5788 --BBI;
5789 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5790
5791 // If this instruction is a store to the same location.
5792 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5793 // Okay, we know we can perform this transformation. Insert a PHI
5794 // node now if we need it.
5795 Value *MergedVal = OtherStore->getOperand(0);
5796 if (MergedVal != SI.getOperand(0)) {
5797 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5798 PN->reserveOperandSpace(2);
5799 PN->addIncoming(SI.getOperand(0), SI.getParent());
5800 PN->addIncoming(OtherStore->getOperand(0), Other);
5801 MergedVal = InsertNewInstBefore(PN, Dest->front());
5802 }
5803
5804 // Advance to a place where it is safe to insert the new store and
5805 // insert it.
5806 BBI = Dest->begin();
5807 while (isa<PHINode>(BBI)) ++BBI;
5808 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5809 OtherStore->isVolatile()), *BBI);
5810
5811 // Nuke the old stores.
5812 removeFromWorkList(&SI);
5813 removeFromWorkList(OtherStore);
5814 SI.eraseFromParent();
5815 OtherStore->eraseFromParent();
5816 ++NumCombined;
5817 return 0;
5818 }
5819 }
5820 }
5821 }
5822
Chris Lattner31f486c2005-01-31 05:36:43 +00005823 return 0;
5824}
5825
5826
Chris Lattner9eef8a72003-06-04 04:46:00 +00005827Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5828 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00005829 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00005830 BasicBlock *TrueDest;
5831 BasicBlock *FalseDest;
5832 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
5833 !isa<Constant>(X)) {
5834 // Swap Destinations and condition...
5835 BI.setCondition(X);
5836 BI.setSuccessor(0, FalseDest);
5837 BI.setSuccessor(1, TrueDest);
5838 return &BI;
5839 }
5840
5841 // Cannonicalize setne -> seteq
5842 Instruction::BinaryOps Op; Value *Y;
5843 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
5844 TrueDest, FalseDest)))
5845 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
5846 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
5847 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
5848 std::string Name = I->getName(); I->setName("");
5849 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
5850 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00005851 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00005852 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00005853 BI.setSuccessor(0, FalseDest);
5854 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00005855 removeFromWorkList(I);
5856 I->getParent()->getInstList().erase(I);
5857 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00005858 return &BI;
5859 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005860
Chris Lattner9eef8a72003-06-04 04:46:00 +00005861 return 0;
5862}
Chris Lattner1085bdf2002-11-04 16:18:53 +00005863
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005864Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5865 Value *Cond = SI.getCondition();
5866 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5867 if (I->getOpcode() == Instruction::Add)
5868 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5869 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5870 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00005871 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005872 AddRHS));
5873 SI.setOperand(0, I->getOperand(0));
5874 WorkList.push_back(I);
5875 return &SI;
5876 }
5877 }
5878 return 0;
5879}
5880
Robert Bocchinoa8352962006-01-13 22:48:06 +00005881Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
5882 if (ConstantAggregateZero *C =
5883 dyn_cast<ConstantAggregateZero>(EI.getOperand(0))) {
5884 // If packed val is constant 0, replace extract with scalar 0
5885 const Type *Ty = cast<PackedType>(C->getType())->getElementType();
5886 EI.replaceAllUsesWith(Constant::getNullValue(Ty));
5887 return ReplaceInstUsesWith(EI, Constant::getNullValue(Ty));
5888 }
5889 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
5890 // If packed val is constant with uniform operands, replace EI
5891 // with that operand
5892 Constant *op0 = cast<Constant>(C->getOperand(0));
5893 for (unsigned i = 1; i < C->getNumOperands(); ++i)
5894 if (C->getOperand(i) != op0) return 0;
5895 return ReplaceInstUsesWith(EI, op0);
5896 }
5897 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
5898 if (I->hasOneUse()) {
5899 // Push extractelement into predecessor operation if legal and
5900 // profitable to do so
5901 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
5902 if (!isa<Constant>(BO->getOperand(0)) &&
5903 !isa<Constant>(BO->getOperand(1)))
5904 return 0;
5905 ExtractElementInst *newEI0 =
5906 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
5907 EI.getName());
5908 ExtractElementInst *newEI1 =
5909 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
5910 EI.getName());
5911 InsertNewInstBefore(newEI0, EI);
5912 InsertNewInstBefore(newEI1, EI);
5913 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
5914 }
5915 switch(I->getOpcode()) {
5916 case Instruction::Load: {
5917 Value *Ptr = InsertCastBefore(I->getOperand(0),
5918 PointerType::get(EI.getType()), EI);
5919 GetElementPtrInst *GEP =
5920 new GetElementPtrInst(Ptr, EI.getOperand(1),
5921 I->getName() + ".gep");
5922 InsertNewInstBefore(GEP, EI);
5923 return new LoadInst(GEP);
5924 }
5925 default:
5926 return 0;
5927 }
5928 }
5929 return 0;
5930}
5931
5932
Chris Lattner99f48c62002-09-02 04:59:56 +00005933void InstCombiner::removeFromWorkList(Instruction *I) {
5934 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5935 WorkList.end());
5936}
5937
Chris Lattner39c98bb2004-12-08 23:43:58 +00005938
5939/// TryToSinkInstruction - Try to move the specified instruction from its
5940/// current block into the beginning of DestBlock, which can only happen if it's
5941/// safe to move the instruction past all of the instructions between it and the
5942/// end of its block.
5943static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5944 assert(I->hasOneUse() && "Invariants didn't hold!");
5945
Chris Lattnerc4f67e62005-10-27 17:13:11 +00005946 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
5947 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005948
Chris Lattner39c98bb2004-12-08 23:43:58 +00005949 // Do not sink alloca instructions out of the entry block.
5950 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5951 return false;
5952
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005953 // We can only sink load instructions if there is nothing between the load and
5954 // the end of block that could change the value.
5955 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005956 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5957 Scan != E; ++Scan)
5958 if (Scan->mayWriteToMemory())
5959 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005960 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00005961
5962 BasicBlock::iterator InsertPos = DestBlock->begin();
5963 while (isa<PHINode>(InsertPos)) ++InsertPos;
5964
Chris Lattner9f269e42005-08-08 19:11:57 +00005965 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00005966 ++NumSunkInst;
5967 return true;
5968}
5969
Chris Lattner113f4f42002-06-25 16:13:24 +00005970bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00005971 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005972 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00005973
Chris Lattner4ed40f72005-07-07 20:40:38 +00005974 {
5975 // Populate the worklist with the reachable instructions.
5976 std::set<BasicBlock*> Visited;
5977 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
5978 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
5979 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
5980 WorkList.push_back(I);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005981
Chris Lattner4ed40f72005-07-07 20:40:38 +00005982 // Do a quick scan over the function. If we find any blocks that are
5983 // unreachable, remove any instructions inside of them. This prevents
5984 // the instcombine code from having to deal with some bad special cases.
5985 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5986 if (!Visited.count(BB)) {
5987 Instruction *Term = BB->getTerminator();
5988 while (Term != BB->begin()) { // Remove instrs bottom-up
5989 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00005990
Chris Lattner4ed40f72005-07-07 20:40:38 +00005991 DEBUG(std::cerr << "IC: DCE: " << *I);
5992 ++NumDeadInst;
5993
5994 if (!I->use_empty())
5995 I->replaceAllUsesWith(UndefValue::get(I->getType()));
5996 I->eraseFromParent();
5997 }
5998 }
5999 }
Chris Lattnerca081252001-12-14 16:52:21 +00006000
6001 while (!WorkList.empty()) {
6002 Instruction *I = WorkList.back(); // Get an instruction from the worklist
6003 WorkList.pop_back();
6004
Misha Brukman632df282002-10-29 23:06:16 +00006005 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00006006 // Check to see if we can DIE the instruction...
6007 if (isInstructionTriviallyDead(I)) {
6008 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006009 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00006010 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00006011 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006012
Chris Lattnercd517ff2005-01-28 19:32:01 +00006013 DEBUG(std::cerr << "IC: DCE: " << *I);
6014
6015 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006016 removeFromWorkList(I);
6017 continue;
6018 }
Chris Lattner99f48c62002-09-02 04:59:56 +00006019
Misha Brukman632df282002-10-29 23:06:16 +00006020 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00006021 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006022 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00006023 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006024 cast<Constant>(Ptr)->isNullValue() &&
6025 !isa<ConstantPointerNull>(C) &&
6026 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00006027 // If this is a constant expr gep that is effectively computing an
6028 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
6029 bool isFoldableGEP = true;
6030 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
6031 if (!isa<ConstantInt>(I->getOperand(i)))
6032 isFoldableGEP = false;
6033 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006034 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00006035 std::vector<Value*>(I->op_begin()+1, I->op_end()));
6036 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00006037 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00006038 C = ConstantExpr::getCast(C, I->getType());
6039 }
6040 }
6041
Chris Lattnercd517ff2005-01-28 19:32:01 +00006042 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
6043
Chris Lattner99f48c62002-09-02 04:59:56 +00006044 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00006045 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00006046 ReplaceInstUsesWith(*I, C);
6047
Chris Lattner99f48c62002-09-02 04:59:56 +00006048 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006049 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00006050 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006051 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00006052 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006053
Chris Lattner39c98bb2004-12-08 23:43:58 +00006054 // See if we can trivially sink this instruction to a successor basic block.
6055 if (I->hasOneUse()) {
6056 BasicBlock *BB = I->getParent();
6057 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
6058 if (UserParent != BB) {
6059 bool UserIsSuccessor = false;
6060 // See if the user is one of our successors.
6061 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6062 if (*SI == UserParent) {
6063 UserIsSuccessor = true;
6064 break;
6065 }
6066
6067 // If the user is one of our immediate successors, and if that successor
6068 // only has us as a predecessors (we'd have to split the critical edge
6069 // otherwise), we can keep going.
6070 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
6071 next(pred_begin(UserParent)) == pred_end(UserParent))
6072 // Okay, the CFG is simple enough, try to sink this instruction.
6073 Changed |= TryToSinkInstruction(I, UserParent);
6074 }
6075 }
6076
Chris Lattnerca081252001-12-14 16:52:21 +00006077 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006078 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00006079 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00006080 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00006081 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00006082 DEBUG(std::cerr << "IC: Old = " << *I
6083 << " New = " << *Result);
6084
Chris Lattner396dbfe2004-06-09 05:08:07 +00006085 // Everything uses the new instruction now.
6086 I->replaceAllUsesWith(Result);
6087
6088 // Push the new instruction and any users onto the worklist.
6089 WorkList.push_back(Result);
6090 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006091
6092 // Move the name to the new instruction first...
6093 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00006094 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006095
6096 // Insert the new instruction into the basic block...
6097 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00006098 BasicBlock::iterator InsertPos = I;
6099
6100 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
6101 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6102 ++InsertPos;
6103
6104 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006105
Chris Lattner63d75af2004-05-01 23:27:23 +00006106 // Make sure that we reprocess all operands now that we reduced their
6107 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00006108 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6109 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6110 WorkList.push_back(OpI);
6111
Chris Lattner396dbfe2004-06-09 05:08:07 +00006112 // Instructions can end up on the worklist more than once. Make sure
6113 // we do not process an instruction that has been deleted.
6114 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006115
6116 // Erase the old instruction.
6117 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00006118 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00006119 DEBUG(std::cerr << "IC: MOD = " << *I);
6120
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006121 // If the instruction was modified, it's possible that it is now dead.
6122 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00006123 if (isInstructionTriviallyDead(I)) {
6124 // Make sure we process all operands now that we are reducing their
6125 // use counts.
6126 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6127 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6128 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006129
Chris Lattner63d75af2004-05-01 23:27:23 +00006130 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00006131 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00006132 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00006133 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00006134 } else {
6135 WorkList.push_back(Result);
6136 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006137 }
Chris Lattner053c0932002-05-14 15:24:07 +00006138 }
Chris Lattner260ab202002-04-18 17:39:14 +00006139 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00006140 }
6141 }
6142
Chris Lattner260ab202002-04-18 17:39:14 +00006143 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00006144}
6145
Brian Gaeke38b79e82004-07-27 17:43:21 +00006146FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00006147 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00006148}
Brian Gaeke960707c2003-11-11 22:41:34 +00006149