blob: 4a764c996d7d54a5d64a2b28cf771ffbb8bea174 [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 Lattner113f4f42002-06-25 16:13:24 +0000122 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000123 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
124 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000125 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000126 Instruction *visitCallInst(CallInst &CI);
127 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000128 Instruction *visitPHINode(PHINode &PN);
129 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000130 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000131 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000132 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000133 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000134 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000135 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000136
137 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000138 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000139
Chris Lattner970c33a2003-06-19 17:00:31 +0000140 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000141 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000142 bool transformConstExprCastCall(CallSite CS);
143
Chris Lattner69193f92004-04-05 01:30:19 +0000144 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000145 // InsertNewInstBefore - insert an instruction New before instruction Old
146 // in the program. Add the new instruction to the worklist.
147 //
Chris Lattner623826c2004-09-28 21:48:02 +0000148 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000149 assert(New && New->getParent() == 0 &&
150 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000151 BasicBlock *BB = Old.getParent();
152 BB->getInstList().insert(&Old, New); // Insert inst
153 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000154 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000155 }
156
Chris Lattner7e794272004-09-24 15:21:34 +0000157 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
158 /// This also adds the cast to the worklist. Finally, this returns the
159 /// cast.
160 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
161 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000162
Chris Lattner7e794272004-09-24 15:21:34 +0000163 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
164 WorkList.push_back(C);
165 return C;
166 }
167
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000168 // ReplaceInstUsesWith - This method is to be used when an instruction is
169 // found to be dead, replacable with another preexisting expression. Here
170 // we add all uses of I to the worklist, replace all uses of I with the new
171 // value, then return I, so that the inst combiner will know that I was
172 // modified.
173 //
174 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000175 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000176 if (&I != V) {
177 I.replaceAllUsesWith(V);
178 return &I;
179 } else {
180 // If we are replacing the instruction with itself, this must be in a
181 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000182 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000183 return &I;
184 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000185 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000186
187 // EraseInstFromFunction - When dealing with an instruction that has side
188 // effects or produces a void value, we can't rely on DCE to delete the
189 // instruction. Instead, visit methods should return the value returned by
190 // this function.
191 Instruction *EraseInstFromFunction(Instruction &I) {
192 assert(I.use_empty() && "Cannot erase instruction that is used!");
193 AddUsesToWorkList(I);
194 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000195 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000196 return 0; // Don't do anything with FI
197 }
198
199
Chris Lattner3ac7c262003-08-13 20:16:26 +0000200 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000201 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
202 /// InsertBefore instruction. This is specialized a bit to avoid inserting
203 /// casts that are known to not do anything...
204 ///
205 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
206 Instruction *InsertBefore);
207
Chris Lattner7fb29e12003-03-11 00:12:48 +0000208 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000209 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000210 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000211
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000212
213 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
214 // PHI node as operand #0, see if we can fold the instruction into the PHI
215 // (which is only possible if all operands to the PHI are constants).
216 Instruction *FoldOpIntoPhi(Instruction &I);
217
Chris Lattner7515cab2004-11-14 19:13:23 +0000218 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
219 // operator and they all are only used by the PHI, PHI together their
220 // inputs, and do the operation once, to the result of the PHI.
221 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
222
Chris Lattnerba1cb382003-09-19 17:17:26 +0000223 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
224 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000225
226 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
227 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000228 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
229 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000230 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattner260ab202002-04-18 17:39:14 +0000231 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000232
Chris Lattnerc8b70922002-07-26 21:12:46 +0000233 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000234}
235
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000236// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000237// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000238static unsigned getComplexity(Value *V) {
239 if (isa<Instruction>(V)) {
240 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000241 return 3;
242 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000243 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000244 if (isa<Argument>(V)) return 3;
245 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000246}
Chris Lattner260ab202002-04-18 17:39:14 +0000247
Chris Lattner7fb29e12003-03-11 00:12:48 +0000248// isOnlyUse - Return true if this instruction will be deleted if we stop using
249// it.
250static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000251 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000252}
253
Chris Lattnere79e8542004-02-23 06:38:22 +0000254// getPromotedType - Return the specified type promoted as it would be to pass
255// though a va_arg area...
256static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000257 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000258 case Type::SByteTyID:
259 case Type::ShortTyID: return Type::IntTy;
260 case Type::UByteTyID:
261 case Type::UShortTyID: return Type::UIntTy;
262 case Type::FloatTyID: return Type::DoubleTy;
263 default: return Ty;
264 }
265}
266
Chris Lattner567b81f2005-09-13 00:40:14 +0000267/// isCast - If the specified operand is a CastInst or a constant expr cast,
268/// return the operand value, otherwise return null.
269static Value *isCast(Value *V) {
270 if (CastInst *I = dyn_cast<CastInst>(V))
271 return I->getOperand(0);
272 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
273 if (CE->getOpcode() == Instruction::Cast)
274 return CE->getOperand(0);
275 return 0;
276}
277
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000278// SimplifyCommutative - This performs a few simplifications for commutative
279// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000280//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000281// 1. Order operands such that they are listed from right (least complex) to
282// left (most complex). This puts constants before unary operators before
283// binary operators.
284//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000285// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
286// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000287//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000288bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000289 bool Changed = false;
290 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
291 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000292
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000293 if (!I.isAssociative()) return Changed;
294 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000295 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
296 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
297 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000298 Constant *Folded = ConstantExpr::get(I.getOpcode(),
299 cast<Constant>(I.getOperand(1)),
300 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000301 I.setOperand(0, Op->getOperand(0));
302 I.setOperand(1, Folded);
303 return true;
304 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
305 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
306 isOnlyUse(Op) && isOnlyUse(Op1)) {
307 Constant *C1 = cast<Constant>(Op->getOperand(1));
308 Constant *C2 = cast<Constant>(Op1->getOperand(1));
309
310 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000311 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000312 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
313 Op1->getOperand(0),
314 Op1->getName(), &I);
315 WorkList.push_back(New);
316 I.setOperand(0, New);
317 I.setOperand(1, Folded);
318 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000319 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000320 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000321 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000322}
Chris Lattnerca081252001-12-14 16:52:21 +0000323
Chris Lattnerbb74e222003-03-10 23:06:50 +0000324// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
325// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000326//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000327static inline Value *dyn_castNegVal(Value *V) {
328 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000329 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000330
Chris Lattner9ad0d552004-12-14 20:08:06 +0000331 // Constants can be considered to be negated values if they can be folded.
332 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
333 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000334 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000335}
336
Chris Lattnerbb74e222003-03-10 23:06:50 +0000337static inline Value *dyn_castNotVal(Value *V) {
338 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000339 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000340
341 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000342 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000343 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000344 return 0;
345}
346
Chris Lattner7fb29e12003-03-11 00:12:48 +0000347// dyn_castFoldableMul - If this value is a multiply that can be folded into
348// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000349// non-constant operand of the multiply, and set CST to point to the multiplier.
350// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000351//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000352static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000353 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000354 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000355 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000356 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000357 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000358 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000359 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000360 // The multiplier is really 1 << CST.
361 Constant *One = ConstantInt::get(V->getType(), 1);
362 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
363 return I->getOperand(0);
364 }
365 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000366 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000367}
Chris Lattner31ae8632002-08-14 17:51:49 +0000368
Chris Lattner0798af32005-01-13 20:14:25 +0000369/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
370/// expression, return it.
371static User *dyn_castGetElementPtr(Value *V) {
372 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
373 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
374 if (CE->getOpcode() == Instruction::GetElementPtr)
375 return cast<User>(V);
376 return false;
377}
378
Chris Lattner623826c2004-09-28 21:48:02 +0000379// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000380static ConstantInt *AddOne(ConstantInt *C) {
381 return cast<ConstantInt>(ConstantExpr::getAdd(C,
382 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000383}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000384static ConstantInt *SubOne(ConstantInt *C) {
385 return cast<ConstantInt>(ConstantExpr::getSub(C,
386 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000387}
388
Chris Lattner0b3557f2005-09-24 23:43:33 +0000389/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
390/// this predicate to simplify operations downstream. V and Mask are known to
391/// be the same type.
Chris Lattner09efd4e2005-10-31 18:35:52 +0000392static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask,
393 unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000394 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
395 // we cannot optimize based on the assumption that it is zero without changing
396 // to to an explicit zero. If we don't change it to zero, other code could
397 // optimized based on the contradictory assumption that it is non-zero.
398 // Because instcombine aggressively folds operations with undef args anyway,
399 // this won't lose us code quality.
400 if (Mask->isNullValue())
401 return true;
402 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
403 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
Chris Lattner09efd4e2005-10-31 18:35:52 +0000404
405 if (Depth == 6) return false; // Limit search depth.
Chris Lattner0b3557f2005-09-24 23:43:33 +0000406
407 if (Instruction *I = dyn_cast<Instruction>(V)) {
408 switch (I->getOpcode()) {
Chris Lattner62010c42005-10-09 06:36:35 +0000409 case Instruction::And:
410 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
Chris Lattner03b9eb52005-10-09 22:08:50 +0000411 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1))) {
412 ConstantIntegral *C1C2 =
413 cast<ConstantIntegral>(ConstantExpr::getAnd(CI, Mask));
Chris Lattner09efd4e2005-10-31 18:35:52 +0000414 if (MaskedValueIsZero(I->getOperand(0), C1C2, Depth+1))
Chris Lattner62010c42005-10-09 06:36:35 +0000415 return true;
Chris Lattner03b9eb52005-10-09 22:08:50 +0000416 }
417 // If either the LHS or the RHS are MaskedValueIsZero, the result is zero.
Chris Lattner09efd4e2005-10-31 18:35:52 +0000418 return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) ||
419 MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000420 case Instruction::Or:
Chris Lattner03b9eb52005-10-09 22:08:50 +0000421 case Instruction::Xor:
Chris Lattner62010c42005-10-09 06:36:35 +0000422 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
Chris Lattner09efd4e2005-10-31 18:35:52 +0000423 return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) &&
424 MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000425 case Instruction::Select:
426 // If the T and F values are MaskedValueIsZero, the result is also zero.
Chris Lattner09efd4e2005-10-31 18:35:52 +0000427 return MaskedValueIsZero(I->getOperand(2), Mask, Depth+1) &&
428 MaskedValueIsZero(I->getOperand(1), Mask, Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000429 case Instruction::Cast: {
430 const Type *SrcTy = I->getOperand(0)->getType();
431 if (SrcTy == Type::BoolTy)
432 return (Mask->getRawValue() & 1) == 0;
433
434 if (SrcTy->isInteger()) {
435 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
436 if (SrcTy->isUnsigned() && // Only handle zero ext.
437 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
438 return true;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000439
Chris Lattner62010c42005-10-09 06:36:35 +0000440 // If this is a noop cast, recurse.
441 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() == I->getType())||
442 SrcTy->getSignedVersion() == I->getType()) {
443 Constant *NewMask =
444 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +0000445 return MaskedValueIsZero(I->getOperand(0),
Chris Lattner09efd4e2005-10-31 18:35:52 +0000446 cast<ConstantIntegral>(NewMask), Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000447 }
448 }
449 break;
450 }
451 case Instruction::Shl:
452 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
453 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
454 return MaskedValueIsZero(I->getOperand(0),
Chris Lattner09efd4e2005-10-31 18:35:52 +0000455 cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)),
456 Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000457 break;
458 case Instruction::Shr:
459 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
460 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
461 if (I->getType()->isUnsigned()) {
462 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
463 C1 = ConstantExpr::getShr(C1, SA);
464 C1 = ConstantExpr::getAnd(C1, Mask);
465 if (C1->isNullValue())
466 return true;
467 }
468 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000469 }
470 }
471
472 return false;
473}
474
Chris Lattner623826c2004-09-28 21:48:02 +0000475// isTrueWhenEqual - Return true if the specified setcondinst instruction is
476// true when both operands are equal...
477//
478static bool isTrueWhenEqual(Instruction &I) {
479 return I.getOpcode() == Instruction::SetEQ ||
480 I.getOpcode() == Instruction::SetGE ||
481 I.getOpcode() == Instruction::SetLE;
482}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000483
484/// AssociativeOpt - Perform an optimization on an associative operator. This
485/// function is designed to check a chain of associative operators for a
486/// potential to apply a certain optimization. Since the optimization may be
487/// applicable if the expression was reassociated, this checks the chain, then
488/// reassociates the expression as necessary to expose the optimization
489/// opportunity. This makes use of a special Functor, which must define
490/// 'shouldApply' and 'apply' methods.
491///
492template<typename Functor>
493Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
494 unsigned Opcode = Root.getOpcode();
495 Value *LHS = Root.getOperand(0);
496
497 // Quick check, see if the immediate LHS matches...
498 if (F.shouldApply(LHS))
499 return F.apply(Root);
500
501 // Otherwise, if the LHS is not of the same opcode as the root, return.
502 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000503 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000504 // Should we apply this transform to the RHS?
505 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
506
507 // If not to the RHS, check to see if we should apply to the LHS...
508 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
509 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
510 ShouldApply = true;
511 }
512
513 // If the functor wants to apply the optimization to the RHS of LHSI,
514 // reassociate the expression from ((? op A) op B) to (? op (A op B))
515 if (ShouldApply) {
516 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000517
Chris Lattnerb8b97502003-08-13 19:01:45 +0000518 // Now all of the instructions are in the current basic block, go ahead
519 // and perform the reassociation.
520 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
521
522 // First move the selected RHS to the LHS of the root...
523 Root.setOperand(0, LHSI->getOperand(1));
524
525 // Make what used to be the LHS of the root be the user of the root...
526 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000527 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000528 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
529 return 0;
530 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000531 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000532 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000533 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
534 BasicBlock::iterator ARI = &Root; ++ARI;
535 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
536 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000537
538 // Now propagate the ExtraOperand down the chain of instructions until we
539 // get to LHSI.
540 while (TmpLHSI != LHSI) {
541 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000542 // Move the instruction to immediately before the chain we are
543 // constructing to avoid breaking dominance properties.
544 NextLHSI->getParent()->getInstList().remove(NextLHSI);
545 BB->getInstList().insert(ARI, NextLHSI);
546 ARI = NextLHSI;
547
Chris Lattnerb8b97502003-08-13 19:01:45 +0000548 Value *NextOp = NextLHSI->getOperand(1);
549 NextLHSI->setOperand(1, ExtraOperand);
550 TmpLHSI = NextLHSI;
551 ExtraOperand = NextOp;
552 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000553
Chris Lattnerb8b97502003-08-13 19:01:45 +0000554 // Now that the instructions are reassociated, have the functor perform
555 // the transformation...
556 return F.apply(Root);
557 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000558
Chris Lattnerb8b97502003-08-13 19:01:45 +0000559 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
560 }
561 return 0;
562}
563
564
565// AddRHS - Implements: X + X --> X << 1
566struct AddRHS {
567 Value *RHS;
568 AddRHS(Value *rhs) : RHS(rhs) {}
569 bool shouldApply(Value *LHS) const { return LHS == RHS; }
570 Instruction *apply(BinaryOperator &Add) const {
571 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
572 ConstantInt::get(Type::UByteTy, 1));
573 }
574};
575
576// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
577// iff C1&C2 == 0
578struct AddMaskingAnd {
579 Constant *C2;
580 AddMaskingAnd(Constant *c) : C2(c) {}
581 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000582 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000583 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +0000584 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000585 }
586 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000587 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000588 }
589};
590
Chris Lattner86102b82005-01-01 16:22:27 +0000591static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000592 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +0000593 if (isa<CastInst>(I)) {
594 if (Constant *SOC = dyn_cast<Constant>(SO))
595 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000596
Chris Lattner86102b82005-01-01 16:22:27 +0000597 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
598 SO->getName() + ".cast"), I);
599 }
600
Chris Lattner183b3362004-04-09 19:05:30 +0000601 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000602 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
603 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000604
Chris Lattner183b3362004-04-09 19:05:30 +0000605 if (Constant *SOC = dyn_cast<Constant>(SO)) {
606 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +0000607 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
608 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000609 }
610
611 Value *Op0 = SO, *Op1 = ConstOperand;
612 if (!ConstIsRHS)
613 std::swap(Op0, Op1);
614 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +0000615 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
616 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
617 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
618 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000619 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000620 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000621 abort();
622 }
Chris Lattner86102b82005-01-01 16:22:27 +0000623 return IC->InsertNewInstBefore(New, I);
624}
625
626// FoldOpIntoSelect - Given an instruction with a select as one operand and a
627// constant as the other operand, try to fold the binary operator into the
628// select arguments. This also works for Cast instructions, which obviously do
629// not have a second operand.
630static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
631 InstCombiner *IC) {
632 // Don't modify shared select instructions
633 if (!SI->hasOneUse()) return 0;
634 Value *TV = SI->getOperand(1);
635 Value *FV = SI->getOperand(2);
636
637 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +0000638 // Bool selects with constant operands can be folded to logical ops.
639 if (SI->getType() == Type::BoolTy) return 0;
640
Chris Lattner86102b82005-01-01 16:22:27 +0000641 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
642 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
643
644 return new SelectInst(SI->getCondition(), SelectTrueVal,
645 SelectFalseVal);
646 }
647 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +0000648}
649
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000650
651/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
652/// node as operand #0, see if we can fold the instruction into the PHI (which
653/// is only possible if all operands to the PHI are constants).
654Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
655 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000656 unsigned NumPHIValues = PN->getNumIncomingValues();
657 if (!PN->hasOneUse() || NumPHIValues == 0 ||
658 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000659
660 // Check to see if all of the operands of the PHI are constants. If not, we
661 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000662 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000663 if (!isa<Constant>(PN->getIncomingValue(i)))
664 return 0;
665
666 // Okay, we can do the transformation: create the new PHI node.
667 PHINode *NewPN = new PHINode(I.getType(), I.getName());
668 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +0000669 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000670 InsertNewInstBefore(NewPN, *PN);
671
672 // Next, add all of the operands to the PHI.
673 if (I.getNumOperands() == 2) {
674 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000675 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000676 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
677 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
678 PN->getIncomingBlock(i));
679 }
680 } else {
681 assert(isa<CastInst>(I) && "Unary op should be a cast!");
682 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000683 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000684 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
685 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
686 PN->getIncomingBlock(i));
687 }
688 }
689 return ReplaceInstUsesWith(I, NewPN);
690}
691
Chris Lattner113f4f42002-06-25 16:13:24 +0000692Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000693 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000694 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000695
Chris Lattnercf4a9962004-04-10 22:01:55 +0000696 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000697 // X + undef -> undef
698 if (isa<UndefValue>(RHS))
699 return ReplaceInstUsesWith(I, RHS);
700
Chris Lattnercf4a9962004-04-10 22:01:55 +0000701 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +0000702 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
703 if (RHSC->isNullValue())
704 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +0000705 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
706 if (CFP->isExactlyValue(-0.0))
707 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +0000708 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000709
Chris Lattnercf4a9962004-04-10 22:01:55 +0000710 // X + (signbit) --> X ^ signbit
711 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000712 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Andrew Lenharth66229552005-11-02 18:35:40 +0000713 uint64_t Val = CI->getRawValue() & (~0ULL >> (64- NumBits));
Chris Lattner33eb9092004-11-05 04:45:43 +0000714 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000715 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000716 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000717
718 if (isa<PHINode>(LHS))
719 if (Instruction *NV = FoldOpIntoPhi(I))
720 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000721
722 ConstantInt *XorRHS;
723 Value *XorLHS;
724 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
725 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
726 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
727 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
728
729 uint64_t C0080Val = 1ULL << 31;
730 int64_t CFF80Val = -C0080Val;
731 unsigned Size = 32;
732 do {
733 if (TySizeBits > Size) {
734 bool Found = false;
735 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
736 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
737 if (RHSSExt == CFF80Val) {
738 if (XorRHS->getZExtValue() == C0080Val)
739 Found = true;
740 } else if (RHSZExt == C0080Val) {
741 if (XorRHS->getSExtValue() == CFF80Val)
742 Found = true;
743 }
744 if (Found) {
745 // This is a sign extend if the top bits are known zero.
746 Constant *Mask = ConstantInt::getAllOnesValue(XorLHS->getType());
747 Mask = ConstantExpr::getShl(Mask,
748 ConstantInt::get(Type::UByteTy, 64-TySizeBits-Size));
749 if (!MaskedValueIsZero(XorLHS, cast<ConstantInt>(Mask)))
750 Size = 0; // Not a sign ext, but can't be any others either.
751 goto FoundSExt;
752 }
753 }
754 Size >>= 1;
755 C0080Val >>= Size;
756 CFF80Val >>= Size;
757 } while (Size >= 8);
758
759FoundSExt:
760 const Type *MiddleType = 0;
761 switch (Size) {
762 default: break;
763 case 32: MiddleType = Type::IntTy; break;
764 case 16: MiddleType = Type::ShortTy; break;
765 case 8: MiddleType = Type::SByteTy; break;
766 }
767 if (MiddleType) {
768 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
769 InsertNewInstBefore(NewTrunc, I);
770 return new CastInst(NewTrunc, I.getType());
771 }
772 }
Chris Lattnercf4a9962004-04-10 22:01:55 +0000773 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000774
Chris Lattnerb8b97502003-08-13 19:01:45 +0000775 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000776 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000777 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +0000778
779 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
780 if (RHSI->getOpcode() == Instruction::Sub)
781 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
782 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
783 }
784 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
785 if (LHSI->getOpcode() == Instruction::Sub)
786 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
787 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
788 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000789 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000790
Chris Lattner147e9752002-05-08 22:46:53 +0000791 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000792 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000793 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000794
795 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000796 if (!isa<Constant>(RHS))
797 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000798 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000799
Misha Brukmanb1c93172005-04-21 23:48:37 +0000800
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000801 ConstantInt *C2;
802 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
803 if (X == RHS) // X*C + X --> X * (C+1)
804 return BinaryOperator::createMul(RHS, AddOne(C2));
805
806 // X*C1 + X*C2 --> X * (C1+C2)
807 ConstantInt *C1;
808 if (X == dyn_castFoldableMul(RHS, C1))
809 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000810 }
811
812 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000813 if (dyn_castFoldableMul(RHS, C2) == LHS)
814 return BinaryOperator::createMul(LHS, AddOne(C2));
815
Chris Lattner57c8d992003-02-18 19:57:07 +0000816
Chris Lattnerb8b97502003-08-13 19:01:45 +0000817 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000818 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000819 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000820
Chris Lattnerb9cde762003-10-02 15:11:26 +0000821 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000822 Value *X;
823 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
824 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
825 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000826 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000827
Chris Lattnerbff91d92004-10-08 05:07:56 +0000828 // (X & FF00) + xx00 -> (X+xx00) & FF00
829 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
830 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
831 if (Anded == CRHS) {
832 // See if all bits from the first bit set in the Add RHS up are included
833 // in the mask. First, get the rightmost bit.
834 uint64_t AddRHSV = CRHS->getRawValue();
835
836 // Form a mask of all bits from the lowest bit added through the top.
837 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner2f1457f2005-04-24 17:46:05 +0000838 AddRHSHighBits &= ~0ULL >> (64-C2->getType()->getPrimitiveSizeInBits());
Chris Lattnerbff91d92004-10-08 05:07:56 +0000839
840 // See if the and mask includes all of these bits.
841 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000842
Chris Lattnerbff91d92004-10-08 05:07:56 +0000843 if (AddRHSHighBits == AddRHSHighBitsAnd) {
844 // Okay, the xform is safe. Insert the new add pronto.
845 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
846 LHS->getName()), I);
847 return BinaryOperator::createAnd(NewAdd, C2);
848 }
849 }
850 }
851
Chris Lattnerd4252a72004-07-30 07:50:03 +0000852 // Try to fold constant add into select arguments.
853 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +0000854 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +0000855 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000856 }
857
Chris Lattner113f4f42002-06-25 16:13:24 +0000858 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000859}
860
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000861// isSignBit - Return true if the value represented by the constant only has the
862// highest order bit set.
863static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000864 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +0000865 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000866}
867
Chris Lattner022167f2004-03-13 00:11:49 +0000868/// RemoveNoopCast - Strip off nonconverting casts from the value.
869///
870static Value *RemoveNoopCast(Value *V) {
871 if (CastInst *CI = dyn_cast<CastInst>(V)) {
872 const Type *CTy = CI->getType();
873 const Type *OpTy = CI->getOperand(0)->getType();
874 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000875 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +0000876 return RemoveNoopCast(CI->getOperand(0));
877 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
878 return RemoveNoopCast(CI->getOperand(0));
879 }
880 return V;
881}
882
Chris Lattner113f4f42002-06-25 16:13:24 +0000883Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000884 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000885
Chris Lattnere6794492002-08-12 21:17:25 +0000886 if (Op0 == Op1) // sub X, X -> 0
887 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000888
Chris Lattnere6794492002-08-12 21:17:25 +0000889 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000890 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000891 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000892
Chris Lattner81a7a232004-10-16 18:11:37 +0000893 if (isa<UndefValue>(Op0))
894 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
895 if (isa<UndefValue>(Op1))
896 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
897
Chris Lattner8f2f5982003-11-05 01:06:05 +0000898 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
899 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000900 if (C->isAllOnesValue())
901 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000902
Chris Lattner8f2f5982003-11-05 01:06:05 +0000903 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +0000904 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +0000905 if (match(Op1, m_Not(m_Value(X))))
906 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000907 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000908 // -((uint)X >> 31) -> ((int)X >> 31)
909 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000910 if (C->isNullValue()) {
911 Value *NoopCastedRHS = RemoveNoopCast(Op1);
912 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000913 if (SI->getOpcode() == Instruction::Shr)
914 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
915 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000916 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000917 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000918 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000919 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000920 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000921 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000922 // Ok, the transformation is safe. Insert a cast of the incoming
923 // value, then the new shift, then the new cast.
924 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
925 SI->getOperand(0)->getName());
926 Value *InV = InsertNewInstBefore(FirstCast, I);
927 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
928 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000929 if (NewShift->getType() == I.getType())
930 return NewShift;
931 else {
932 InV = InsertNewInstBefore(NewShift, I);
933 return new CastInst(NewShift, I.getType());
934 }
Chris Lattner92295c52004-03-12 23:53:13 +0000935 }
936 }
Chris Lattner022167f2004-03-13 00:11:49 +0000937 }
Chris Lattner183b3362004-04-09 19:05:30 +0000938
939 // Try to fold constant sub into select arguments.
940 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +0000941 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000942 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000943
944 if (isa<PHINode>(Op0))
945 if (Instruction *NV = FoldOpIntoPhi(I))
946 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000947 }
948
Chris Lattnera9be4492005-04-07 16:15:25 +0000949 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
950 if (Op1I->getOpcode() == Instruction::Add &&
951 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000952 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000953 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000954 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000955 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000956 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
957 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
958 // C1-(X+C2) --> (C1-C2)-X
959 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
960 Op1I->getOperand(0));
961 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000962 }
963
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000964 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000965 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
966 // is not used by anyone else...
967 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000968 if (Op1I->getOpcode() == Instruction::Sub &&
969 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000970 // Swap the two operands of the subexpr...
971 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
972 Op1I->setOperand(0, IIOp1);
973 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000974
Chris Lattner3082c5a2003-02-18 19:28:33 +0000975 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000976 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000977 }
978
979 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
980 //
981 if (Op1I->getOpcode() == Instruction::And &&
982 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
983 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
984
Chris Lattner396dbfe2004-06-09 05:08:07 +0000985 Value *NewNot =
986 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000987 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000988 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000989
Chris Lattner0aee4b72004-10-06 15:08:25 +0000990 // -(X sdiv C) -> (X sdiv -C)
991 if (Op1I->getOpcode() == Instruction::Div)
992 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +0000993 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +0000994 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +0000995 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +0000996 ConstantExpr::getNeg(DivRHS));
997
Chris Lattner57c8d992003-02-18 19:57:07 +0000998 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +0000999 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001000 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001001 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001002 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001003 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001004 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001005 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001006 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001007
Chris Lattner47060462005-04-07 17:14:51 +00001008 if (!Op0->getType()->isFloatingPoint())
1009 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1010 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001011 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1012 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1013 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1014 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001015 } else if (Op0I->getOpcode() == Instruction::Sub) {
1016 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1017 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001018 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001019
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001020 ConstantInt *C1;
1021 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1022 if (X == Op1) { // X*C - X --> X * (C-1)
1023 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1024 return BinaryOperator::createMul(Op1, CP1);
1025 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001026
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001027 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1028 if (X == dyn_castFoldableMul(Op1, C2))
1029 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1030 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001031 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001032}
1033
Chris Lattnere79e8542004-02-23 06:38:22 +00001034/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1035/// really just returns true if the most significant (sign) bit is set.
1036static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1037 if (RHS->getType()->isSigned()) {
1038 // True if source is LHS < 0 or LHS <= -1
1039 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1040 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1041 } else {
1042 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1043 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1044 // the size of the integer type.
1045 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001046 return RHSC->getValue() ==
1047 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001048 if (Opcode == Instruction::SetGT)
1049 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001050 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001051 }
1052 return false;
1053}
1054
Chris Lattner113f4f42002-06-25 16:13:24 +00001055Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001056 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001057 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001058
Chris Lattner81a7a232004-10-16 18:11:37 +00001059 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1060 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1061
Chris Lattnere6794492002-08-12 21:17:25 +00001062 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001063 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1064 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001065
1066 // ((X << C1)*C2) == (X * (C2 << C1))
1067 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1068 if (SI->getOpcode() == Instruction::Shl)
1069 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001070 return BinaryOperator::createMul(SI->getOperand(0),
1071 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001072
Chris Lattnercce81be2003-09-11 22:24:54 +00001073 if (CI->isNullValue())
1074 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1075 if (CI->equalsInt(1)) // X * 1 == X
1076 return ReplaceInstUsesWith(I, Op0);
1077 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001078 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001079
Chris Lattnercce81be2003-09-11 22:24:54 +00001080 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001081 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1082 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001083 return new ShiftInst(Instruction::Shl, Op0,
1084 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001085 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001086 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001087 if (Op1F->isNullValue())
1088 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001089
Chris Lattner3082c5a2003-02-18 19:28:33 +00001090 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1091 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1092 if (Op1F->getValue() == 1.0)
1093 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1094 }
Chris Lattner183b3362004-04-09 19:05:30 +00001095
1096 // Try to fold constant mul into select arguments.
1097 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001098 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001099 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001100
1101 if (isa<PHINode>(Op0))
1102 if (Instruction *NV = FoldOpIntoPhi(I))
1103 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001104 }
1105
Chris Lattner934a64cf2003-03-10 23:23:04 +00001106 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1107 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001108 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001109
Chris Lattner2635b522004-02-23 05:39:21 +00001110 // If one of the operands of the multiply is a cast from a boolean value, then
1111 // we know the bool is either zero or one, so this is a 'masking' multiply.
1112 // See if we can simplify things based on how the boolean was originally
1113 // formed.
1114 CastInst *BoolCast = 0;
1115 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1116 if (CI->getOperand(0)->getType() == Type::BoolTy)
1117 BoolCast = CI;
1118 if (!BoolCast)
1119 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1120 if (CI->getOperand(0)->getType() == Type::BoolTy)
1121 BoolCast = CI;
1122 if (BoolCast) {
1123 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1124 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1125 const Type *SCOpTy = SCIOp0->getType();
1126
Chris Lattnere79e8542004-02-23 06:38:22 +00001127 // If the setcc is true iff the sign bit of X is set, then convert this
1128 // multiply into a shift/and combination.
1129 if (isa<ConstantInt>(SCIOp1) &&
1130 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001131 // Shift the X value right to turn it into "all signbits".
1132 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001133 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001134 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001135 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001136 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1137 SCIOp0->getName()), I);
1138 }
1139
1140 Value *V =
1141 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1142 BoolCast->getOperand(0)->getName()+
1143 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001144
1145 // If the multiply type is not the same as the source type, sign extend
1146 // or truncate to the multiply type.
1147 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001148 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001149
Chris Lattner2635b522004-02-23 05:39:21 +00001150 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001151 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001152 }
1153 }
1154 }
1155
Chris Lattner113f4f42002-06-25 16:13:24 +00001156 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001157}
1158
Chris Lattner113f4f42002-06-25 16:13:24 +00001159Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001160 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001161
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001162 if (isa<UndefValue>(Op0)) // undef / X -> 0
1163 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1164 if (isa<UndefValue>(Op1))
1165 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1166
1167 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001168 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001169 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001170 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001171
Chris Lattnere20c3342004-04-26 14:01:59 +00001172 // div X, -1 == -X
1173 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001174 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001175
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001176 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001177 if (LHS->getOpcode() == Instruction::Div)
1178 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001179 // (X / C1) / C2 -> X / (C1*C2)
1180 return BinaryOperator::createDiv(LHS->getOperand(0),
1181 ConstantExpr::getMul(RHS, LHSRHS));
1182 }
1183
Chris Lattner3082c5a2003-02-18 19:28:33 +00001184 // Check to see if this is an unsigned division with an exact power of 2,
1185 // if so, convert to a right shift.
1186 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1187 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001188 if (isPowerOf2_64(Val)) {
1189 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001190 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001191 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001192 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001193
Chris Lattner4ad08352004-10-09 02:50:40 +00001194 // -X/C -> X/-C
1195 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001196 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001197 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1198
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001199 if (!RHS->isNullValue()) {
1200 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001201 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001202 return R;
1203 if (isa<PHINode>(Op0))
1204 if (Instruction *NV = FoldOpIntoPhi(I))
1205 return NV;
1206 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001207 }
1208
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001209 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1210 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1211 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1212 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1213 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1214 if (STO->getValue() == 0) { // Couldn't be this argument.
1215 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001216 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001217 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001218 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001219 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001220 }
1221
Chris Lattner42362612005-04-08 04:03:26 +00001222 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001223 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1224 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001225 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1226 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1227 TC, SI->getName()+".t");
1228 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001229
Chris Lattner42362612005-04-08 04:03:26 +00001230 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1231 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1232 FC, SI->getName()+".f");
1233 FSI = InsertNewInstBefore(FSI, I);
1234 return new SelectInst(SI->getOperand(0), TSI, FSI);
1235 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001236 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001237
Chris Lattner3082c5a2003-02-18 19:28:33 +00001238 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001239 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001240 if (LHS->equalsInt(0))
1241 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1242
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001243 return 0;
1244}
1245
1246
Chris Lattner113f4f42002-06-25 16:13:24 +00001247Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001248 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001249 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001250 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001251 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001252 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001253 // X % -Y -> X % Y
1254 AddUsesToWorkList(I);
1255 I.setOperand(1, RHSNeg);
1256 return &I;
1257 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001258
1259 // If the top bits of both operands are zero (i.e. we can prove they are
1260 // unsigned inputs), turn this into a urem.
1261 ConstantIntegral *MaskV = ConstantSInt::getMinValue(I.getType());
1262 if (MaskedValueIsZero(Op1, MaskV) && MaskedValueIsZero(Op0, MaskV)) {
1263 const Type *NTy = Op0->getType()->getUnsignedVersion();
1264 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1265 InsertNewInstBefore(LHS, I);
1266 Value *RHS;
1267 if (Constant *R = dyn_cast<Constant>(Op1))
1268 RHS = ConstantExpr::getCast(R, NTy);
1269 else
1270 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1271 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1272 InsertNewInstBefore(Rem, I);
1273 return new CastInst(Rem, I.getType());
1274 }
1275 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00001276
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001277 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001278 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001279 if (isa<UndefValue>(Op1))
1280 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001281
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001282 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001283 if (RHS->equalsInt(1)) // X % 1 == 0
1284 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1285
1286 // Check to see if this is an unsigned remainder with an exact power of 2,
1287 // if so, convert to a bitwise and.
1288 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1289 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001290 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001291 return BinaryOperator::createAnd(Op0,
1292 ConstantUInt::get(I.getType(), Val-1));
1293
1294 if (!RHS->isNullValue()) {
1295 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001296 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001297 return R;
1298 if (isa<PHINode>(Op0))
1299 if (Instruction *NV = FoldOpIntoPhi(I))
1300 return NV;
1301 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001302 }
1303
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001304 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1305 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1306 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1307 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1308 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1309 if (STO->getValue() == 0) { // Couldn't be this argument.
1310 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001311 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001312 } else if (SFO->getValue() == 0) {
1313 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001314 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001315 }
1316
1317 if (!(STO->getValue() & (STO->getValue()-1)) &&
1318 !(SFO->getValue() & (SFO->getValue()-1))) {
1319 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1320 SubOne(STO), SI->getName()+".t"), I);
1321 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1322 SubOne(SFO), SI->getName()+".f"), I);
1323 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1324 }
1325 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001326
Chris Lattner3082c5a2003-02-18 19:28:33 +00001327 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001328 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001329 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001330 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1331
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001332 return 0;
1333}
1334
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001335// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001336static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001337 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1338 // Calculate -1 casted to the right type...
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001339 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001340 uint64_t Val = ~0ULL; // All ones
1341 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1342 return CU->getValue() == Val-1;
1343 }
1344
1345 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001346
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001347 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001348 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001349 int64_t Val = INT64_MAX; // All ones
1350 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1351 return CS->getValue() == Val-1;
1352}
1353
1354// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001355static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001356 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1357 return CU->getValue() == 1;
1358
1359 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001360
1361 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001362 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001363 int64_t Val = -1; // All ones
1364 Val <<= TypeBits-1; // Shift over to the right spot
1365 return CS->getValue() == Val+1;
1366}
1367
Chris Lattner35167c32004-06-09 07:59:58 +00001368// isOneBitSet - Return true if there is exactly one bit set in the specified
1369// constant.
1370static bool isOneBitSet(const ConstantInt *CI) {
1371 uint64_t V = CI->getRawValue();
1372 return V && (V & (V-1)) == 0;
1373}
1374
Chris Lattner8fc5af42004-09-23 21:46:38 +00001375#if 0 // Currently unused
1376// isLowOnes - Return true if the constant is of the form 0+1+.
1377static bool isLowOnes(const ConstantInt *CI) {
1378 uint64_t V = CI->getRawValue();
1379
1380 // There won't be bits set in parts that the type doesn't contain.
1381 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1382
1383 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1384 return U && V && (U & V) == 0;
1385}
1386#endif
1387
1388// isHighOnes - Return true if the constant is of the form 1+0+.
1389// This is the same as lowones(~X).
1390static bool isHighOnes(const ConstantInt *CI) {
1391 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00001392 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00001393
1394 // There won't be bits set in parts that the type doesn't contain.
1395 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1396
1397 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1398 return U && V && (U & V) == 0;
1399}
1400
1401
Chris Lattner3ac7c262003-08-13 20:16:26 +00001402/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1403/// are carefully arranged to allow folding of expressions such as:
1404///
1405/// (A < B) | (A > B) --> (A != B)
1406///
1407/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1408/// represents that the comparison is true if A == B, and bit value '1' is true
1409/// if A < B.
1410///
1411static unsigned getSetCondCode(const SetCondInst *SCI) {
1412 switch (SCI->getOpcode()) {
1413 // False -> 0
1414 case Instruction::SetGT: return 1;
1415 case Instruction::SetEQ: return 2;
1416 case Instruction::SetGE: return 3;
1417 case Instruction::SetLT: return 4;
1418 case Instruction::SetNE: return 5;
1419 case Instruction::SetLE: return 6;
1420 // True -> 7
1421 default:
1422 assert(0 && "Invalid SetCC opcode!");
1423 return 0;
1424 }
1425}
1426
1427/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1428/// opcode and two operands into either a constant true or false, or a brand new
1429/// SetCC instruction.
1430static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1431 switch (Opcode) {
1432 case 0: return ConstantBool::False;
1433 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1434 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1435 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1436 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1437 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1438 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1439 case 7: return ConstantBool::True;
1440 default: assert(0 && "Illegal SetCCCode!"); return 0;
1441 }
1442}
1443
1444// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1445struct FoldSetCCLogical {
1446 InstCombiner &IC;
1447 Value *LHS, *RHS;
1448 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1449 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1450 bool shouldApply(Value *V) const {
1451 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1452 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1453 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1454 return false;
1455 }
1456 Instruction *apply(BinaryOperator &Log) const {
1457 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1458 if (SCI->getOperand(0) != LHS) {
1459 assert(SCI->getOperand(1) == LHS);
1460 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1461 }
1462
1463 unsigned LHSCode = getSetCondCode(SCI);
1464 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1465 unsigned Code;
1466 switch (Log.getOpcode()) {
1467 case Instruction::And: Code = LHSCode & RHSCode; break;
1468 case Instruction::Or: Code = LHSCode | RHSCode; break;
1469 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001470 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001471 }
1472
1473 Value *RV = getSetCCValue(Code, LHS, RHS);
1474 if (Instruction *I = dyn_cast<Instruction>(RV))
1475 return I;
1476 // Otherwise, it's a constant boolean value...
1477 return IC.ReplaceInstUsesWith(Log, RV);
1478 }
1479};
1480
Chris Lattnerba1cb382003-09-19 17:17:26 +00001481// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1482// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1483// guaranteed to be either a shift instruction or a binary operator.
1484Instruction *InstCombiner::OptAndOp(Instruction *Op,
1485 ConstantIntegral *OpRHS,
1486 ConstantIntegral *AndRHS,
1487 BinaryOperator &TheAnd) {
1488 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001489 Constant *Together = 0;
1490 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001491 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001492
Chris Lattnerba1cb382003-09-19 17:17:26 +00001493 switch (Op->getOpcode()) {
1494 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001495 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001496 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1497 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001498 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001499 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001500 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001501 }
1502 break;
1503 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001504 if (Together == AndRHS) // (X | C) & C --> C
1505 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001506
Chris Lattner86102b82005-01-01 16:22:27 +00001507 if (Op->hasOneUse() && Together != OpRHS) {
1508 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1509 std::string Op0Name = Op->getName(); Op->setName("");
1510 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1511 InsertNewInstBefore(Or, TheAnd);
1512 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001513 }
1514 break;
1515 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001516 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001517 // Adding a one to a single bit bit-field should be turned into an XOR
1518 // of the bit. First thing to check is to see if this AND is with a
1519 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001520 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001521
1522 // Clear bits that are not part of the constant.
Chris Lattner2f1457f2005-04-24 17:46:05 +00001523 AndRHSV &= ~0ULL >> (64-AndRHS->getType()->getPrimitiveSizeInBits());
Chris Lattnerba1cb382003-09-19 17:17:26 +00001524
1525 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001526 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001527 // Ok, at this point, we know that we are masking the result of the
1528 // ADD down to exactly one bit. If the constant we are adding has
1529 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001530 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001531
Chris Lattnerba1cb382003-09-19 17:17:26 +00001532 // Check to see if any bits below the one bit set in AndRHSV are set.
1533 if ((AddRHS & (AndRHSV-1)) == 0) {
1534 // If not, the only thing that can effect the output of the AND is
1535 // the bit specified by AndRHSV. If that bit is set, the effect of
1536 // the XOR is to toggle the bit. If it is clear, then the ADD has
1537 // no effect.
1538 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1539 TheAnd.setOperand(0, X);
1540 return &TheAnd;
1541 } else {
1542 std::string Name = Op->getName(); Op->setName("");
1543 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001544 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001545 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001546 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001547 }
1548 }
1549 }
1550 }
1551 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001552
1553 case Instruction::Shl: {
1554 // We know that the AND will not produce any of the bits shifted in, so if
1555 // the anded constant includes them, clear them now!
1556 //
1557 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001558 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1559 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001560
Chris Lattner7e794272004-09-24 15:21:34 +00001561 if (CI == ShlMask) { // Masking out bits that the shift already masks
1562 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1563 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001564 TheAnd.setOperand(1, CI);
1565 return &TheAnd;
1566 }
1567 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001568 }
Chris Lattner2da29172003-09-19 19:05:02 +00001569 case Instruction::Shr:
1570 // We know that the AND will not produce any of the bits shifted in, so if
1571 // the anded constant includes them, clear them now! This only applies to
1572 // unsigned shifts, because a signed shr may bring in set bits!
1573 //
1574 if (AndRHS->getType()->isUnsigned()) {
1575 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001576 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1577 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1578
1579 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1580 return ReplaceInstUsesWith(TheAnd, Op);
1581 } else if (CI != AndRHS) {
1582 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001583 return &TheAnd;
1584 }
Chris Lattner7e794272004-09-24 15:21:34 +00001585 } else { // Signed shr.
1586 // See if this is shifting in some sign extension, then masking it out
1587 // with an and.
1588 if (Op->hasOneUse()) {
1589 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1590 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1591 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001592 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001593 // Make the argument unsigned.
1594 Value *ShVal = Op->getOperand(0);
1595 ShVal = InsertCastBefore(ShVal,
1596 ShVal->getType()->getUnsignedVersion(),
1597 TheAnd);
1598 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1599 OpRHS, Op->getName()),
1600 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001601 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1602 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1603 TheAnd.getName()),
1604 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001605 return new CastInst(ShVal, Op->getType());
1606 }
1607 }
Chris Lattner2da29172003-09-19 19:05:02 +00001608 }
1609 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001610 }
1611 return 0;
1612}
1613
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001614
Chris Lattner6862fbd2004-09-29 17:40:11 +00001615/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1616/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1617/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1618/// insert new instructions.
1619Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1620 bool Inside, Instruction &IB) {
1621 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1622 "Lo is not <= Hi in range emission code!");
1623 if (Inside) {
1624 if (Lo == Hi) // Trivially false.
1625 return new SetCondInst(Instruction::SetNE, V, V);
1626 if (cast<ConstantIntegral>(Lo)->isMinValue())
1627 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001628
Chris Lattner6862fbd2004-09-29 17:40:11 +00001629 Constant *AddCST = ConstantExpr::getNeg(Lo);
1630 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1631 InsertNewInstBefore(Add, IB);
1632 // Convert to unsigned for the comparison.
1633 const Type *UnsType = Add->getType()->getUnsignedVersion();
1634 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1635 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1636 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1637 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1638 }
1639
1640 if (Lo == Hi) // Trivially true.
1641 return new SetCondInst(Instruction::SetEQ, V, V);
1642
1643 Hi = SubOne(cast<ConstantInt>(Hi));
1644 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1645 return new SetCondInst(Instruction::SetGT, V, Hi);
1646
1647 // Emit X-Lo > Hi-Lo-1
1648 Constant *AddCST = ConstantExpr::getNeg(Lo);
1649 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1650 InsertNewInstBefore(Add, IB);
1651 // Convert to unsigned for the comparison.
1652 const Type *UnsType = Add->getType()->getUnsignedVersion();
1653 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1654 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1655 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1656 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1657}
1658
Chris Lattnerb4b25302005-09-18 07:22:02 +00001659// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1660// any number of 0s on either side. The 1s are allowed to wrap from LSB to
1661// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1662// not, since all 1s are not contiguous.
1663static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
1664 uint64_t V = Val->getRawValue();
1665 if (!isShiftedMask_64(V)) return false;
1666
1667 // look for the first zero bit after the run of ones
1668 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
1669 // look for the first non-zero bit
1670 ME = 64-CountLeadingZeros_64(V);
1671 return true;
1672}
1673
1674
1675
1676/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1677/// where isSub determines whether the operator is a sub. If we can fold one of
1678/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00001679///
1680/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1681/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1682/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1683///
1684/// return (A +/- B).
1685///
1686Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1687 ConstantIntegral *Mask, bool isSub,
1688 Instruction &I) {
1689 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1690 if (!LHSI || LHSI->getNumOperands() != 2 ||
1691 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1692
1693 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1694
1695 switch (LHSI->getOpcode()) {
1696 default: return 0;
1697 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001698 if (ConstantExpr::getAnd(N, Mask) == Mask) {
1699 // If the AndRHS is a power of two minus one (0+1+), this is simple.
1700 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
1701 break;
1702
1703 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1704 // part, we don't need any explicit masks to take them out of A. If that
1705 // is all N is, ignore it.
1706 unsigned MB, ME;
1707 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
1708 Constant *Mask = ConstantInt::getAllOnesValue(RHS->getType());
1709 Mask = ConstantExpr::getUShr(Mask,
1710 ConstantInt::get(Type::UByteTy,
1711 (64-MB+1)));
1712 if (MaskedValueIsZero(RHS, cast<ConstantIntegral>(Mask)))
1713 break;
1714 }
1715 }
Chris Lattneraf517572005-09-18 04:24:45 +00001716 return 0;
1717 case Instruction::Or:
1718 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001719 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
1720 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
1721 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00001722 break;
1723 return 0;
1724 }
1725
1726 Instruction *New;
1727 if (isSub)
1728 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
1729 else
1730 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
1731 return InsertNewInstBefore(New, I);
1732}
1733
Chris Lattner113f4f42002-06-25 16:13:24 +00001734Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001735 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001736 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001737
Chris Lattner81a7a232004-10-16 18:11:37 +00001738 if (isa<UndefValue>(Op1)) // X & undef -> 0
1739 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1740
Chris Lattner86102b82005-01-01 16:22:27 +00001741 // and X, X = X
1742 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00001743 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001744
Chris Lattner86102b82005-01-01 16:22:27 +00001745 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001746 // and X, -1 == X
1747 if (AndRHS->isAllOnesValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001748 return ReplaceInstUsesWith(I, Op0);
Chris Lattner38a1b002005-10-26 17:18:16 +00001749
1750 // and (and X, c1), c2 -> and (x, c1&c2). Handle this case here, before
1751 // calling MaskedValueIsZero, to avoid inefficient cases where we traipse
1752 // through many levels of ands.
1753 {
1754 Value *X; ConstantInt *C1;
1755 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))))
1756 return BinaryOperator::createAnd(X, ConstantExpr::getAnd(C1, AndRHS));
1757 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001758
Chris Lattner86102b82005-01-01 16:22:27 +00001759 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1760 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1761
1762 // If the mask is not masking out any bits, there is no reason to do the
1763 // and in the first place.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001764 ConstantIntegral *NotAndRHS =
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001765 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001766 if (MaskedValueIsZero(Op0, NotAndRHS))
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001767 return ReplaceInstUsesWith(I, Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001768
Chris Lattnerba1cb382003-09-19 17:17:26 +00001769 // Optimize a variety of ((val OP C1) & C2) combinations...
1770 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1771 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001772 Value *Op0LHS = Op0I->getOperand(0);
1773 Value *Op0RHS = Op0I->getOperand(1);
1774 switch (Op0I->getOpcode()) {
1775 case Instruction::Xor:
1776 case Instruction::Or:
1777 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1778 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1779 if (MaskedValueIsZero(Op0LHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001780 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattner86102b82005-01-01 16:22:27 +00001781 if (MaskedValueIsZero(Op0RHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001782 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001783
1784 // If the mask is only needed on one incoming arm, push it up.
1785 if (Op0I->hasOneUse()) {
1786 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1787 // Not masking anything out for the LHS, move to RHS.
1788 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1789 Op0RHS->getName()+".masked");
1790 InsertNewInstBefore(NewRHS, I);
1791 return BinaryOperator::create(
1792 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001793 }
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001794 if (!isa<Constant>(NotAndRHS) &&
1795 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1796 // Not masking anything out for the RHS, move to LHS.
1797 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1798 Op0LHS->getName()+".masked");
1799 InsertNewInstBefore(NewLHS, I);
1800 return BinaryOperator::create(
1801 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1802 }
1803 }
1804
Chris Lattner86102b82005-01-01 16:22:27 +00001805 break;
1806 case Instruction::And:
1807 // (X & V) & C2 --> 0 iff (V & C2) == 0
1808 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1809 MaskedValueIsZero(Op0RHS, AndRHS))
1810 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1811 break;
Chris Lattneraf517572005-09-18 04:24:45 +00001812 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001813 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1814 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1815 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1816 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1817 return BinaryOperator::createAnd(V, AndRHS);
1818 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1819 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00001820 break;
1821
1822 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001823 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1824 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1825 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1826 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1827 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00001828 break;
Chris Lattner86102b82005-01-01 16:22:27 +00001829 }
1830
Chris Lattner16464b32003-07-23 19:25:52 +00001831 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00001832 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001833 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00001834 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1835 const Type *SrcTy = CI->getOperand(0)->getType();
1836
Chris Lattner2c14cf72005-08-07 07:03:10 +00001837 // If this is an integer truncation or change from signed-to-unsigned, and
1838 // if the source is an and/or with immediate, transform it. This
1839 // frequently occurs for bitfield accesses.
1840 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
1841 if (SrcTy->getPrimitiveSizeInBits() >=
1842 I.getType()->getPrimitiveSizeInBits() &&
1843 CastOp->getNumOperands() == 2)
1844 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
1845 if (CastOp->getOpcode() == Instruction::And) {
1846 // Change: and (cast (and X, C1) to T), C2
1847 // into : and (cast X to T), trunc(C1)&C2
1848 // This will folds the two ands together, which may allow other
1849 // simplifications.
1850 Instruction *NewCast =
1851 new CastInst(CastOp->getOperand(0), I.getType(),
1852 CastOp->getName()+".shrunk");
1853 NewCast = InsertNewInstBefore(NewCast, I);
1854
1855 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1856 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
1857 return BinaryOperator::createAnd(NewCast, C3);
1858 } else if (CastOp->getOpcode() == Instruction::Or) {
1859 // Change: and (cast (or X, C1) to T), C2
1860 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
1861 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1862 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
1863 return ReplaceInstUsesWith(I, AndRHS);
1864 }
1865 }
1866
1867
Chris Lattner86102b82005-01-01 16:22:27 +00001868 // If this is an integer sign or zero extension instruction.
1869 if (SrcTy->isIntegral() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001870 SrcTy->getPrimitiveSizeInBits() <
1871 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00001872
1873 if (SrcTy->isUnsigned()) {
1874 // See if this and is clearing out bits that are known to be zero
1875 // anyway (due to the zero extension).
1876 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1877 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1878 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1879 if (Result == Mask) // The "and" isn't doing anything, remove it.
1880 return ReplaceInstUsesWith(I, CI);
1881 if (Result != AndRHS) { // Reduce the and RHS constant.
1882 I.setOperand(1, Result);
1883 return &I;
1884 }
1885
1886 } else {
1887 if (CI->hasOneUse() && SrcTy->isInteger()) {
1888 // We can only do this if all of the sign bits brought in are masked
1889 // out. Compute this by first getting 0000011111, then inverting
1890 // it.
1891 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1892 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1893 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1894 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1895 // If the and is clearing all of the sign bits, change this to a
1896 // zero extension cast. To do this, cast the cast input to
1897 // unsigned, then to the requested size.
1898 Value *CastOp = CI->getOperand(0);
1899 Instruction *NC =
1900 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1901 CI->getName()+".uns");
1902 NC = InsertNewInstBefore(NC, I);
1903 // Finally, insert a replacement for CI.
1904 NC = new CastInst(NC, CI->getType(), CI->getName());
1905 CI->setName("");
1906 NC = InsertNewInstBefore(NC, I);
1907 WorkList.push_back(CI); // Delete CI later.
1908 I.setOperand(0, NC);
1909 return &I; // The AND operand was modified.
1910 }
1911 }
1912 }
1913 }
Chris Lattner33217db2003-07-23 19:36:21 +00001914 }
Chris Lattner183b3362004-04-09 19:05:30 +00001915
1916 // Try to fold constant and into select arguments.
1917 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001918 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001919 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001920 if (isa<PHINode>(Op0))
1921 if (Instruction *NV = FoldOpIntoPhi(I))
1922 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001923 }
1924
Chris Lattnerbb74e222003-03-10 23:06:50 +00001925 Value *Op0NotVal = dyn_castNotVal(Op0);
1926 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001927
Chris Lattner023a4832004-06-18 06:07:51 +00001928 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1929 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1930
Misha Brukman9c003d82004-07-30 12:50:08 +00001931 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001932 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001933 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1934 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001935 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001936 return BinaryOperator::createNot(Or);
1937 }
1938
Chris Lattner623826c2004-09-28 21:48:02 +00001939 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1940 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001941 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1942 return R;
1943
Chris Lattner623826c2004-09-28 21:48:02 +00001944 Value *LHSVal, *RHSVal;
1945 ConstantInt *LHSCst, *RHSCst;
1946 Instruction::BinaryOps LHSCC, RHSCC;
1947 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1948 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1949 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1950 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001951 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00001952 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1953 // Ensure that the larger constant is on the RHS.
1954 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1955 SetCondInst *LHS = cast<SetCondInst>(Op0);
1956 if (cast<ConstantBool>(Cmp)->getValue()) {
1957 std::swap(LHS, RHS);
1958 std::swap(LHSCst, RHSCst);
1959 std::swap(LHSCC, RHSCC);
1960 }
1961
1962 // At this point, we know we have have two setcc instructions
1963 // comparing a value against two constants and and'ing the result
1964 // together. Because of the above check, we know that we only have
1965 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1966 // FoldSetCCLogical check above), that the two constants are not
1967 // equal.
1968 assert(LHSCst != RHSCst && "Compares not folded above?");
1969
1970 switch (LHSCC) {
1971 default: assert(0 && "Unknown integer condition code!");
1972 case Instruction::SetEQ:
1973 switch (RHSCC) {
1974 default: assert(0 && "Unknown integer condition code!");
1975 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1976 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1977 return ReplaceInstUsesWith(I, ConstantBool::False);
1978 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1979 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1980 return ReplaceInstUsesWith(I, LHS);
1981 }
1982 case Instruction::SetNE:
1983 switch (RHSCC) {
1984 default: assert(0 && "Unknown integer condition code!");
1985 case Instruction::SetLT:
1986 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1987 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1988 break; // (X != 13 & X < 15) -> no change
1989 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1990 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1991 return ReplaceInstUsesWith(I, RHS);
1992 case Instruction::SetNE:
1993 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1994 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1995 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1996 LHSVal->getName()+".off");
1997 InsertNewInstBefore(Add, I);
1998 const Type *UnsType = Add->getType()->getUnsignedVersion();
1999 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2000 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2001 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2002 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2003 }
2004 break; // (X != 13 & X != 15) -> no change
2005 }
2006 break;
2007 case Instruction::SetLT:
2008 switch (RHSCC) {
2009 default: assert(0 && "Unknown integer condition code!");
2010 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2011 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2012 return ReplaceInstUsesWith(I, ConstantBool::False);
2013 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2014 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2015 return ReplaceInstUsesWith(I, LHS);
2016 }
2017 case Instruction::SetGT:
2018 switch (RHSCC) {
2019 default: assert(0 && "Unknown integer condition code!");
2020 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2021 return ReplaceInstUsesWith(I, LHS);
2022 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2023 return ReplaceInstUsesWith(I, RHS);
2024 case Instruction::SetNE:
2025 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2026 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2027 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002028 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2029 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002030 }
2031 }
2032 }
2033 }
2034
Chris Lattner113f4f42002-06-25 16:13:24 +00002035 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002036}
2037
Chris Lattner113f4f42002-06-25 16:13:24 +00002038Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002039 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002040 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002041
Chris Lattner81a7a232004-10-16 18:11:37 +00002042 if (isa<UndefValue>(Op1))
2043 return ReplaceInstUsesWith(I, // X | undef -> -1
2044 ConstantIntegral::getAllOnesValue(I.getType()));
2045
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002046 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00002047 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2048 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002049
2050 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00002051 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00002052 // If X is known to only contain bits that already exist in RHS, just
2053 // replace this instruction with RHS directly.
2054 if (MaskedValueIsZero(Op0,
2055 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
2056 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002057
Chris Lattnerd4252a72004-07-30 07:50:03 +00002058 ConstantInt *C1; Value *X;
2059 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2060 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002061 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2062 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00002063 InsertNewInstBefore(Or, I);
2064 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2065 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00002066
Chris Lattnerd4252a72004-07-30 07:50:03 +00002067 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2068 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2069 std::string Op0Name = Op0->getName(); Op0->setName("");
2070 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2071 InsertNewInstBefore(Or, I);
2072 return BinaryOperator::createXor(Or,
2073 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00002074 }
Chris Lattner183b3362004-04-09 19:05:30 +00002075
2076 // Try to fold constant and into select arguments.
2077 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002078 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002079 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002080 if (isa<PHINode>(Op0))
2081 if (Instruction *NV = FoldOpIntoPhi(I))
2082 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00002083 }
2084
Chris Lattnerd4252a72004-07-30 07:50:03 +00002085 Value *A, *B; ConstantInt *C1, *C2;
Chris Lattner4294cec2005-05-07 23:49:08 +00002086
2087 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2088 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2089 return ReplaceInstUsesWith(I, Op1);
2090 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2091 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2092 return ReplaceInstUsesWith(I, Op0);
2093
Chris Lattnerb62f5082005-05-09 04:58:36 +00002094 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2095 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2096 MaskedValueIsZero(Op1, C1)) {
2097 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2098 Op0->setName("");
2099 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2100 }
2101
2102 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2103 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2104 MaskedValueIsZero(Op0, C1)) {
2105 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2106 Op0->setName("");
2107 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2108 }
2109
Chris Lattner15212982005-09-18 03:42:07 +00002110 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00002111 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00002112 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2113
2114 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2115 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2116
2117
Chris Lattner01f56c62005-09-18 06:02:59 +00002118 // If we have: ((V + N) & C1) | (V & C2)
2119 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2120 // replace with V+N.
2121 if (C1 == ConstantExpr::getNot(C2)) {
2122 Value *V1, *V2;
2123 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2124 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2125 // Add commutes, try both ways.
2126 if (V1 == B && MaskedValueIsZero(V2, C2))
2127 return ReplaceInstUsesWith(I, A);
2128 if (V2 == B && MaskedValueIsZero(V1, C2))
2129 return ReplaceInstUsesWith(I, A);
2130 }
2131 // Or commutes, try both ways.
2132 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2133 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2134 // Add commutes, try both ways.
2135 if (V1 == A && MaskedValueIsZero(V2, C1))
2136 return ReplaceInstUsesWith(I, B);
2137 if (V2 == A && MaskedValueIsZero(V1, C1))
2138 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00002139 }
2140 }
2141 }
Chris Lattner812aab72003-08-12 19:11:07 +00002142
Chris Lattnerd4252a72004-07-30 07:50:03 +00002143 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2144 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00002145 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002146 ConstantIntegral::getAllOnesValue(I.getType()));
2147 } else {
2148 A = 0;
2149 }
Chris Lattner4294cec2005-05-07 23:49:08 +00002150 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00002151 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2152 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00002153 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002154 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00002155
Misha Brukman9c003d82004-07-30 12:50:08 +00002156 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00002157 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2158 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2159 I.getName()+".demorgan"), I);
2160 return BinaryOperator::createNot(And);
2161 }
Chris Lattner3e327a42003-03-10 23:13:59 +00002162 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002163
Chris Lattner3ac7c262003-08-13 20:16:26 +00002164 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002165 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002166 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2167 return R;
2168
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002169 Value *LHSVal, *RHSVal;
2170 ConstantInt *LHSCst, *RHSCst;
2171 Instruction::BinaryOps LHSCC, RHSCC;
2172 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2173 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2174 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2175 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002176 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002177 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2178 // Ensure that the larger constant is on the RHS.
2179 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2180 SetCondInst *LHS = cast<SetCondInst>(Op0);
2181 if (cast<ConstantBool>(Cmp)->getValue()) {
2182 std::swap(LHS, RHS);
2183 std::swap(LHSCst, RHSCst);
2184 std::swap(LHSCC, RHSCC);
2185 }
2186
2187 // At this point, we know we have have two setcc instructions
2188 // comparing a value against two constants and or'ing the result
2189 // together. Because of the above check, we know that we only have
2190 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2191 // FoldSetCCLogical check above), that the two constants are not
2192 // equal.
2193 assert(LHSCst != RHSCst && "Compares not folded above?");
2194
2195 switch (LHSCC) {
2196 default: assert(0 && "Unknown integer condition code!");
2197 case Instruction::SetEQ:
2198 switch (RHSCC) {
2199 default: assert(0 && "Unknown integer condition code!");
2200 case Instruction::SetEQ:
2201 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2202 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2203 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2204 LHSVal->getName()+".off");
2205 InsertNewInstBefore(Add, I);
2206 const Type *UnsType = Add->getType()->getUnsignedVersion();
2207 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2208 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2209 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2210 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2211 }
2212 break; // (X == 13 | X == 15) -> no change
2213
Chris Lattner5c219462005-04-19 06:04:18 +00002214 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2215 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002216 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2217 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2218 return ReplaceInstUsesWith(I, RHS);
2219 }
2220 break;
2221 case Instruction::SetNE:
2222 switch (RHSCC) {
2223 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002224 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2225 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2226 return ReplaceInstUsesWith(I, LHS);
2227 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00002228 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002229 return ReplaceInstUsesWith(I, ConstantBool::True);
2230 }
2231 break;
2232 case Instruction::SetLT:
2233 switch (RHSCC) {
2234 default: assert(0 && "Unknown integer condition code!");
2235 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2236 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002237 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2238 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
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::SetGT:
2245 switch (RHSCC) {
2246 default: assert(0 && "Unknown integer condition code!");
2247 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
2251 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2252 return ReplaceInstUsesWith(I, ConstantBool::True);
2253 }
2254 }
2255 }
2256 }
Chris Lattner15212982005-09-18 03:42:07 +00002257
Chris Lattner113f4f42002-06-25 16:13:24 +00002258 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002259}
2260
Chris Lattnerc2076352004-02-16 01:20:27 +00002261// XorSelf - Implements: X ^ X --> 0
2262struct XorSelf {
2263 Value *RHS;
2264 XorSelf(Value *rhs) : RHS(rhs) {}
2265 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2266 Instruction *apply(BinaryOperator &Xor) const {
2267 return &Xor;
2268 }
2269};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002270
2271
Chris Lattner113f4f42002-06-25 16:13:24 +00002272Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002273 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002274 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002275
Chris Lattner81a7a232004-10-16 18:11:37 +00002276 if (isa<UndefValue>(Op1))
2277 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2278
Chris Lattnerc2076352004-02-16 01:20:27 +00002279 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2280 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2281 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002282 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002283 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002284
Chris Lattner97638592003-07-23 21:37:07 +00002285 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002286 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00002287 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00002288 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002289
Chris Lattner97638592003-07-23 21:37:07 +00002290 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002291 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002292 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002293 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002294 return new SetCondInst(SCI->getInverseCondition(),
2295 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002296
Chris Lattner8f2f5982003-11-05 01:06:05 +00002297 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002298 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2299 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002300 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2301 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002302 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002303 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002304 }
Chris Lattner023a4832004-06-18 06:07:51 +00002305
2306 // ~(~X & Y) --> (X | ~Y)
2307 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2308 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2309 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2310 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002311 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002312 Op0I->getOperand(1)->getName()+".not");
2313 InsertNewInstBefore(NotY, I);
2314 return BinaryOperator::createOr(Op0NotVal, NotY);
2315 }
2316 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002317
Chris Lattner97638592003-07-23 21:37:07 +00002318 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002319 switch (Op0I->getOpcode()) {
2320 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002321 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002322 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002323 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2324 return BinaryOperator::createSub(
2325 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002326 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002327 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002328 }
Chris Lattnere5806662003-11-04 23:50:51 +00002329 break;
2330 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002331 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002332 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2333 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002334 break;
2335 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002336 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002337 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002338 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002339 break;
2340 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002341 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002342 }
Chris Lattner183b3362004-04-09 19:05:30 +00002343
2344 // Try to fold constant and into select arguments.
2345 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002346 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002347 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002348 if (isa<PHINode>(Op0))
2349 if (Instruction *NV = FoldOpIntoPhi(I))
2350 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002351 }
2352
Chris Lattnerbb74e222003-03-10 23:06:50 +00002353 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002354 if (X == Op1)
2355 return ReplaceInstUsesWith(I,
2356 ConstantIntegral::getAllOnesValue(I.getType()));
2357
Chris Lattnerbb74e222003-03-10 23:06:50 +00002358 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002359 if (X == Op0)
2360 return ReplaceInstUsesWith(I,
2361 ConstantIntegral::getAllOnesValue(I.getType()));
2362
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002363 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002364 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002365 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2366 cast<BinaryOperator>(Op1I)->swapOperands();
2367 I.swapOperands();
2368 std::swap(Op0, Op1);
2369 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2370 I.swapOperands();
2371 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002372 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002373 } else if (Op1I->getOpcode() == Instruction::Xor) {
2374 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2375 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2376 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2377 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2378 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002379
2380 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002381 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002382 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2383 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002384 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002385 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2386 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002387 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002388 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002389 } else if (Op0I->getOpcode() == Instruction::Xor) {
2390 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2391 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2392 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2393 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002394 }
2395
Chris Lattner7aa2d472004-08-01 19:42:59 +00002396 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002397 Value *A, *B; ConstantInt *C1, *C2;
2398 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2399 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002400 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002401 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002402
Chris Lattner3ac7c262003-08-13 20:16:26 +00002403 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2404 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2405 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2406 return R;
2407
Chris Lattner113f4f42002-06-25 16:13:24 +00002408 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002409}
2410
Chris Lattner6862fbd2004-09-29 17:40:11 +00002411/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2412/// overflowed for this type.
2413static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2414 ConstantInt *In2) {
2415 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2416 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2417}
2418
2419static bool isPositive(ConstantInt *C) {
2420 return cast<ConstantSInt>(C)->getValue() >= 0;
2421}
2422
2423/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2424/// overflowed for this type.
2425static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2426 ConstantInt *In2) {
2427 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2428
2429 if (In1->getType()->isUnsigned())
2430 return cast<ConstantUInt>(Result)->getValue() <
2431 cast<ConstantUInt>(In1)->getValue();
2432 if (isPositive(In1) != isPositive(In2))
2433 return false;
2434 if (isPositive(In1))
2435 return cast<ConstantSInt>(Result)->getValue() <
2436 cast<ConstantSInt>(In1)->getValue();
2437 return cast<ConstantSInt>(Result)->getValue() >
2438 cast<ConstantSInt>(In1)->getValue();
2439}
2440
Chris Lattner0798af32005-01-13 20:14:25 +00002441/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2442/// code necessary to compute the offset from the base pointer (without adding
2443/// in the base pointer). Return the result as a signed integer of intptr size.
2444static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2445 TargetData &TD = IC.getTargetData();
2446 gep_type_iterator GTI = gep_type_begin(GEP);
2447 const Type *UIntPtrTy = TD.getIntPtrType();
2448 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2449 Value *Result = Constant::getNullValue(SIntPtrTy);
2450
2451 // Build a mask for high order bits.
2452 uint64_t PtrSizeMask = ~0ULL;
2453 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2454
Chris Lattner0798af32005-01-13 20:14:25 +00002455 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2456 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002457 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002458 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2459 SIntPtrTy);
2460 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2461 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002462 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002463 Scale = ConstantExpr::getMul(OpC, Scale);
2464 if (Constant *RC = dyn_cast<Constant>(Result))
2465 Result = ConstantExpr::getAdd(RC, Scale);
2466 else {
2467 // Emit an add instruction.
2468 Result = IC.InsertNewInstBefore(
2469 BinaryOperator::createAdd(Result, Scale,
2470 GEP->getName()+".offs"), I);
2471 }
2472 }
2473 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002474 // Convert to correct type.
2475 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2476 Op->getName()+".c"), I);
2477 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002478 // We'll let instcombine(mul) convert this to a shl if possible.
2479 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2480 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002481
2482 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002483 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002484 GEP->getName()+".offs"), I);
2485 }
2486 }
2487 return Result;
2488}
2489
2490/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2491/// else. At this point we know that the GEP is on the LHS of the comparison.
2492Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2493 Instruction::BinaryOps Cond,
2494 Instruction &I) {
2495 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002496
2497 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2498 if (isa<PointerType>(CI->getOperand(0)->getType()))
2499 RHS = CI->getOperand(0);
2500
Chris Lattner0798af32005-01-13 20:14:25 +00002501 Value *PtrBase = GEPLHS->getOperand(0);
2502 if (PtrBase == RHS) {
2503 // As an optimization, we don't actually have to compute the actual value of
2504 // OFFSET if this is a seteq or setne comparison, just return whether each
2505 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002506 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2507 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002508 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2509 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00002510 bool EmitIt = true;
2511 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2512 if (isa<UndefValue>(C)) // undef index -> undef.
2513 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2514 if (C->isNullValue())
2515 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002516 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2517 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00002518 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00002519 return ReplaceInstUsesWith(I, // No comparison is needed here.
2520 ConstantBool::get(Cond == Instruction::SetNE));
2521 }
2522
2523 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002524 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00002525 new SetCondInst(Cond, GEPLHS->getOperand(i),
2526 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2527 if (InVal == 0)
2528 InVal = Comp;
2529 else {
2530 InVal = InsertNewInstBefore(InVal, I);
2531 InsertNewInstBefore(Comp, I);
2532 if (Cond == Instruction::SetNE) // True if any are unequal
2533 InVal = BinaryOperator::createOr(InVal, Comp);
2534 else // True if all are equal
2535 InVal = BinaryOperator::createAnd(InVal, Comp);
2536 }
2537 }
2538 }
2539
2540 if (InVal)
2541 return InVal;
2542 else
2543 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2544 ConstantBool::get(Cond == Instruction::SetEQ));
2545 }
Chris Lattner0798af32005-01-13 20:14:25 +00002546
2547 // Only lower this if the setcc is the only user of the GEP or if we expect
2548 // the result to fold to a constant!
2549 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2550 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2551 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2552 return new SetCondInst(Cond, Offset,
2553 Constant::getNullValue(Offset->getType()));
2554 }
2555 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002556 // If the base pointers are different, but the indices are the same, just
2557 // compare the base pointer.
2558 if (PtrBase != GEPRHS->getOperand(0)) {
2559 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002560 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00002561 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002562 if (IndicesTheSame)
2563 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2564 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2565 IndicesTheSame = false;
2566 break;
2567 }
2568
2569 // If all indices are the same, just compare the base pointers.
2570 if (IndicesTheSame)
2571 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2572 GEPRHS->getOperand(0));
2573
2574 // Otherwise, the base pointers are different and the indices are
2575 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00002576 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002577 }
Chris Lattner0798af32005-01-13 20:14:25 +00002578
Chris Lattner81e84172005-01-13 22:25:21 +00002579 // If one of the GEPs has all zero indices, recurse.
2580 bool AllZeros = true;
2581 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2582 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2583 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2584 AllZeros = false;
2585 break;
2586 }
2587 if (AllZeros)
2588 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2589 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00002590
2591 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00002592 AllZeros = true;
2593 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2594 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2595 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2596 AllZeros = false;
2597 break;
2598 }
2599 if (AllZeros)
2600 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2601
Chris Lattner4fa89822005-01-14 00:20:05 +00002602 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2603 // If the GEPs only differ by one index, compare it.
2604 unsigned NumDifferences = 0; // Keep track of # differences.
2605 unsigned DiffOperand = 0; // The operand that differs.
2606 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2607 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002608 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2609 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002610 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00002611 NumDifferences = 2;
2612 break;
2613 } else {
2614 if (NumDifferences++) break;
2615 DiffOperand = i;
2616 }
2617 }
2618
2619 if (NumDifferences == 0) // SAME GEP?
2620 return ReplaceInstUsesWith(I, // No comparison is needed here.
2621 ConstantBool::get(Cond == Instruction::SetEQ));
2622 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002623 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2624 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00002625
2626 // Convert the operands to signed values to make sure to perform a
2627 // signed comparison.
2628 const Type *NewTy = LHSV->getType()->getSignedVersion();
2629 if (LHSV->getType() != NewTy)
2630 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2631 LHSV->getName()), I);
2632 if (RHSV->getType() != NewTy)
2633 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2634 RHSV->getName()), I);
2635 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00002636 }
2637 }
2638
Chris Lattner0798af32005-01-13 20:14:25 +00002639 // Only lower this if the setcc is the only user of the GEP or if we expect
2640 // the result to fold to a constant!
2641 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2642 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2643 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2644 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2645 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2646 return new SetCondInst(Cond, L, R);
2647 }
2648 }
2649 return 0;
2650}
2651
2652
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002653Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002654 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002655 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2656 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002657
2658 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002659 if (Op0 == Op1)
2660 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002661
Chris Lattner81a7a232004-10-16 18:11:37 +00002662 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2663 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2664
Chris Lattner15ff1e12004-11-14 07:33:16 +00002665 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2666 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002667 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2668 isa<ConstantPointerNull>(Op0)) &&
2669 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00002670 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002671 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2672
2673 // setcc's with boolean values can always be turned into bitwise operations
2674 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002675 switch (I.getOpcode()) {
2676 default: assert(0 && "Invalid setcc instruction!");
2677 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002678 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002679 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002680 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002681 }
Chris Lattner4456da62004-08-11 00:50:51 +00002682 case Instruction::SetNE:
2683 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002684
Chris Lattner4456da62004-08-11 00:50:51 +00002685 case Instruction::SetGT:
2686 std::swap(Op0, Op1); // Change setgt -> setlt
2687 // FALL THROUGH
2688 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2689 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2690 InsertNewInstBefore(Not, I);
2691 return BinaryOperator::createAnd(Not, Op1);
2692 }
2693 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002694 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002695 // FALL THROUGH
2696 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2697 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2698 InsertNewInstBefore(Not, I);
2699 return BinaryOperator::createOr(Not, Op1);
2700 }
2701 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002702 }
2703
Chris Lattner2dd01742004-06-09 04:24:29 +00002704 // See if we are doing a comparison between a constant and an instruction that
2705 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002706 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002707 // Check to see if we are comparing against the minimum or maximum value...
2708 if (CI->isMinValue()) {
2709 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2710 return ReplaceInstUsesWith(I, ConstantBool::False);
2711 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2712 return ReplaceInstUsesWith(I, ConstantBool::True);
2713 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2714 return BinaryOperator::createSetEQ(Op0, Op1);
2715 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2716 return BinaryOperator::createSetNE(Op0, Op1);
2717
2718 } else if (CI->isMaxValue()) {
2719 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2720 return ReplaceInstUsesWith(I, ConstantBool::False);
2721 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2722 return ReplaceInstUsesWith(I, ConstantBool::True);
2723 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2724 return BinaryOperator::createSetEQ(Op0, Op1);
2725 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2726 return BinaryOperator::createSetNE(Op0, Op1);
2727
2728 // Comparing against a value really close to min or max?
2729 } else if (isMinValuePlusOne(CI)) {
2730 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2731 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2732 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2733 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2734
2735 } else if (isMaxValueMinusOne(CI)) {
2736 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2737 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2738 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2739 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2740 }
2741
2742 // If we still have a setle or setge instruction, turn it into the
2743 // appropriate setlt or setgt instruction. Since the border cases have
2744 // already been handled above, this requires little checking.
2745 //
2746 if (I.getOpcode() == Instruction::SetLE)
2747 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2748 if (I.getOpcode() == Instruction::SetGE)
2749 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2750
Chris Lattnere1e10e12004-05-25 06:32:08 +00002751 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002752 switch (LHSI->getOpcode()) {
2753 case Instruction::And:
2754 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2755 LHSI->getOperand(0)->hasOneUse()) {
2756 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2757 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2758 // happens a LOT in code produced by the C front-end, for bitfield
2759 // access.
2760 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2761 ConstantUInt *ShAmt;
2762 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2763 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2764 const Type *Ty = LHSI->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002765
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002766 // We can fold this as long as we can't shift unknown bits
2767 // into the mask. This can only happen with signed shift
2768 // rights, as they sign-extend.
2769 if (ShAmt) {
2770 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002771 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002772 if (!CanFold) {
2773 // To test for the bad case of the signed shr, see if any
2774 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00002775 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2776 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2777
2778 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002779 Constant *ShVal =
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002780 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2781 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2782 CanFold = true;
2783 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002784
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002785 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002786 Constant *NewCst;
2787 if (Shift->getOpcode() == Instruction::Shl)
2788 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2789 else
2790 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002791
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002792 // Check to see if we are shifting out any of the bits being
2793 // compared.
2794 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2795 // If we shifted bits out, the fold is not going to work out.
2796 // As a special case, check to see if this means that the
2797 // result is always true or false now.
2798 if (I.getOpcode() == Instruction::SetEQ)
2799 return ReplaceInstUsesWith(I, ConstantBool::False);
2800 if (I.getOpcode() == Instruction::SetNE)
2801 return ReplaceInstUsesWith(I, ConstantBool::True);
2802 } else {
2803 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002804 Constant *NewAndCST;
2805 if (Shift->getOpcode() == Instruction::Shl)
2806 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2807 else
2808 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2809 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002810 LHSI->setOperand(0, Shift->getOperand(0));
2811 WorkList.push_back(Shift); // Shift is dead.
2812 AddUsesToWorkList(I);
2813 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002814 }
2815 }
Chris Lattner35167c32004-06-09 07:59:58 +00002816 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002817 }
2818 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002819
Chris Lattner272d5ca2004-09-28 18:22:15 +00002820 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2821 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2822 switch (I.getOpcode()) {
2823 default: break;
2824 case Instruction::SetEQ:
2825 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002826 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2827
2828 // Check that the shift amount is in range. If not, don't perform
2829 // undefined shifts. When the shift is visited it will be
2830 // simplified.
2831 if (ShAmt->getValue() >= TypeBits)
2832 break;
2833
Chris Lattner272d5ca2004-09-28 18:22:15 +00002834 // If we are comparing against bits always shifted out, the
2835 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002836 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00002837 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2838 if (Comp != CI) {// Comparing against a bit that we know is zero.
2839 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2840 Constant *Cst = ConstantBool::get(IsSetNE);
2841 return ReplaceInstUsesWith(I, Cst);
2842 }
2843
2844 if (LHSI->hasOneUse()) {
2845 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002846 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002847 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2848
2849 Constant *Mask;
2850 if (CI->getType()->isUnsigned()) {
2851 Mask = ConstantUInt::get(CI->getType(), Val);
2852 } else if (ShAmtVal != 0) {
2853 Mask = ConstantSInt::get(CI->getType(), Val);
2854 } else {
2855 Mask = ConstantInt::getAllOnesValue(CI->getType());
2856 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002857
Chris Lattner272d5ca2004-09-28 18:22:15 +00002858 Instruction *AndI =
2859 BinaryOperator::createAnd(LHSI->getOperand(0),
2860 Mask, LHSI->getName()+".mask");
2861 Value *And = InsertNewInstBefore(AndI, I);
2862 return new SetCondInst(I.getOpcode(), And,
2863 ConstantExpr::getUShr(CI, ShAmt));
2864 }
2865 }
2866 }
2867 }
2868 break;
2869
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002870 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002871 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002872 switch (I.getOpcode()) {
2873 default: break;
2874 case Instruction::SetEQ:
2875 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002876
2877 // Check that the shift amount is in range. If not, don't perform
2878 // undefined shifts. When the shift is visited it will be
2879 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00002880 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00002881 if (ShAmt->getValue() >= TypeBits)
2882 break;
2883
Chris Lattner1023b872004-09-27 16:18:50 +00002884 // If we are comparing against bits always shifted out, the
2885 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002886 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00002887 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002888
Chris Lattner1023b872004-09-27 16:18:50 +00002889 if (Comp != CI) {// Comparing against a bit that we know is zero.
2890 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2891 Constant *Cst = ConstantBool::get(IsSetNE);
2892 return ReplaceInstUsesWith(I, Cst);
2893 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002894
Chris Lattner1023b872004-09-27 16:18:50 +00002895 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002896 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002897
Chris Lattner1023b872004-09-27 16:18:50 +00002898 // Otherwise strength reduce the shift into an and.
2899 uint64_t Val = ~0ULL; // All ones.
2900 Val <<= ShAmtVal; // Shift over to the right spot.
2901
2902 Constant *Mask;
2903 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00002904 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00002905 Mask = ConstantUInt::get(CI->getType(), Val);
2906 } else {
2907 Mask = ConstantSInt::get(CI->getType(), Val);
2908 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002909
Chris Lattner1023b872004-09-27 16:18:50 +00002910 Instruction *AndI =
2911 BinaryOperator::createAnd(LHSI->getOperand(0),
2912 Mask, LHSI->getName()+".mask");
2913 Value *And = InsertNewInstBefore(AndI, I);
2914 return new SetCondInst(I.getOpcode(), And,
2915 ConstantExpr::getShl(CI, ShAmt));
2916 }
2917 break;
2918 }
2919 }
2920 }
2921 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002922
Chris Lattner6862fbd2004-09-29 17:40:11 +00002923 case Instruction::Div:
2924 // Fold: (div X, C1) op C2 -> range check
2925 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2926 // Fold this div into the comparison, producing a range check.
2927 // Determine, based on the divide type, what the range is being
2928 // checked. If there is an overflow on the low or high side, remember
2929 // it, otherwise compute the range [low, hi) bounding the new value.
2930 bool LoOverflow = false, HiOverflow = 0;
2931 ConstantInt *LoBound = 0, *HiBound = 0;
2932
2933 ConstantInt *Prod;
2934 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2935
Chris Lattnera92af962004-10-11 19:40:04 +00002936 Instruction::BinaryOps Opcode = I.getOpcode();
2937
Chris Lattner6862fbd2004-09-29 17:40:11 +00002938 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2939 } else if (LHSI->getType()->isUnsigned()) { // udiv
2940 LoBound = Prod;
2941 LoOverflow = ProdOV;
2942 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2943 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2944 if (CI->isNullValue()) { // (X / pos) op 0
2945 // Can't overflow.
2946 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2947 HiBound = DivRHS;
2948 } else if (isPositive(CI)) { // (X / pos) op pos
2949 LoBound = Prod;
2950 LoOverflow = ProdOV;
2951 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2952 } else { // (X / pos) op neg
2953 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2954 LoOverflow = AddWithOverflow(LoBound, Prod,
2955 cast<ConstantInt>(DivRHSH));
2956 HiBound = Prod;
2957 HiOverflow = ProdOV;
2958 }
2959 } else { // Divisor is < 0.
2960 if (CI->isNullValue()) { // (X / neg) op 0
2961 LoBound = AddOne(DivRHS);
2962 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00002963 if (HiBound == DivRHS)
2964 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00002965 } else if (isPositive(CI)) { // (X / neg) op pos
2966 HiOverflow = LoOverflow = ProdOV;
2967 if (!LoOverflow)
2968 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2969 HiBound = AddOne(Prod);
2970 } else { // (X / neg) op neg
2971 LoBound = Prod;
2972 LoOverflow = HiOverflow = ProdOV;
2973 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2974 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002975
Chris Lattnera92af962004-10-11 19:40:04 +00002976 // Dividing by a negate swaps the condition.
2977 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002978 }
2979
2980 if (LoBound) {
2981 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002982 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002983 default: assert(0 && "Unhandled setcc opcode!");
2984 case Instruction::SetEQ:
2985 if (LoOverflow && HiOverflow)
2986 return ReplaceInstUsesWith(I, ConstantBool::False);
2987 else if (HiOverflow)
2988 return new SetCondInst(Instruction::SetGE, X, LoBound);
2989 else if (LoOverflow)
2990 return new SetCondInst(Instruction::SetLT, X, HiBound);
2991 else
2992 return InsertRangeTest(X, LoBound, HiBound, true, I);
2993 case Instruction::SetNE:
2994 if (LoOverflow && HiOverflow)
2995 return ReplaceInstUsesWith(I, ConstantBool::True);
2996 else if (HiOverflow)
2997 return new SetCondInst(Instruction::SetLT, X, LoBound);
2998 else if (LoOverflow)
2999 return new SetCondInst(Instruction::SetGE, X, HiBound);
3000 else
3001 return InsertRangeTest(X, LoBound, HiBound, false, I);
3002 case Instruction::SetLT:
3003 if (LoOverflow)
3004 return ReplaceInstUsesWith(I, ConstantBool::False);
3005 return new SetCondInst(Instruction::SetLT, X, LoBound);
3006 case Instruction::SetGT:
3007 if (HiOverflow)
3008 return ReplaceInstUsesWith(I, ConstantBool::False);
3009 return new SetCondInst(Instruction::SetGE, X, HiBound);
3010 }
3011 }
3012 }
3013 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003014 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003015
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003016 // Simplify seteq and setne instructions...
3017 if (I.getOpcode() == Instruction::SetEQ ||
3018 I.getOpcode() == Instruction::SetNE) {
3019 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3020
Chris Lattnercfbce7c2003-07-23 17:26:36 +00003021 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003022 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00003023 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3024 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00003025 case Instruction::Rem:
3026 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3027 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3028 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00003029 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3030 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3031 if (isPowerOf2_64(V)) {
3032 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00003033 const Type *UTy = BO->getType()->getUnsignedVersion();
3034 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3035 UTy, "tmp"), I);
3036 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3037 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3038 RHSCst, BO->getName()), I);
3039 return BinaryOperator::create(I.getOpcode(), NewRem,
3040 Constant::getNullValue(UTy));
3041 }
Chris Lattner22d00a82005-08-02 19:16:58 +00003042 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003043 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00003044
Chris Lattnerc992add2003-08-13 05:33:12 +00003045 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00003046 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3047 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00003048 if (BO->hasOneUse())
3049 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3050 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00003051 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003052 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3053 // efficiently invertible, or if the add has just this one use.
3054 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003055
Chris Lattnerc992add2003-08-13 05:33:12 +00003056 if (Value *NegVal = dyn_castNegVal(BOp1))
3057 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3058 else if (Value *NegVal = dyn_castNegVal(BOp0))
3059 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003060 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003061 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3062 BO->setName("");
3063 InsertNewInstBefore(Neg, I);
3064 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3065 }
3066 }
3067 break;
3068 case Instruction::Xor:
3069 // For the xor case, we can xor two constants together, eliminating
3070 // the explicit xor.
3071 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3072 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003073 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00003074
3075 // FALLTHROUGH
3076 case Instruction::Sub:
3077 // Replace (([sub|xor] A, B) != 0) with (A != B)
3078 if (CI->isNullValue())
3079 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3080 BO->getOperand(1));
3081 break;
3082
3083 case Instruction::Or:
3084 // If bits are being or'd in that are not present in the constant we
3085 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003086 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003087 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003088 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003089 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003090 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003091 break;
3092
3093 case Instruction::And:
3094 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003095 // If bits are being compared against that are and'd out, then the
3096 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003097 if (!ConstantExpr::getAnd(CI,
3098 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003099 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00003100
Chris Lattner35167c32004-06-09 07:59:58 +00003101 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00003102 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00003103 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3104 Instruction::SetNE, Op0,
3105 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00003106
Chris Lattnerc992add2003-08-13 05:33:12 +00003107 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3108 // to be a signed value as appropriate.
3109 if (isSignBit(BOC)) {
3110 Value *X = BO->getOperand(0);
3111 // If 'X' is not signed, insert a cast now...
3112 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00003113 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003114 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00003115 }
3116 return new SetCondInst(isSetNE ? Instruction::SetLT :
3117 Instruction::SetGE, X,
3118 Constant::getNullValue(X->getType()));
3119 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003120
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003121 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00003122 if (CI->isNullValue() && isHighOnes(BOC)) {
3123 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003124 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003125
3126 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003127 if (NegX->getType()->isSigned()) {
3128 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3129 X = InsertCastBefore(X, DestTy, I);
3130 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003131 }
3132
3133 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003134 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003135 }
3136
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003137 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003138 default: break;
3139 }
3140 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00003141 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00003142 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00003143 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3144 Value *CastOp = Cast->getOperand(0);
3145 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003146 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00003147 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003148 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003149 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00003150 "Source and destination signednesses should differ!");
3151 if (Cast->getType()->isSigned()) {
3152 // If this is a signed comparison, check for comparisons in the
3153 // vicinity of zero.
3154 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3155 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003156 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003157 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003158 else if (I.getOpcode() == Instruction::SetGT &&
3159 cast<ConstantSInt>(CI)->getValue() == -1)
3160 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003161 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003162 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003163 } else {
3164 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3165 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003166 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00003167 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003168 return BinaryOperator::createSetGT(CastOp,
3169 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003170 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003171 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00003172 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003173 return BinaryOperator::createSetLT(CastOp,
3174 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003175 }
3176 }
3177 }
Chris Lattnere967b342003-06-04 05:10:11 +00003178 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003179 }
3180
Chris Lattner77c32c32005-04-23 15:31:55 +00003181 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3182 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3183 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3184 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00003185 case Instruction::GetElementPtr:
3186 if (RHSC->isNullValue()) {
3187 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3188 bool isAllZeros = true;
3189 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3190 if (!isa<Constant>(LHSI->getOperand(i)) ||
3191 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3192 isAllZeros = false;
3193 break;
3194 }
3195 if (isAllZeros)
3196 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3197 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3198 }
3199 break;
3200
Chris Lattner77c32c32005-04-23 15:31:55 +00003201 case Instruction::PHI:
3202 if (Instruction *NV = FoldOpIntoPhi(I))
3203 return NV;
3204 break;
3205 case Instruction::Select:
3206 // If either operand of the select is a constant, we can fold the
3207 // comparison into the select arms, which will cause one to be
3208 // constant folded and the select turned into a bitwise or.
3209 Value *Op1 = 0, *Op2 = 0;
3210 if (LHSI->hasOneUse()) {
3211 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3212 // Fold the known value into the constant operand.
3213 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3214 // Insert a new SetCC of the other select operand.
3215 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3216 LHSI->getOperand(2), RHSC,
3217 I.getName()), I);
3218 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3219 // Fold the known value into the constant operand.
3220 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3221 // Insert a new SetCC of the other select operand.
3222 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3223 LHSI->getOperand(1), RHSC,
3224 I.getName()), I);
3225 }
3226 }
Jeff Cohen82639852005-04-23 21:38:35 +00003227
Chris Lattner77c32c32005-04-23 15:31:55 +00003228 if (Op1)
3229 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3230 break;
3231 }
3232 }
3233
Chris Lattner0798af32005-01-13 20:14:25 +00003234 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3235 if (User *GEP = dyn_castGetElementPtr(Op0))
3236 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3237 return NI;
3238 if (User *GEP = dyn_castGetElementPtr(Op1))
3239 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3240 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3241 return NI;
3242
Chris Lattner16930792003-11-03 04:25:02 +00003243 // Test to see if the operands of the setcc are casted versions of other
3244 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00003245 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3246 Value *CastOp0 = CI->getOperand(0);
3247 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00003248 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00003249 (I.getOpcode() == Instruction::SetEQ ||
3250 I.getOpcode() == Instruction::SetNE)) {
3251 // We keep moving the cast from the left operand over to the right
3252 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00003253 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003254
Chris Lattner16930792003-11-03 04:25:02 +00003255 // If operand #1 is a cast instruction, see if we can eliminate it as
3256 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00003257 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3258 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00003259 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00003260 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003261
Chris Lattner16930792003-11-03 04:25:02 +00003262 // If Op1 is a constant, we can fold the cast into the constant.
3263 if (Op1->getType() != Op0->getType())
3264 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3265 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3266 } else {
3267 // Otherwise, cast the RHS right before the setcc
3268 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3269 InsertNewInstBefore(cast<Instruction>(Op1), I);
3270 }
3271 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3272 }
3273
Chris Lattner6444c372003-11-03 05:17:03 +00003274 // Handle the special case of: setcc (cast bool to X), <cst>
3275 // This comes up when you have code like
3276 // int X = A < B;
3277 // if (X) ...
3278 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003279 // with a constant or another cast from the same type.
3280 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3281 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3282 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00003283 }
Chris Lattner113f4f42002-06-25 16:13:24 +00003284 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003285}
3286
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003287// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3288// We only handle extending casts so far.
3289//
3290Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3291 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3292 const Type *SrcTy = LHSCIOp->getType();
3293 const Type *DestTy = SCI.getOperand(0)->getType();
3294 Value *RHSCIOp;
3295
3296 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00003297 return 0;
3298
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003299 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3300 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3301 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3302
3303 // Is this a sign or zero extension?
3304 bool isSignSrc = SrcTy->isSigned();
3305 bool isSignDest = DestTy->isSigned();
3306
3307 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3308 // Not an extension from the same type?
3309 RHSCIOp = CI->getOperand(0);
3310 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3311 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3312 // Compute the constant that would happen if we truncated to SrcTy then
3313 // reextended to DestTy.
3314 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3315
3316 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3317 RHSCIOp = Res;
3318 } else {
3319 // If the value cannot be represented in the shorter type, we cannot emit
3320 // a simple comparison.
3321 if (SCI.getOpcode() == Instruction::SetEQ)
3322 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3323 if (SCI.getOpcode() == Instruction::SetNE)
3324 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3325
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003326 // Evaluate the comparison for LT.
3327 Value *Result;
3328 if (DestTy->isSigned()) {
3329 // We're performing a signed comparison.
3330 if (isSignSrc) {
3331 // Signed extend and signed comparison.
3332 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3333 Result = ConstantBool::False;
3334 else
3335 Result = ConstantBool::True; // X < (large) --> true
3336 } else {
3337 // Unsigned extend and signed comparison.
3338 if (cast<ConstantSInt>(CI)->getValue() < 0)
3339 Result = ConstantBool::False;
3340 else
3341 Result = ConstantBool::True;
3342 }
3343 } else {
3344 // We're performing an unsigned comparison.
3345 if (!isSignSrc) {
3346 // Unsigned extend & compare -> always true.
3347 Result = ConstantBool::True;
3348 } else {
3349 // We're performing an unsigned comp with a sign extended value.
3350 // This is true if the input is >= 0. [aka >s -1]
3351 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3352 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3353 NegOne, SCI.getName()), SCI);
3354 }
Reid Spencer279fa252004-11-28 21:31:15 +00003355 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003356
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003357 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003358 if (SCI.getOpcode() == Instruction::SetLT) {
3359 return ReplaceInstUsesWith(SCI, Result);
3360 } else {
3361 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3362 if (Constant *CI = dyn_cast<Constant>(Result))
3363 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3364 else
3365 return BinaryOperator::createNot(Result);
3366 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003367 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003368 } else {
3369 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00003370 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003371
Chris Lattner252a8452005-06-16 03:00:08 +00003372 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003373 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3374}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003375
Chris Lattnere8d6c602003-03-10 19:16:08 +00003376Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003377 assert(I.getOperand(1)->getType() == Type::UByteTy);
3378 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003379 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003380
3381 // shl X, 0 == X and shr X, 0 == X
3382 // shl 0, X == 0 and shr 0, X == 0
3383 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003384 Op0 == Constant::getNullValue(Op0->getType()))
3385 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003386
Chris Lattner81a7a232004-10-16 18:11:37 +00003387 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3388 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003389 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003390 else // undef << X -> 0 AND undef >>u X -> 0
3391 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3392 }
3393 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00003394 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00003395 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3396 else
3397 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3398 }
3399
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003400 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3401 if (!isLeftShift)
3402 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3403 if (CSI->isAllOnesValue())
3404 return ReplaceInstUsesWith(I, CSI);
3405
Chris Lattner183b3362004-04-09 19:05:30 +00003406 // Try to fold constant and into select arguments.
3407 if (isa<Constant>(Op0))
3408 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003409 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003410 return R;
3411
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00003412 // See if we can turn a signed shr into an unsigned shr.
3413 if (!isLeftShift && I.getType()->isSigned()) {
3414 if (MaskedValueIsZero(Op0, ConstantInt::getMinValue(I.getType()))) {
3415 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3416 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3417 I.getName()), I);
3418 return new CastInst(V, I.getType());
3419 }
3420 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003421
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003422 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003423 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3424 // of a signed value.
3425 //
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003426 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003427 if (CUI->getValue() >= TypeBits) {
3428 if (!Op0->getType()->isSigned() || isLeftShift)
3429 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3430 else {
3431 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3432 return &I;
3433 }
3434 }
Chris Lattner55f3d942002-09-10 23:04:09 +00003435
Chris Lattnerede3fe02003-08-13 04:18:28 +00003436 // ((X*C1) << C2) == (X * (C1 << C2))
3437 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3438 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3439 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003440 return BinaryOperator::createMul(BO->getOperand(0),
3441 ConstantExpr::getShl(BOOp, CUI));
Misha Brukmanb1c93172005-04-21 23:48:37 +00003442
Chris Lattner183b3362004-04-09 19:05:30 +00003443 // Try to fold constant and into select arguments.
3444 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003445 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003446 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003447 if (isa<PHINode>(Op0))
3448 if (Instruction *NV = FoldOpIntoPhi(I))
3449 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00003450
Chris Lattner86102b82005-01-01 16:22:27 +00003451 if (Op0->hasOneUse()) {
3452 // If this is a SHL of a sign-extending cast, see if we can turn the input
3453 // into a zero extending cast (a simple strength reduction).
3454 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3455 const Type *SrcTy = CI->getOperand(0)->getType();
3456 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003457 SrcTy->getPrimitiveSizeInBits() <
3458 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00003459 // We can change it to a zero extension if we are shifting out all of
3460 // the sign extended bits. To check this, form a mask of all of the
3461 // sign extend bits, then shift them left and see if we have anything
3462 // left.
3463 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3464 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3465 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3466 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3467 // If the shift is nuking all of the sign bits, change this to a
3468 // zero extension cast. To do this, cast the cast input to
3469 // unsigned, then to the requested size.
3470 Value *CastOp = CI->getOperand(0);
3471 Instruction *NC =
3472 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3473 CI->getName()+".uns");
3474 NC = InsertNewInstBefore(NC, I);
3475 // Finally, insert a replacement for CI.
3476 NC = new CastInst(NC, CI->getType(), CI->getName());
3477 CI->setName("");
3478 NC = InsertNewInstBefore(NC, I);
3479 WorkList.push_back(CI); // Delete CI later.
3480 I.setOperand(0, NC);
3481 return &I; // The SHL operand was modified.
3482 }
3483 }
3484 }
3485
Chris Lattner27cb9db2005-09-18 05:12:10 +00003486 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3487 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Jeff Cohen572910c2005-10-07 05:28:29 +00003488 Value *V1, *V2;
Chris Lattner797dee72005-09-18 06:30:59 +00003489 ConstantInt *CC;
Chris Lattner27cb9db2005-09-18 05:12:10 +00003490 switch (Op0BO->getOpcode()) {
3491 default: break;
3492 case Instruction::Add:
3493 case Instruction::And:
3494 case Instruction::Or:
3495 case Instruction::Xor:
3496 // These operators commute.
3497 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003498 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3499 match(Op0BO->getOperand(1),
3500 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == CUI) {
3501 Instruction *YS = new ShiftInst(Instruction::Shl,
3502 Op0BO->getOperand(0), CUI,
3503 Op0BO->getName());
3504 InsertNewInstBefore(YS, I); // (Y << C)
3505 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3506 V1,
3507 Op0BO->getOperand(1)->getName());
3508 InsertNewInstBefore(X, I); // (X + (Y << C))
3509 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3510 C2 = ConstantExpr::getShl(C2, CUI);
3511 return BinaryOperator::createAnd(X, C2);
3512 }
3513
3514 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
3515 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3516 match(Op0BO->getOperand(1),
3517 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3518 m_ConstantInt(CC))) && V2 == CUI &&
3519 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
3520 Instruction *YS = new ShiftInst(Instruction::Shl,
3521 Op0BO->getOperand(0), CUI,
3522 Op0BO->getName());
3523 InsertNewInstBefore(YS, I); // (Y << C)
3524 Instruction *XM =
3525 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, CUI),
3526 V1->getName()+".mask");
3527 InsertNewInstBefore(XM, I); // X & (CC << C)
3528
3529 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3530 }
3531
3532 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00003533 case Instruction::Sub:
3534 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003535 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3536 match(Op0BO->getOperand(0),
3537 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == CUI) {
3538 Instruction *YS = new ShiftInst(Instruction::Shl,
3539 Op0BO->getOperand(1), CUI,
3540 Op0BO->getName());
3541 InsertNewInstBefore(YS, I); // (Y << C)
3542 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3543 V1,
3544 Op0BO->getOperand(0)->getName());
3545 InsertNewInstBefore(X, I); // (X + (Y << C))
3546 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3547 C2 = ConstantExpr::getShl(C2, CUI);
3548 return BinaryOperator::createAnd(X, C2);
3549 }
3550
3551 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3552 match(Op0BO->getOperand(0),
3553 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3554 m_ConstantInt(CC))) && V2 == CUI &&
3555 cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
3556 Instruction *YS = new ShiftInst(Instruction::Shl,
3557 Op0BO->getOperand(1), CUI,
3558 Op0BO->getName());
3559 InsertNewInstBefore(YS, I); // (Y << C)
3560 Instruction *XM =
3561 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, CUI),
3562 V1->getName()+".mask");
3563 InsertNewInstBefore(XM, I); // X & (CC << C)
3564
3565 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3566 }
3567
Chris Lattner27cb9db2005-09-18 05:12:10 +00003568 break;
3569 }
3570
3571
3572 // If the operand is an bitwise operator with a constant RHS, and the
3573 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003574 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3575 bool isValid = true; // Valid only for And, Or, Xor
3576 bool highBitSet = false; // Transform if high bit of constant set?
3577
3578 switch (Op0BO->getOpcode()) {
3579 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003580 case Instruction::Add:
3581 isValid = isLeftShift;
3582 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003583 case Instruction::Or:
3584 case Instruction::Xor:
3585 highBitSet = false;
3586 break;
3587 case Instruction::And:
3588 highBitSet = true;
3589 break;
3590 }
3591
3592 // If this is a signed shift right, and the high bit is modified
3593 // by the logical operation, do not perform the transformation.
3594 // The highBitSet boolean indicates the value of the high bit of
3595 // the constant which would cause it to be modified for this
3596 // operation.
3597 //
3598 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3599 uint64_t Val = Op0C->getRawValue();
3600 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3601 }
3602
3603 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003604 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003605
3606 Instruction *NewShift =
3607 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3608 Op0BO->getName());
3609 Op0BO->setName("");
3610 InsertNewInstBefore(NewShift, I);
3611
3612 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3613 NewRHS);
3614 }
3615 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00003616 }
Chris Lattner86102b82005-01-01 16:22:27 +00003617 }
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003618
Chris Lattner3204d4e2003-07-24 17:52:58 +00003619 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003620 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00003621 if (ConstantUInt *ShiftAmt1C =
3622 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003623 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3624 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003625
Chris Lattner3204d4e2003-07-24 17:52:58 +00003626 // Check for (A << c1) << c2 and (A >> c1) >> c2
3627 if (I.getOpcode() == Op0SI->getOpcode()) {
3628 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003629 if (Op0->getType()->getPrimitiveSizeInBits() < Amt)
3630 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner3204d4e2003-07-24 17:52:58 +00003631 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3632 ConstantUInt::get(Type::UByteTy, Amt));
3633 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003634
Chris Lattnerab780df2003-07-24 18:38:56 +00003635 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3636 // signed types, we can only support the (A >> c1) << c2 configuration,
3637 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003638 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003639 // Calculate bitmask for what gets shifted off the edge...
3640 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003641 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003642 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003643 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003644 C = ConstantExpr::getShr(C, ShiftAmt1C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003645
Chris Lattner3204d4e2003-07-24 17:52:58 +00003646 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003647 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3648 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00003649 InsertNewInstBefore(Mask, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003650
Chris Lattner3204d4e2003-07-24 17:52:58 +00003651 // Figure out what flavor of shift we should use...
3652 if (ShiftAmt1 == ShiftAmt2)
3653 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3654 else if (ShiftAmt1 < ShiftAmt2) {
3655 return new ShiftInst(I.getOpcode(), Mask,
3656 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3657 } else {
3658 return new ShiftInst(Op0SI->getOpcode(), Mask,
3659 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3660 }
Chris Lattner0b3557f2005-09-24 23:43:33 +00003661 } else {
3662 // We can handle signed (X << C1) >> C2 if it's a sign extend. In
3663 // this case, C1 == C2 and C1 is 8, 16, or 32.
3664 if (ShiftAmt1 == ShiftAmt2) {
3665 const Type *SExtType = 0;
3666 switch (ShiftAmt1) {
3667 case 8 : SExtType = Type::SByteTy; break;
3668 case 16: SExtType = Type::ShortTy; break;
3669 case 32: SExtType = Type::IntTy; break;
3670 }
3671
3672 if (SExtType) {
3673 Instruction *NewTrunc = new CastInst(Op0SI->getOperand(0),
3674 SExtType, "sext");
3675 InsertNewInstBefore(NewTrunc, I);
3676 return new CastInst(NewTrunc, I.getType());
3677 }
3678 }
Chris Lattner3204d4e2003-07-24 17:52:58 +00003679 }
3680 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003681 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00003682
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003683 return 0;
3684}
3685
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003686enum CastType {
3687 Noop = 0,
3688 Truncate = 1,
3689 Signext = 2,
3690 Zeroext = 3
3691};
3692
3693/// getCastType - In the future, we will split the cast instruction into these
3694/// various types. Until then, we have to do the analysis here.
3695static CastType getCastType(const Type *Src, const Type *Dest) {
3696 assert(Src->isIntegral() && Dest->isIntegral() &&
3697 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003698 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3699 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003700
3701 if (SrcSize == DestSize) return Noop;
3702 if (SrcSize > DestSize) return Truncate;
3703 if (Src->isSigned()) return Signext;
3704 return Zeroext;
3705}
3706
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003707
Chris Lattner48a44f72002-05-02 17:06:02 +00003708// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3709// instruction.
3710//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003711static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00003712 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003713
Chris Lattner650b6da2002-08-02 20:00:25 +00003714 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00003715 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003716 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003717 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003718 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003719
Chris Lattner4fbad962004-07-21 04:27:24 +00003720 // If we are casting between pointer and integer types, treat pointers as
3721 // integers of the appropriate size for the code below.
3722 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3723 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3724 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003725
Chris Lattner48a44f72002-05-02 17:06:02 +00003726 // Allow free casting and conversion of sizes as long as the sign doesn't
3727 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003728 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003729 CastType FirstCast = getCastType(SrcTy, MidTy);
3730 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003731
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003732 // Capture the effect of these two casts. If the result is a legal cast,
3733 // the CastType is stored here, otherwise a special code is used.
3734 static const unsigned CastResult[] = {
3735 // First cast is noop
3736 0, 1, 2, 3,
3737 // First cast is a truncate
3738 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3739 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003740 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003741 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003742 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003743 };
3744
3745 unsigned Result = CastResult[FirstCast*4+SecondCast];
3746 switch (Result) {
3747 default: assert(0 && "Illegal table value!");
3748 case 0:
3749 case 1:
3750 case 2:
3751 case 3:
3752 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3753 // truncates, we could eliminate more casts.
3754 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3755 case 4:
3756 return false; // Not possible to eliminate this here.
3757 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00003758 // Sign or zero extend followed by truncate is always ok if the result
3759 // is a truncate or noop.
3760 CastType ResultCast = getCastType(SrcTy, DstTy);
3761 if (ResultCast == Noop || ResultCast == Truncate)
3762 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003763 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00003764 // result will match the sign/zeroextendness of the result.
3765 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00003766 }
Chris Lattner650b6da2002-08-02 20:00:25 +00003767 }
Chris Lattner48a44f72002-05-02 17:06:02 +00003768 return false;
3769}
3770
Chris Lattner11ffd592004-07-20 05:21:00 +00003771static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003772 if (V->getType() == Ty || isa<Constant>(V)) return false;
3773 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00003774 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3775 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003776 return false;
3777 return true;
3778}
3779
3780/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3781/// InsertBefore instruction. This is specialized a bit to avoid inserting
3782/// casts that are known to not do anything...
3783///
3784Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3785 Instruction *InsertBefore) {
3786 if (V->getType() == DestTy) return V;
3787 if (Constant *C = dyn_cast<Constant>(V))
3788 return ConstantExpr::getCast(C, DestTy);
3789
3790 CastInst *CI = new CastInst(V, DestTy, V->getName());
3791 InsertNewInstBefore(CI, *InsertBefore);
3792 return CI;
3793}
Chris Lattner48a44f72002-05-02 17:06:02 +00003794
Chris Lattner8f663e82005-10-29 04:36:15 +00003795/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
3796/// expression. If so, decompose it, returning some value X, such that Val is
3797/// X*Scale+Offset.
3798///
3799static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
3800 unsigned &Offset) {
3801 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
3802 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
3803 Offset = CI->getValue();
3804 Scale = 1;
3805 return ConstantUInt::get(Type::UIntTy, 0);
3806 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
3807 if (I->getNumOperands() == 2) {
3808 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
3809 if (I->getOpcode() == Instruction::Shl) {
3810 // This is a value scaled by '1 << the shift amt'.
3811 Scale = 1U << CUI->getValue();
3812 Offset = 0;
3813 return I->getOperand(0);
3814 } else if (I->getOpcode() == Instruction::Mul) {
3815 // This value is scaled by 'CUI'.
3816 Scale = CUI->getValue();
3817 Offset = 0;
3818 return I->getOperand(0);
3819 } else if (I->getOpcode() == Instruction::Add) {
3820 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
3821 // divisible by C2.
3822 unsigned SubScale;
3823 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
3824 Offset);
3825 Offset += CUI->getValue();
3826 if (SubScale > 1 && (Offset % SubScale == 0)) {
3827 Scale = SubScale;
3828 return SubVal;
3829 }
3830 }
3831 }
3832 }
3833 }
3834
3835 // Otherwise, we can't look past this.
3836 Scale = 1;
3837 Offset = 0;
3838 return Val;
3839}
3840
3841
Chris Lattner216be912005-10-24 06:03:58 +00003842/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
3843/// try to eliminate the cast by moving the type information into the alloc.
3844Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
3845 AllocationInst &AI) {
3846 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00003847 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00003848
Chris Lattnerac87beb2005-10-24 06:22:12 +00003849 // Remove any uses of AI that are dead.
3850 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
3851 std::vector<Instruction*> DeadUsers;
3852 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
3853 Instruction *User = cast<Instruction>(*UI++);
3854 if (isInstructionTriviallyDead(User)) {
3855 while (UI != E && *UI == User)
3856 ++UI; // If this instruction uses AI more than once, don't break UI.
3857
3858 // Add operands to the worklist.
3859 AddUsesToWorkList(*User);
3860 ++NumDeadInst;
3861 DEBUG(std::cerr << "IC: DCE: " << *User);
3862
3863 User->eraseFromParent();
3864 removeFromWorkList(User);
3865 }
3866 }
3867
Chris Lattner216be912005-10-24 06:03:58 +00003868 // Get the type really allocated and the type casted to.
3869 const Type *AllocElTy = AI.getAllocatedType();
3870 const Type *CastElTy = PTy->getElementType();
3871 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00003872
3873 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
3874 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
3875 if (CastElTyAlign < AllocElTyAlign) return 0;
3876
Chris Lattner46705b22005-10-24 06:35:18 +00003877 // If the allocation has multiple uses, only promote it if we are strictly
3878 // increasing the alignment of the resultant allocation. If we keep it the
3879 // same, we open the door to infinite loops of various kinds.
3880 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
3881
Chris Lattner216be912005-10-24 06:03:58 +00003882 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3883 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00003884 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00003885
Chris Lattner8270c332005-10-29 03:19:53 +00003886 // See if we can satisfy the modulus by pulling a scale out of the array
3887 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00003888 unsigned ArraySizeScale, ArrayOffset;
3889 Value *NumElements = // See if the array size is a decomposable linear expr.
3890 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
3891
Chris Lattner8270c332005-10-29 03:19:53 +00003892 // If we can now satisfy the modulus, by using a non-1 scale, we really can
3893 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00003894 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
3895 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00003896
Chris Lattner8270c332005-10-29 03:19:53 +00003897 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
3898 Value *Amt = 0;
3899 if (Scale == 1) {
3900 Amt = NumElements;
3901 } else {
3902 Amt = ConstantUInt::get(Type::UIntTy, Scale);
3903 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
3904 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
3905 else if (Scale != 1) {
3906 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
3907 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00003908 }
Chris Lattnerbb171802005-10-27 05:53:56 +00003909 }
3910
Chris Lattner8f663e82005-10-29 04:36:15 +00003911 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
3912 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
3913 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
3914 Amt = InsertNewInstBefore(Tmp, AI);
3915 }
3916
Chris Lattner216be912005-10-24 06:03:58 +00003917 std::string Name = AI.getName(); AI.setName("");
3918 AllocationInst *New;
3919 if (isa<MallocInst>(AI))
3920 New = new MallocInst(CastElTy, Amt, Name);
3921 else
3922 New = new AllocaInst(CastElTy, Amt, Name);
3923 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00003924
3925 // If the allocation has multiple uses, insert a cast and change all things
3926 // that used it to use the new cast. This will also hack on CI, but it will
3927 // die soon.
3928 if (!AI.hasOneUse()) {
3929 AddUsesToWorkList(AI);
3930 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
3931 InsertNewInstBefore(NewCast, AI);
3932 AI.replaceAllUsesWith(NewCast);
3933 }
Chris Lattner216be912005-10-24 06:03:58 +00003934 return ReplaceInstUsesWith(CI, New);
3935}
3936
3937
Chris Lattner48a44f72002-05-02 17:06:02 +00003938// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00003939//
Chris Lattner113f4f42002-06-25 16:13:24 +00003940Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00003941 Value *Src = CI.getOperand(0);
3942
Chris Lattner48a44f72002-05-02 17:06:02 +00003943 // If the user is casting a value to the same type, eliminate this cast
3944 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00003945 if (CI.getType() == Src->getType())
3946 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00003947
Chris Lattner81a7a232004-10-16 18:11:37 +00003948 if (isa<UndefValue>(Src)) // cast undef -> undef
3949 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3950
Chris Lattner48a44f72002-05-02 17:06:02 +00003951 // If casting the result of another cast instruction, try to eliminate this
3952 // one!
3953 //
Chris Lattner86102b82005-01-01 16:22:27 +00003954 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3955 Value *A = CSrc->getOperand(0);
3956 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3957 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003958 // This instruction now refers directly to the cast's src operand. This
3959 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00003960 CI.setOperand(0, CSrc->getOperand(0));
3961 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00003962 }
3963
Chris Lattner650b6da2002-08-02 20:00:25 +00003964 // If this is an A->B->A cast, and we are dealing with integral types, try
3965 // to convert this into a logical 'and' instruction.
3966 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00003967 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003968 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00003969 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003970 CSrc->getType()->getPrimitiveSizeInBits() <
3971 CI.getType()->getPrimitiveSizeInBits()&&
3972 A->getType()->getPrimitiveSizeInBits() ==
3973 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00003974 assert(CSrc->getType() != Type::ULongTy &&
3975 "Cannot have type bigger than ulong!");
Chris Lattner2f1457f2005-04-24 17:46:05 +00003976 uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
Chris Lattner86102b82005-01-01 16:22:27 +00003977 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3978 AndValue);
3979 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3980 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3981 if (And->getType() != CI.getType()) {
3982 And->setName(CSrc->getName()+".mask");
3983 InsertNewInstBefore(And, CI);
3984 And = new CastInst(And, CI.getType());
3985 }
3986 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00003987 }
3988 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003989
Chris Lattner03841652004-05-25 04:29:21 +00003990 // If this is a cast to bool, turn it into the appropriate setne instruction.
3991 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003992 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00003993 Constant::getNullValue(CI.getOperand(0)->getType()));
3994
Chris Lattnerd0d51602003-06-21 23:12:02 +00003995 // If casting the result of a getelementptr instruction with no offset, turn
3996 // this into a cast of the original pointer!
3997 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00003998 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00003999 bool AllZeroOperands = true;
4000 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4001 if (!isa<Constant>(GEP->getOperand(i)) ||
4002 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4003 AllZeroOperands = false;
4004 break;
4005 }
4006 if (AllZeroOperands) {
4007 CI.setOperand(0, GEP->getOperand(0));
4008 return &CI;
4009 }
4010 }
4011
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004012 // If we are casting a malloc or alloca to a pointer to a type of the same
4013 // size, rewrite the allocation instruction to allocate the "right" type.
4014 //
4015 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00004016 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4017 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004018
Chris Lattner86102b82005-01-01 16:22:27 +00004019 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4020 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4021 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004022 if (isa<PHINode>(Src))
4023 if (Instruction *NV = FoldOpIntoPhi(CI))
4024 return NV;
4025
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004026 // If the source value is an instruction with only this use, we can attempt to
4027 // propagate the cast into the instruction. Also, only handle integral types
4028 // for now.
4029 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004030 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004031 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4032 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004033 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4034 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004035
4036 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4037 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4038
4039 switch (SrcI->getOpcode()) {
4040 case Instruction::Add:
4041 case Instruction::Mul:
4042 case Instruction::And:
4043 case Instruction::Or:
4044 case Instruction::Xor:
4045 // If we are discarding information, or just changing the sign, rewrite.
4046 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4047 // Don't insert two casts if they cannot be eliminated. We allow two
4048 // casts to be inserted if the sizes are the same. This could only be
4049 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00004050 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4051 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004052 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4053 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4054 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4055 ->getOpcode(), Op0c, Op1c);
4056 }
4057 }
Chris Lattner72086162005-05-06 02:07:39 +00004058
4059 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4060 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4061 Op1 == ConstantBool::True &&
4062 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4063 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4064 return BinaryOperator::createXor(New,
4065 ConstantInt::get(CI.getType(), 1));
4066 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004067 break;
4068 case Instruction::Shl:
4069 // Allow changing the sign of the source operand. Do not allow changing
4070 // the size of the shift, UNLESS the shift amount is a constant. We
4071 // mush not change variable sized shifts to a smaller size, because it
4072 // is undefined to shift more bits out than exist in the value.
4073 if (DestBitSize == SrcBitSize ||
4074 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4075 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4076 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4077 }
4078 break;
Chris Lattner87380412005-05-06 04:18:52 +00004079 case Instruction::Shr:
4080 // If this is a signed shr, and if all bits shifted in are about to be
4081 // truncated off, turn it into an unsigned shr to allow greater
4082 // simplifications.
4083 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4084 isa<ConstantInt>(Op1)) {
4085 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4086 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4087 // Convert to unsigned.
4088 Value *N1 = InsertOperandCastBefore(Op0,
4089 Op0->getType()->getUnsignedVersion(), &CI);
4090 // Insert the new shift, which is now unsigned.
4091 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4092 Op1, Src->getName()), CI);
4093 return new CastInst(N1, CI.getType());
4094 }
4095 }
4096 break;
4097
Chris Lattner809dfac2005-05-04 19:10:26 +00004098 case Instruction::SetNE:
Chris Lattner809dfac2005-05-04 19:10:26 +00004099 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004100 if (Op1C->getRawValue() == 0) {
4101 // If the input only has the low bit set, simplify directly.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004102 Constant *Not1 =
Chris Lattner809dfac2005-05-04 19:10:26 +00004103 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattner4c2d3782005-05-06 01:53:19 +00004104 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattner809dfac2005-05-04 19:10:26 +00004105 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4106 if (CI.getType() == Op0->getType())
4107 return ReplaceInstUsesWith(CI, Op0);
4108 else
4109 return new CastInst(Op0, CI.getType());
4110 }
Chris Lattner4c2d3782005-05-06 01:53:19 +00004111
4112 // If the input is an and with a single bit, shift then simplify.
4113 ConstantInt *AndRHS;
4114 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
4115 if (AndRHS->getRawValue() &&
4116 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattner22d00a82005-08-02 19:16:58 +00004117 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattner4c2d3782005-05-06 01:53:19 +00004118 // Perform an unsigned shr by shiftamt. Convert input to
4119 // unsigned if it is signed.
4120 Value *In = Op0;
4121 if (In->getType()->isSigned())
4122 In = InsertNewInstBefore(new CastInst(In,
4123 In->getType()->getUnsignedVersion(), In->getName()),CI);
4124 // Insert the shift to put the result in the low bit.
4125 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4126 ConstantInt::get(Type::UByteTy, ShiftAmt),
4127 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00004128 if (CI.getType() == In->getType())
4129 return ReplaceInstUsesWith(CI, In);
4130 else
4131 return new CastInst(In, CI.getType());
4132 }
4133 }
4134 }
4135 break;
4136 case Instruction::SetEQ:
4137 // We if we are just checking for a seteq of a single bit and casting it
4138 // to an integer. If so, shift the bit to the appropriate place then
4139 // cast to integer to avoid the comparison.
4140 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4141 // Is Op1C a power of two or zero?
4142 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
4143 // cast (X == 1) to int -> X iff X has only the low bit set.
4144 if (Op1C->getRawValue() == 1) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004145 Constant *Not1 =
Chris Lattner4c2d3782005-05-06 01:53:19 +00004146 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
4147 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4148 if (CI.getType() == Op0->getType())
4149 return ReplaceInstUsesWith(CI, Op0);
4150 else
4151 return new CastInst(Op0, CI.getType());
4152 }
4153 }
Chris Lattner809dfac2005-05-04 19:10:26 +00004154 }
4155 }
4156 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004157 }
4158 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004159
Chris Lattner260ab202002-04-18 17:39:14 +00004160 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00004161}
4162
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004163/// GetSelectFoldableOperands - We want to turn code that looks like this:
4164/// %C = or %A, %B
4165/// %D = select %cond, %C, %A
4166/// into:
4167/// %C = select %cond, %B, 0
4168/// %D = or %A, %C
4169///
4170/// Assuming that the specified instruction is an operand to the select, return
4171/// a bitmask indicating which operands of this instruction are foldable if they
4172/// equal the other incoming value of the select.
4173///
4174static unsigned GetSelectFoldableOperands(Instruction *I) {
4175 switch (I->getOpcode()) {
4176 case Instruction::Add:
4177 case Instruction::Mul:
4178 case Instruction::And:
4179 case Instruction::Or:
4180 case Instruction::Xor:
4181 return 3; // Can fold through either operand.
4182 case Instruction::Sub: // Can only fold on the amount subtracted.
4183 case Instruction::Shl: // Can only fold on the shift amount.
4184 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00004185 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004186 default:
4187 return 0; // Cannot fold
4188 }
4189}
4190
4191/// GetSelectFoldableConstant - For the same transformation as the previous
4192/// function, return the identity constant that goes into the select.
4193static Constant *GetSelectFoldableConstant(Instruction *I) {
4194 switch (I->getOpcode()) {
4195 default: assert(0 && "This cannot happen!"); abort();
4196 case Instruction::Add:
4197 case Instruction::Sub:
4198 case Instruction::Or:
4199 case Instruction::Xor:
4200 return Constant::getNullValue(I->getType());
4201 case Instruction::Shl:
4202 case Instruction::Shr:
4203 return Constant::getNullValue(Type::UByteTy);
4204 case Instruction::And:
4205 return ConstantInt::getAllOnesValue(I->getType());
4206 case Instruction::Mul:
4207 return ConstantInt::get(I->getType(), 1);
4208 }
4209}
4210
Chris Lattner411336f2005-01-19 21:50:18 +00004211/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4212/// have the same opcode and only one use each. Try to simplify this.
4213Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4214 Instruction *FI) {
4215 if (TI->getNumOperands() == 1) {
4216 // If this is a non-volatile load or a cast from the same type,
4217 // merge.
4218 if (TI->getOpcode() == Instruction::Cast) {
4219 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4220 return 0;
4221 } else {
4222 return 0; // unknown unary op.
4223 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004224
Chris Lattner411336f2005-01-19 21:50:18 +00004225 // Fold this by inserting a select from the input values.
4226 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4227 FI->getOperand(0), SI.getName()+".v");
4228 InsertNewInstBefore(NewSI, SI);
4229 return new CastInst(NewSI, TI->getType());
4230 }
4231
4232 // Only handle binary operators here.
4233 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4234 return 0;
4235
4236 // Figure out if the operations have any operands in common.
4237 Value *MatchOp, *OtherOpT, *OtherOpF;
4238 bool MatchIsOpZero;
4239 if (TI->getOperand(0) == FI->getOperand(0)) {
4240 MatchOp = TI->getOperand(0);
4241 OtherOpT = TI->getOperand(1);
4242 OtherOpF = FI->getOperand(1);
4243 MatchIsOpZero = true;
4244 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4245 MatchOp = TI->getOperand(1);
4246 OtherOpT = TI->getOperand(0);
4247 OtherOpF = FI->getOperand(0);
4248 MatchIsOpZero = false;
4249 } else if (!TI->isCommutative()) {
4250 return 0;
4251 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4252 MatchOp = TI->getOperand(0);
4253 OtherOpT = TI->getOperand(1);
4254 OtherOpF = FI->getOperand(0);
4255 MatchIsOpZero = true;
4256 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4257 MatchOp = TI->getOperand(1);
4258 OtherOpT = TI->getOperand(0);
4259 OtherOpF = FI->getOperand(1);
4260 MatchIsOpZero = true;
4261 } else {
4262 return 0;
4263 }
4264
4265 // If we reach here, they do have operations in common.
4266 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4267 OtherOpF, SI.getName()+".v");
4268 InsertNewInstBefore(NewSI, SI);
4269
4270 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4271 if (MatchIsOpZero)
4272 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4273 else
4274 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4275 } else {
4276 if (MatchIsOpZero)
4277 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4278 else
4279 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4280 }
4281}
4282
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004283Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00004284 Value *CondVal = SI.getCondition();
4285 Value *TrueVal = SI.getTrueValue();
4286 Value *FalseVal = SI.getFalseValue();
4287
4288 // select true, X, Y -> X
4289 // select false, X, Y -> Y
4290 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004291 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00004292 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004293 else {
4294 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00004295 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004296 }
Chris Lattner533bc492004-03-30 19:37:13 +00004297
4298 // select C, X, X -> X
4299 if (TrueVal == FalseVal)
4300 return ReplaceInstUsesWith(SI, TrueVal);
4301
Chris Lattner81a7a232004-10-16 18:11:37 +00004302 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4303 return ReplaceInstUsesWith(SI, FalseVal);
4304 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4305 return ReplaceInstUsesWith(SI, TrueVal);
4306 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4307 if (isa<Constant>(TrueVal))
4308 return ReplaceInstUsesWith(SI, TrueVal);
4309 else
4310 return ReplaceInstUsesWith(SI, FalseVal);
4311 }
4312
Chris Lattner1c631e82004-04-08 04:43:23 +00004313 if (SI.getType() == Type::BoolTy)
4314 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4315 if (C == ConstantBool::True) {
4316 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004317 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004318 } else {
4319 // Change: A = select B, false, C --> A = and !B, C
4320 Value *NotCond =
4321 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4322 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004323 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004324 }
4325 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4326 if (C == ConstantBool::False) {
4327 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004328 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004329 } else {
4330 // Change: A = select B, C, true --> A = or !B, C
4331 Value *NotCond =
4332 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4333 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004334 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004335 }
4336 }
4337
Chris Lattner183b3362004-04-09 19:05:30 +00004338 // Selecting between two integer constants?
4339 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4340 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4341 // select C, 1, 0 -> cast C to int
4342 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4343 return new CastInst(CondVal, SI.getType());
4344 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4345 // select C, 0, 1 -> cast !C to int
4346 Value *NotCond =
4347 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00004348 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00004349 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00004350 }
Chris Lattner35167c32004-06-09 07:59:58 +00004351
4352 // If one of the constants is zero (we know they can't both be) and we
4353 // have a setcc instruction with zero, and we have an 'and' with the
4354 // non-constant value, eliminate this whole mess. This corresponds to
4355 // cases like this: ((X & 27) ? 27 : 0)
4356 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4357 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4358 if ((IC->getOpcode() == Instruction::SetEQ ||
4359 IC->getOpcode() == Instruction::SetNE) &&
4360 isa<ConstantInt>(IC->getOperand(1)) &&
4361 cast<Constant>(IC->getOperand(1))->isNullValue())
4362 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4363 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004364 isa<ConstantInt>(ICA->getOperand(1)) &&
4365 (ICA->getOperand(1) == TrueValC ||
4366 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00004367 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4368 // Okay, now we know that everything is set up, we just don't
4369 // know whether we have a setne or seteq and whether the true or
4370 // false val is the zero.
4371 bool ShouldNotVal = !TrueValC->isNullValue();
4372 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4373 Value *V = ICA;
4374 if (ShouldNotVal)
4375 V = InsertNewInstBefore(BinaryOperator::create(
4376 Instruction::Xor, V, ICA->getOperand(1)), SI);
4377 return ReplaceInstUsesWith(SI, V);
4378 }
Chris Lattner533bc492004-03-30 19:37:13 +00004379 }
Chris Lattner623fba12004-04-10 22:21:27 +00004380
4381 // See if we are selecting two values based on a comparison of the two values.
4382 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4383 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4384 // Transform (X == Y) ? X : Y -> Y
4385 if (SCI->getOpcode() == Instruction::SetEQ)
4386 return ReplaceInstUsesWith(SI, FalseVal);
4387 // Transform (X != Y) ? X : Y -> X
4388 if (SCI->getOpcode() == Instruction::SetNE)
4389 return ReplaceInstUsesWith(SI, TrueVal);
4390 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4391
4392 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4393 // Transform (X == Y) ? Y : X -> X
4394 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00004395 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004396 // Transform (X != Y) ? Y : X -> Y
4397 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00004398 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004399 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4400 }
4401 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004402
Chris Lattnera04c9042005-01-13 22:52:24 +00004403 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4404 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4405 if (TI->hasOneUse() && FI->hasOneUse()) {
4406 bool isInverse = false;
4407 Instruction *AddOp = 0, *SubOp = 0;
4408
Chris Lattner411336f2005-01-19 21:50:18 +00004409 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4410 if (TI->getOpcode() == FI->getOpcode())
4411 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4412 return IV;
4413
4414 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4415 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00004416 if (TI->getOpcode() == Instruction::Sub &&
4417 FI->getOpcode() == Instruction::Add) {
4418 AddOp = FI; SubOp = TI;
4419 } else if (FI->getOpcode() == Instruction::Sub &&
4420 TI->getOpcode() == Instruction::Add) {
4421 AddOp = TI; SubOp = FI;
4422 }
4423
4424 if (AddOp) {
4425 Value *OtherAddOp = 0;
4426 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4427 OtherAddOp = AddOp->getOperand(1);
4428 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4429 OtherAddOp = AddOp->getOperand(0);
4430 }
4431
4432 if (OtherAddOp) {
4433 // So at this point we know we have:
4434 // select C, (add X, Y), (sub X, ?)
4435 // We can do the transform profitably if either 'Y' = '?' or '?' is
4436 // a constant.
4437 if (SubOp->getOperand(1) == AddOp ||
4438 isa<Constant>(SubOp->getOperand(1))) {
4439 Value *NegVal;
4440 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4441 NegVal = ConstantExpr::getNeg(C);
4442 } else {
4443 NegVal = InsertNewInstBefore(
4444 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4445 }
4446
Chris Lattner51726c42005-01-14 17:35:12 +00004447 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00004448 Value *NewFalseOp = NegVal;
4449 if (AddOp != TI)
4450 std::swap(NewTrueOp, NewFalseOp);
4451 Instruction *NewSel =
4452 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanb1c93172005-04-21 23:48:37 +00004453
Chris Lattnera04c9042005-01-13 22:52:24 +00004454 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00004455 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00004456 }
4457 }
4458 }
4459 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004460
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004461 // See if we can fold the select into one of our operands.
4462 if (SI.getType()->isInteger()) {
4463 // See the comment above GetSelectFoldableOperands for a description of the
4464 // transformation we are doing here.
4465 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4466 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4467 !isa<Constant>(FalseVal))
4468 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4469 unsigned OpToFold = 0;
4470 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4471 OpToFold = 1;
4472 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4473 OpToFold = 2;
4474 }
4475
4476 if (OpToFold) {
4477 Constant *C = GetSelectFoldableConstant(TVI);
4478 std::string Name = TVI->getName(); TVI->setName("");
4479 Instruction *NewSel =
4480 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4481 Name);
4482 InsertNewInstBefore(NewSel, SI);
4483 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4484 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4485 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4486 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4487 else {
4488 assert(0 && "Unknown instruction!!");
4489 }
4490 }
4491 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00004492
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004493 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4494 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4495 !isa<Constant>(TrueVal))
4496 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4497 unsigned OpToFold = 0;
4498 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4499 OpToFold = 1;
4500 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4501 OpToFold = 2;
4502 }
4503
4504 if (OpToFold) {
4505 Constant *C = GetSelectFoldableConstant(FVI);
4506 std::string Name = FVI->getName(); FVI->setName("");
4507 Instruction *NewSel =
4508 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4509 Name);
4510 InsertNewInstBefore(NewSel, SI);
4511 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4512 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4513 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4514 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4515 else {
4516 assert(0 && "Unknown instruction!!");
4517 }
4518 }
4519 }
4520 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00004521
4522 if (BinaryOperator::isNot(CondVal)) {
4523 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4524 SI.setOperand(1, FalseVal);
4525 SI.setOperand(2, TrueVal);
4526 return &SI;
4527 }
4528
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004529 return 0;
4530}
4531
4532
Chris Lattner970c33a2003-06-19 17:00:31 +00004533// CallInst simplification
4534//
4535Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00004536 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4537 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00004538 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
4539 bool Changed = false;
4540
4541 // memmove/cpy/set of zero bytes is a noop.
4542 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4543 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4544
4545 // FIXME: Increase alignment here.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004546
Chris Lattner00648e12004-10-12 04:52:52 +00004547 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4548 if (CI->getRawValue() == 1) {
4549 // Replace the instruction with just byte operations. We would
4550 // transform other cases to loads/stores, but we don't know if
4551 // alignment is sufficient.
4552 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004553 }
4554
Chris Lattner00648e12004-10-12 04:52:52 +00004555 // If we have a memmove and the source operation is a constant global,
4556 // then the source and dest pointers can't alias, so we can change this
4557 // into a call to memcpy.
4558 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
4559 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4560 if (GVSrc->isConstant()) {
4561 Module *M = CI.getParent()->getParent()->getParent();
4562 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4563 CI.getCalledFunction()->getFunctionType());
4564 CI.setOperand(0, MemCpy);
4565 Changed = true;
4566 }
4567
4568 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00004569 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
4570 // If this stoppoint is at the same source location as the previous
4571 // stoppoint in the chain, it is not needed.
4572 if (DbgStopPointInst *PrevSPI =
4573 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4574 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4575 SPI->getColNo() == PrevSPI->getColNo()) {
4576 SPI->replaceAllUsesWith(PrevSPI);
4577 return EraseInstFromFunction(CI);
4578 }
Chris Lattner00648e12004-10-12 04:52:52 +00004579 }
4580
Chris Lattneraec3d942003-10-07 22:32:43 +00004581 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00004582}
4583
4584// InvokeInst simplification
4585//
4586Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00004587 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00004588}
4589
Chris Lattneraec3d942003-10-07 22:32:43 +00004590// visitCallSite - Improvements for call and invoke instructions.
4591//
4592Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004593 bool Changed = false;
4594
4595 // If the callee is a constexpr cast of a function, attempt to move the cast
4596 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00004597 if (transformConstExprCastCall(CS)) return 0;
4598
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004599 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00004600
Chris Lattner61d9d812005-05-13 07:09:09 +00004601 if (Function *CalleeF = dyn_cast<Function>(Callee))
4602 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4603 Instruction *OldCall = CS.getInstruction();
4604 // If the call and callee calling conventions don't match, this call must
4605 // be unreachable, as the call is undefined.
4606 new StoreInst(ConstantBool::True,
4607 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4608 if (!OldCall->use_empty())
4609 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4610 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4611 return EraseInstFromFunction(*OldCall);
4612 return 0;
4613 }
4614
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004615 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4616 // This instruction is not reachable, just remove it. We insert a store to
4617 // undef so that we know that this code is not reachable, despite the fact
4618 // that we can't modify the CFG here.
4619 new StoreInst(ConstantBool::True,
4620 UndefValue::get(PointerType::get(Type::BoolTy)),
4621 CS.getInstruction());
4622
4623 if (!CS.getInstruction()->use_empty())
4624 CS.getInstruction()->
4625 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4626
4627 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4628 // Don't break the CFG, insert a dummy cond branch.
4629 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4630 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00004631 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004632 return EraseInstFromFunction(*CS.getInstruction());
4633 }
Chris Lattner81a7a232004-10-16 18:11:37 +00004634
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004635 const PointerType *PTy = cast<PointerType>(Callee->getType());
4636 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4637 if (FTy->isVarArg()) {
4638 // See if we can optimize any arguments passed through the varargs area of
4639 // the call.
4640 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4641 E = CS.arg_end(); I != E; ++I)
4642 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4643 // If this cast does not effect the value passed through the varargs
4644 // area, we can eliminate the use of the cast.
4645 Value *Op = CI->getOperand(0);
4646 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4647 *I = Op;
4648 Changed = true;
4649 }
4650 }
4651 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004652
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004653 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00004654}
4655
Chris Lattner970c33a2003-06-19 17:00:31 +00004656// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4657// attempt to move the cast to the arguments of the call/invoke.
4658//
4659bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4660 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4661 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00004662 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00004663 return false;
Reid Spencer87436872004-07-18 00:38:32 +00004664 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00004665 Instruction *Caller = CS.getInstruction();
4666
4667 // Okay, this is a cast from a function to a different type. Unless doing so
4668 // would cause a type conversion of one of our arguments, change this call to
4669 // be a direct call with arguments casted to the appropriate types.
4670 //
4671 const FunctionType *FT = Callee->getFunctionType();
4672 const Type *OldRetTy = Caller->getType();
4673
Chris Lattner1f7942f2004-01-14 06:06:08 +00004674 // Check to see if we are changing the return type...
4675 if (OldRetTy != FT->getReturnType()) {
4676 if (Callee->isExternal() &&
4677 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4678 !Caller->use_empty())
4679 return false; // Cannot transform this return value...
4680
4681 // If the callsite is an invoke instruction, and the return value is used by
4682 // a PHI node in a successor, we cannot change the return type of the call
4683 // because there is no place to put the cast instruction (without breaking
4684 // the critical edge). Bail out in this case.
4685 if (!Caller->use_empty())
4686 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4687 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4688 UI != E; ++UI)
4689 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4690 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004691 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00004692 return false;
4693 }
Chris Lattner970c33a2003-06-19 17:00:31 +00004694
4695 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4696 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004697
Chris Lattner970c33a2003-06-19 17:00:31 +00004698 CallSite::arg_iterator AI = CS.arg_begin();
4699 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4700 const Type *ParamTy = FT->getParamType(i);
4701 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004702 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00004703 }
4704
4705 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4706 Callee->isExternal())
4707 return false; // Do not delete arguments unless we have a function body...
4708
4709 // Okay, we decided that this is a safe thing to do: go ahead and start
4710 // inserting cast instructions as necessary...
4711 std::vector<Value*> Args;
4712 Args.reserve(NumActualArgs);
4713
4714 AI = CS.arg_begin();
4715 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4716 const Type *ParamTy = FT->getParamType(i);
4717 if ((*AI)->getType() == ParamTy) {
4718 Args.push_back(*AI);
4719 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00004720 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4721 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00004722 }
4723 }
4724
4725 // If the function takes more arguments than the call was taking, add them
4726 // now...
4727 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4728 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4729
4730 // If we are removing arguments to the function, emit an obnoxious warning...
4731 if (FT->getNumParams() < NumActualArgs)
4732 if (!FT->isVarArg()) {
4733 std::cerr << "WARNING: While resolving call to function '"
4734 << Callee->getName() << "' arguments were dropped!\n";
4735 } else {
4736 // Add all of the arguments in their promoted form to the arg list...
4737 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4738 const Type *PTy = getPromotedType((*AI)->getType());
4739 if (PTy != (*AI)->getType()) {
4740 // Must promote to pass through va_arg area!
4741 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4742 InsertNewInstBefore(Cast, *Caller);
4743 Args.push_back(Cast);
4744 } else {
4745 Args.push_back(*AI);
4746 }
4747 }
4748 }
4749
4750 if (FT->getReturnType() == Type::VoidTy)
4751 Caller->setName(""); // Void type should not have a name...
4752
4753 Instruction *NC;
4754 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004755 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00004756 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00004757 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004758 } else {
4759 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00004760 if (cast<CallInst>(Caller)->isTailCall())
4761 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00004762 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004763 }
4764
4765 // Insert a cast of the return type as necessary...
4766 Value *NV = NC;
4767 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4768 if (NV->getType() != Type::VoidTy) {
4769 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00004770
4771 // If this is an invoke instruction, we should insert it after the first
4772 // non-phi, instruction in the normal successor block.
4773 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4774 BasicBlock::iterator I = II->getNormalDest()->begin();
4775 while (isa<PHINode>(I)) ++I;
4776 InsertNewInstBefore(NC, *I);
4777 } else {
4778 // Otherwise, it's a call, just insert cast right after the call instr
4779 InsertNewInstBefore(NC, *Caller);
4780 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004781 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00004782 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00004783 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00004784 }
4785 }
4786
4787 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4788 Caller->replaceAllUsesWith(NV);
4789 Caller->getParent()->getInstList().erase(Caller);
4790 removeFromWorkList(Caller);
4791 return true;
4792}
4793
4794
Chris Lattner7515cab2004-11-14 19:13:23 +00004795// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4796// operator and they all are only used by the PHI, PHI together their
4797// inputs, and do the operation once, to the result of the PHI.
4798Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4799 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4800
4801 // Scan the instruction, looking for input operations that can be folded away.
4802 // If all input operands to the phi are the same instruction (e.g. a cast from
4803 // the same type or "+42") we can pull the operation through the PHI, reducing
4804 // code size and simplifying code.
4805 Constant *ConstantOp = 0;
4806 const Type *CastSrcTy = 0;
4807 if (isa<CastInst>(FirstInst)) {
4808 CastSrcTy = FirstInst->getOperand(0)->getType();
4809 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4810 // Can fold binop or shift if the RHS is a constant.
4811 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4812 if (ConstantOp == 0) return 0;
4813 } else {
4814 return 0; // Cannot fold this operation.
4815 }
4816
4817 // Check to see if all arguments are the same operation.
4818 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4819 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4820 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4821 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4822 return 0;
4823 if (CastSrcTy) {
4824 if (I->getOperand(0)->getType() != CastSrcTy)
4825 return 0; // Cast operation must match.
4826 } else if (I->getOperand(1) != ConstantOp) {
4827 return 0;
4828 }
4829 }
4830
4831 // Okay, they are all the same operation. Create a new PHI node of the
4832 // correct type, and PHI together all of the LHS's of the instructions.
4833 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4834 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00004835 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00004836
4837 Value *InVal = FirstInst->getOperand(0);
4838 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00004839
4840 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00004841 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4842 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4843 if (NewInVal != InVal)
4844 InVal = 0;
4845 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4846 }
4847
4848 Value *PhiVal;
4849 if (InVal) {
4850 // The new PHI unions all of the same values together. This is really
4851 // common, so we handle it intelligently here for compile-time speed.
4852 PhiVal = InVal;
4853 delete NewPN;
4854 } else {
4855 InsertNewInstBefore(NewPN, PN);
4856 PhiVal = NewPN;
4857 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004858
Chris Lattner7515cab2004-11-14 19:13:23 +00004859 // Insert and return the new operation.
4860 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004861 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00004862 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004863 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004864 else
4865 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00004866 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004867}
Chris Lattner48a44f72002-05-02 17:06:02 +00004868
Chris Lattner71536432005-01-17 05:10:15 +00004869/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4870/// that is dead.
4871static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4872 if (PN->use_empty()) return true;
4873 if (!PN->hasOneUse()) return false;
4874
4875 // Remember this node, and if we find the cycle, return.
4876 if (!PotentiallyDeadPHIs.insert(PN).second)
4877 return true;
4878
4879 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4880 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004881
Chris Lattner71536432005-01-17 05:10:15 +00004882 return false;
4883}
4884
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004885// PHINode simplification
4886//
Chris Lattner113f4f42002-06-25 16:13:24 +00004887Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00004888 if (Value *V = PN.hasConstantValue())
4889 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00004890
4891 // If the only user of this instruction is a cast instruction, and all of the
4892 // incoming values are constants, change this PHI to merge together the casted
4893 // constants.
4894 if (PN.hasOneUse())
4895 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4896 if (CI->getType() != PN.getType()) { // noop casts will be folded
4897 bool AllConstant = true;
4898 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4899 if (!isa<Constant>(PN.getIncomingValue(i))) {
4900 AllConstant = false;
4901 break;
4902 }
4903 if (AllConstant) {
4904 // Make a new PHI with all casted values.
4905 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4906 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4907 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4908 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4909 PN.getIncomingBlock(i));
4910 }
4911
4912 // Update the cast instruction.
4913 CI->setOperand(0, New);
4914 WorkList.push_back(CI); // revisit the cast instruction to fold.
4915 WorkList.push_back(New); // Make sure to revisit the new Phi
4916 return &PN; // PN is now dead!
4917 }
4918 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004919
4920 // If all PHI operands are the same operation, pull them through the PHI,
4921 // reducing code size.
4922 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4923 PN.getIncomingValue(0)->hasOneUse())
4924 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4925 return Result;
4926
Chris Lattner71536432005-01-17 05:10:15 +00004927 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4928 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4929 // PHI)... break the cycle.
4930 if (PN.hasOneUse())
4931 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4932 std::set<PHINode*> PotentiallyDeadPHIs;
4933 PotentiallyDeadPHIs.insert(&PN);
4934 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4935 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4936 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004937
Chris Lattner91daeb52003-12-19 05:58:40 +00004938 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004939}
4940
Chris Lattner69193f92004-04-05 01:30:19 +00004941static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4942 Instruction *InsertPoint,
4943 InstCombiner *IC) {
4944 unsigned PS = IC->getTargetData().getPointerSize();
4945 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00004946 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4947 // We must insert a cast to ensure we sign-extend.
4948 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4949 V->getName()), *InsertPoint);
4950 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4951 *InsertPoint);
4952}
4953
Chris Lattner48a44f72002-05-02 17:06:02 +00004954
Chris Lattner113f4f42002-06-25 16:13:24 +00004955Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004956 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00004957 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00004958 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004959 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00004960 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004961
Chris Lattner81a7a232004-10-16 18:11:37 +00004962 if (isa<UndefValue>(GEP.getOperand(0)))
4963 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4964
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004965 bool HasZeroPointerIndex = false;
4966 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4967 HasZeroPointerIndex = C->isNullValue();
4968
4969 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00004970 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00004971
Chris Lattner69193f92004-04-05 01:30:19 +00004972 // Eliminate unneeded casts for indices.
4973 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00004974 gep_type_iterator GTI = gep_type_begin(GEP);
4975 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4976 if (isa<SequentialType>(*GTI)) {
4977 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4978 Value *Src = CI->getOperand(0);
4979 const Type *SrcTy = Src->getType();
4980 const Type *DestTy = CI->getType();
4981 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004982 if (SrcTy->getPrimitiveSizeInBits() ==
4983 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004984 // We can always eliminate a cast from ulong or long to the other.
4985 // We can always eliminate a cast from uint to int or the other on
4986 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004987 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00004988 MadeChange = true;
4989 GEP.setOperand(i, Src);
4990 }
4991 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4992 SrcTy->getPrimitiveSize() == 4) {
4993 // We can always eliminate a cast from int to [u]long. We can
4994 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4995 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004996 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004997 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004998 MadeChange = true;
4999 GEP.setOperand(i, Src);
5000 }
Chris Lattner69193f92004-04-05 01:30:19 +00005001 }
5002 }
5003 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00005004 // If we are using a wider index than needed for this platform, shrink it
5005 // to what we need. If the incoming value needs a cast instruction,
5006 // insert it. This explicit cast can make subsequent optimizations more
5007 // obvious.
5008 Value *Op = GEP.getOperand(i);
5009 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005010 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00005011 GEP.setOperand(i, ConstantExpr::getCast(C,
5012 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005013 MadeChange = true;
5014 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005015 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5016 Op->getName()), GEP);
5017 GEP.setOperand(i, Op);
5018 MadeChange = true;
5019 }
Chris Lattner44d0b952004-07-20 01:48:15 +00005020
5021 // If this is a constant idx, make sure to canonicalize it to be a signed
5022 // operand, otherwise CSE and other optimizations are pessimized.
5023 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5024 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5025 CUI->getType()->getSignedVersion()));
5026 MadeChange = true;
5027 }
Chris Lattner69193f92004-04-05 01:30:19 +00005028 }
5029 if (MadeChange) return &GEP;
5030
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005031 // Combine Indices - If the source pointer to this getelementptr instruction
5032 // is a getelementptr instruction, combine the indices of the two
5033 // getelementptr instructions into a single instruction.
5034 //
Chris Lattner57c67b02004-03-25 22:59:29 +00005035 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00005036 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00005037 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00005038
5039 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005040 // Note that if our source is a gep chain itself that we wait for that
5041 // chain to be resolved before we perform this transformation. This
5042 // avoids us creating a TON of code in some cases.
5043 //
5044 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5045 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5046 return 0; // Wait until our source is folded to completion.
5047
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005048 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00005049
5050 // Find out whether the last index in the source GEP is a sequential idx.
5051 bool EndsWithSequential = false;
5052 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5053 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00005054 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005055
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005056 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00005057 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00005058 // Replace: gep (gep %P, long B), long A, ...
5059 // With: T = long A+B; gep %P, T, ...
5060 //
Chris Lattner5f667a62004-05-07 22:09:22 +00005061 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00005062 if (SO1 == Constant::getNullValue(SO1->getType())) {
5063 Sum = GO1;
5064 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5065 Sum = SO1;
5066 } else {
5067 // If they aren't the same type, convert both to an integer of the
5068 // target's pointer size.
5069 if (SO1->getType() != GO1->getType()) {
5070 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5071 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5072 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5073 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5074 } else {
5075 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00005076 if (SO1->getType()->getPrimitiveSize() == PS) {
5077 // Convert GO1 to SO1's type.
5078 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5079
5080 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5081 // Convert SO1 to GO1's type.
5082 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5083 } else {
5084 const Type *PT = TD->getIntPtrType();
5085 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5086 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5087 }
5088 }
5089 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005090 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5091 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5092 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005093 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5094 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00005095 }
Chris Lattner69193f92004-04-05 01:30:19 +00005096 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005097
5098 // Recycle the GEP we already have if possible.
5099 if (SrcGEPOperands.size() == 2) {
5100 GEP.setOperand(0, SrcGEPOperands[0]);
5101 GEP.setOperand(1, Sum);
5102 return &GEP;
5103 } else {
5104 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5105 SrcGEPOperands.end()-1);
5106 Indices.push_back(Sum);
5107 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5108 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005109 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00005110 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005111 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005112 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00005113 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5114 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005115 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5116 }
5117
5118 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00005119 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005120
Chris Lattner5f667a62004-05-07 22:09:22 +00005121 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005122 // GEP of global variable. If all of the indices for this GEP are
5123 // constants, we can promote this to a constexpr instead of an instruction.
5124
5125 // Scan for nonconstants...
5126 std::vector<Constant*> Indices;
5127 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5128 for (; I != E && isa<Constant>(*I); ++I)
5129 Indices.push_back(cast<Constant>(*I));
5130
5131 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00005132 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005133
5134 // Replace all uses of the GEP with the new constexpr...
5135 return ReplaceInstUsesWith(GEP, CE);
5136 }
Chris Lattner567b81f2005-09-13 00:40:14 +00005137 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5138 if (!isa<PointerType>(X->getType())) {
5139 // Not interesting. Source pointer must be a cast from pointer.
5140 } else if (HasZeroPointerIndex) {
5141 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5142 // into : GEP [10 x ubyte]* X, long 0, ...
5143 //
5144 // This occurs when the program declares an array extern like "int X[];"
5145 //
5146 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5147 const PointerType *XTy = cast<PointerType>(X->getType());
5148 if (const ArrayType *XATy =
5149 dyn_cast<ArrayType>(XTy->getElementType()))
5150 if (const ArrayType *CATy =
5151 dyn_cast<ArrayType>(CPTy->getElementType()))
5152 if (CATy->getElementType() == XATy->getElementType()) {
5153 // At this point, we know that the cast source type is a pointer
5154 // to an array of the same type as the destination pointer
5155 // array. Because the array type is never stepped over (there
5156 // is a leading zero) we can fold the cast into this GEP.
5157 GEP.setOperand(0, X);
5158 return &GEP;
5159 }
5160 } else if (GEP.getNumOperands() == 2) {
5161 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00005162 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5163 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00005164 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5165 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5166 if (isa<ArrayType>(SrcElTy) &&
5167 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5168 TD->getTypeSize(ResElTy)) {
5169 Value *V = InsertNewInstBefore(
5170 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5171 GEP.getOperand(1), GEP.getName()), GEP);
5172 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005173 }
Chris Lattner2a893292005-09-13 18:36:04 +00005174
5175 // Transform things like:
5176 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5177 // (where tmp = 8*tmp2) into:
5178 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5179
5180 if (isa<ArrayType>(SrcElTy) &&
5181 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5182 uint64_t ArrayEltSize =
5183 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5184
5185 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5186 // allow either a mul, shift, or constant here.
5187 Value *NewIdx = 0;
5188 ConstantInt *Scale = 0;
5189 if (ArrayEltSize == 1) {
5190 NewIdx = GEP.getOperand(1);
5191 Scale = ConstantInt::get(NewIdx->getType(), 1);
5192 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00005193 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00005194 Scale = CI;
5195 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5196 if (Inst->getOpcode() == Instruction::Shl &&
5197 isa<ConstantInt>(Inst->getOperand(1))) {
5198 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5199 if (Inst->getType()->isSigned())
5200 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5201 else
5202 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5203 NewIdx = Inst->getOperand(0);
5204 } else if (Inst->getOpcode() == Instruction::Mul &&
5205 isa<ConstantInt>(Inst->getOperand(1))) {
5206 Scale = cast<ConstantInt>(Inst->getOperand(1));
5207 NewIdx = Inst->getOperand(0);
5208 }
5209 }
5210
5211 // If the index will be to exactly the right offset with the scale taken
5212 // out, perform the transformation.
5213 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5214 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5215 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00005216 (int64_t)C->getRawValue() /
5217 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00005218 else
5219 Scale = ConstantUInt::get(Scale->getType(),
5220 Scale->getRawValue() / ArrayEltSize);
5221 if (Scale->getRawValue() != 1) {
5222 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5223 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5224 NewIdx = InsertNewInstBefore(Sc, GEP);
5225 }
5226
5227 // Insert the new GEP instruction.
5228 Instruction *Idx =
5229 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5230 NewIdx, GEP.getName());
5231 Idx = InsertNewInstBefore(Idx, GEP);
5232 return new CastInst(Idx, GEP.getType());
5233 }
5234 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005235 }
Chris Lattnerca081252001-12-14 16:52:21 +00005236 }
5237
Chris Lattnerca081252001-12-14 16:52:21 +00005238 return 0;
5239}
5240
Chris Lattner1085bdf2002-11-04 16:18:53 +00005241Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5242 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5243 if (AI.isArrayAllocation()) // Check C != 1
5244 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5245 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005246 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00005247
5248 // Create and insert the replacement instruction...
5249 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00005250 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005251 else {
5252 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00005253 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005254 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005255
5256 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005257
Chris Lattner1085bdf2002-11-04 16:18:53 +00005258 // Scan to the end of the allocation instructions, to skip over a block of
5259 // allocas if possible...
5260 //
5261 BasicBlock::iterator It = New;
5262 while (isa<AllocationInst>(*It)) ++It;
5263
5264 // Now that I is pointing to the first non-allocation-inst in the block,
5265 // insert our getelementptr instruction...
5266 //
Chris Lattner809dfac2005-05-04 19:10:26 +00005267 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5268 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5269 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00005270
5271 // Now make everything use the getelementptr instead of the original
5272 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00005273 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00005274 } else if (isa<UndefValue>(AI.getArraySize())) {
5275 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00005276 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005277
5278 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5279 // Note that we only do this for alloca's, because malloc should allocate and
5280 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005281 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00005282 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00005283 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5284
Chris Lattner1085bdf2002-11-04 16:18:53 +00005285 return 0;
5286}
5287
Chris Lattner8427bff2003-12-07 01:24:23 +00005288Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5289 Value *Op = FI.getOperand(0);
5290
5291 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5292 if (CastInst *CI = dyn_cast<CastInst>(Op))
5293 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5294 FI.setOperand(0, CI->getOperand(0));
5295 return &FI;
5296 }
5297
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005298 // free undef -> unreachable.
5299 if (isa<UndefValue>(Op)) {
5300 // Insert a new store to null because we cannot modify the CFG here.
5301 new StoreInst(ConstantBool::True,
5302 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5303 return EraseInstFromFunction(FI);
5304 }
5305
Chris Lattnerf3a36602004-02-28 04:57:37 +00005306 // If we have 'free null' delete the instruction. This can happen in stl code
5307 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005308 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00005309 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00005310
Chris Lattner8427bff2003-12-07 01:24:23 +00005311 return 0;
5312}
5313
5314
Chris Lattner72684fe2005-01-31 05:51:45 +00005315/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00005316static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5317 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005318 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00005319
5320 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005321 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00005322 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005323
5324 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5325 // If the source is an array, the code below will not succeed. Check to
5326 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5327 // constants.
5328 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5329 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5330 if (ASrcTy->getNumElements() != 0) {
5331 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5332 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5333 SrcTy = cast<PointerType>(CastOp->getType());
5334 SrcPTy = SrcTy->getElementType();
5335 }
5336
5337 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00005338 // Do not allow turning this into a load of an integer, which is then
5339 // casted to a pointer, this pessimizes pointer analysis a lot.
5340 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005341 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005342 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00005343
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005344 // Okay, we are casting from one integer or pointer type to another of
5345 // the same size. Instead of casting the pointer before the load, cast
5346 // the result of the loaded value.
5347 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5348 CI->getName(),
5349 LI.isVolatile()),LI);
5350 // Now cast the result of the load.
5351 return new CastInst(NewLoad, LI.getType());
5352 }
Chris Lattner35e24772004-07-13 01:49:43 +00005353 }
5354 }
5355 return 0;
5356}
5357
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005358/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00005359/// from this value cannot trap. If it is not obviously safe to load from the
5360/// specified pointer, we do a quick local scan of the basic block containing
5361/// ScanFrom, to determine if the address is already accessed.
5362static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5363 // If it is an alloca or global variable, it is always safe to load from.
5364 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5365
5366 // Otherwise, be a little bit agressive by scanning the local block where we
5367 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005368 // from/to. If so, the previous load or store would have already trapped,
5369 // so there is no harm doing an extra load (also, CSE will later eliminate
5370 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00005371 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5372
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005373 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00005374 --BBI;
5375
5376 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5377 if (LI->getOperand(0) == V) return true;
5378 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5379 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005380
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005381 }
Chris Lattnere6f13092004-09-19 19:18:10 +00005382 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005383}
5384
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005385Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5386 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00005387
Chris Lattnera9d84e32005-05-01 04:24:53 +00005388 // load (cast X) --> cast (load X) iff safe
5389 if (CastInst *CI = dyn_cast<CastInst>(Op))
5390 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5391 return Res;
5392
5393 // None of the following transforms are legal for volatile loads.
5394 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005395
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005396 if (&LI.getParent()->front() != &LI) {
5397 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005398 // If the instruction immediately before this is a store to the same
5399 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005400 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5401 if (SI->getOperand(1) == LI.getOperand(0))
5402 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005403 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5404 if (LIB->getOperand(0) == LI.getOperand(0))
5405 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005406 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00005407
5408 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5409 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5410 isa<UndefValue>(GEPI->getOperand(0))) {
5411 // Insert a new store to null instruction before the load to indicate
5412 // that this code is not reachable. We do this instead of inserting
5413 // an unreachable instruction directly because we cannot modify the
5414 // CFG.
5415 new StoreInst(UndefValue::get(LI.getType()),
5416 Constant::getNullValue(Op->getType()), &LI);
5417 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5418 }
5419
Chris Lattner81a7a232004-10-16 18:11:37 +00005420 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00005421 // load null/undef -> undef
5422 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005423 // Insert a new store to null instruction before the load to indicate that
5424 // this code is not reachable. We do this instead of inserting an
5425 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00005426 new StoreInst(UndefValue::get(LI.getType()),
5427 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00005428 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005429 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005430
Chris Lattner81a7a232004-10-16 18:11:37 +00005431 // Instcombine load (constant global) into the value loaded.
5432 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5433 if (GV->isConstant() && !GV->isExternal())
5434 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00005435
Chris Lattner81a7a232004-10-16 18:11:37 +00005436 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5437 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5438 if (CE->getOpcode() == Instruction::GetElementPtr) {
5439 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5440 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00005441 if (Constant *V =
5442 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00005443 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00005444 if (CE->getOperand(0)->isNullValue()) {
5445 // Insert a new store to null instruction before the load to indicate
5446 // that this code is not reachable. We do this instead of inserting
5447 // an unreachable instruction directly because we cannot modify the
5448 // CFG.
5449 new StoreInst(UndefValue::get(LI.getType()),
5450 Constant::getNullValue(Op->getType()), &LI);
5451 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5452 }
5453
Chris Lattner81a7a232004-10-16 18:11:37 +00005454 } else if (CE->getOpcode() == Instruction::Cast) {
5455 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5456 return Res;
5457 }
5458 }
Chris Lattnere228ee52004-04-08 20:39:49 +00005459
Chris Lattnera9d84e32005-05-01 04:24:53 +00005460 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005461 // Change select and PHI nodes to select values instead of addresses: this
5462 // helps alias analysis out a lot, allows many others simplifications, and
5463 // exposes redundancy in the code.
5464 //
5465 // Note that we cannot do the transformation unless we know that the
5466 // introduced loads cannot trap! Something like this is valid as long as
5467 // the condition is always false: load (select bool %C, int* null, int* %G),
5468 // but it would not be valid if we transformed it to load from null
5469 // unconditionally.
5470 //
5471 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5472 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00005473 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5474 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005475 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00005476 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005477 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00005478 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005479 return new SelectInst(SI->getCondition(), V1, V2);
5480 }
5481
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00005482 // load (select (cond, null, P)) -> load P
5483 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5484 if (C->isNullValue()) {
5485 LI.setOperand(0, SI->getOperand(2));
5486 return &LI;
5487 }
5488
5489 // load (select (cond, P, null)) -> load P
5490 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5491 if (C->isNullValue()) {
5492 LI.setOperand(0, SI->getOperand(1));
5493 return &LI;
5494 }
5495
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005496 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5497 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00005498 bool Safe = PN->getParent() == LI.getParent();
5499
5500 // Scan all of the instructions between the PHI and the load to make
5501 // sure there are no instructions that might possibly alter the value
5502 // loaded from the PHI.
5503 if (Safe) {
5504 BasicBlock::iterator I = &LI;
5505 for (--I; !isa<PHINode>(I); --I)
5506 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5507 Safe = false;
5508 break;
5509 }
5510 }
5511
5512 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00005513 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00005514 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005515 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00005516
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005517 if (Safe) {
5518 // Create the PHI.
5519 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5520 InsertNewInstBefore(NewPN, *PN);
5521 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5522
5523 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5524 BasicBlock *BB = PN->getIncomingBlock(i);
5525 Value *&TheLoad = LoadMap[BB];
5526 if (TheLoad == 0) {
5527 Value *InVal = PN->getIncomingValue(i);
5528 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5529 InVal->getName()+".val"),
5530 *BB->getTerminator());
5531 }
5532 NewPN->addIncoming(TheLoad, BB);
5533 }
5534 return ReplaceInstUsesWith(LI, NewPN);
5535 }
5536 }
5537 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005538 return 0;
5539}
5540
Chris Lattner72684fe2005-01-31 05:51:45 +00005541/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5542/// when possible.
5543static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5544 User *CI = cast<User>(SI.getOperand(1));
5545 Value *CastOp = CI->getOperand(0);
5546
5547 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5548 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5549 const Type *SrcPTy = SrcTy->getElementType();
5550
5551 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5552 // If the source is an array, the code below will not succeed. Check to
5553 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5554 // constants.
5555 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5556 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5557 if (ASrcTy->getNumElements() != 0) {
5558 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5559 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5560 SrcTy = cast<PointerType>(CastOp->getType());
5561 SrcPTy = SrcTy->getElementType();
5562 }
5563
5564 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005565 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00005566 IC.getTargetData().getTypeSize(DestPTy)) {
5567
5568 // Okay, we are casting from one integer or pointer type to another of
5569 // the same size. Instead of casting the pointer before the store, cast
5570 // the value to be stored.
5571 Value *NewCast;
5572 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5573 NewCast = ConstantExpr::getCast(C, SrcPTy);
5574 else
5575 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5576 SrcPTy,
5577 SI.getOperand(0)->getName()+".c"), SI);
5578
5579 return new StoreInst(NewCast, CastOp);
5580 }
5581 }
5582 }
5583 return 0;
5584}
5585
Chris Lattner31f486c2005-01-31 05:36:43 +00005586Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5587 Value *Val = SI.getOperand(0);
5588 Value *Ptr = SI.getOperand(1);
5589
5590 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5591 removeFromWorkList(&SI);
5592 SI.eraseFromParent();
5593 ++NumCombined;
5594 return 0;
5595 }
5596
5597 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5598
5599 // store X, null -> turns into 'unreachable' in SimplifyCFG
5600 if (isa<ConstantPointerNull>(Ptr)) {
5601 if (!isa<UndefValue>(Val)) {
5602 SI.setOperand(0, UndefValue::get(Val->getType()));
5603 if (Instruction *U = dyn_cast<Instruction>(Val))
5604 WorkList.push_back(U); // Dropped a use.
5605 ++NumCombined;
5606 }
5607 return 0; // Do not modify these!
5608 }
5609
5610 // store undef, Ptr -> noop
5611 if (isa<UndefValue>(Val)) {
5612 removeFromWorkList(&SI);
5613 SI.eraseFromParent();
5614 ++NumCombined;
5615 return 0;
5616 }
5617
Chris Lattner72684fe2005-01-31 05:51:45 +00005618 // If the pointer destination is a cast, see if we can fold the cast into the
5619 // source instead.
5620 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5621 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5622 return Res;
5623 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5624 if (CE->getOpcode() == Instruction::Cast)
5625 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5626 return Res;
5627
Chris Lattner219175c2005-09-12 23:23:25 +00005628
5629 // If this store is the last instruction in the basic block, and if the block
5630 // ends with an unconditional branch, try to move it to the successor block.
5631 BasicBlock::iterator BBI = &SI; ++BBI;
5632 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5633 if (BI->isUnconditional()) {
5634 // Check to see if the successor block has exactly two incoming edges. If
5635 // so, see if the other predecessor contains a store to the same location.
5636 // if so, insert a PHI node (if needed) and move the stores down.
5637 BasicBlock *Dest = BI->getSuccessor(0);
5638
5639 pred_iterator PI = pred_begin(Dest);
5640 BasicBlock *Other = 0;
5641 if (*PI != BI->getParent())
5642 Other = *PI;
5643 ++PI;
5644 if (PI != pred_end(Dest)) {
5645 if (*PI != BI->getParent())
5646 if (Other)
5647 Other = 0;
5648 else
5649 Other = *PI;
5650 if (++PI != pred_end(Dest))
5651 Other = 0;
5652 }
5653 if (Other) { // If only one other pred...
5654 BBI = Other->getTerminator();
5655 // Make sure this other block ends in an unconditional branch and that
5656 // there is an instruction before the branch.
5657 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5658 BBI != Other->begin()) {
5659 --BBI;
5660 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5661
5662 // If this instruction is a store to the same location.
5663 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5664 // Okay, we know we can perform this transformation. Insert a PHI
5665 // node now if we need it.
5666 Value *MergedVal = OtherStore->getOperand(0);
5667 if (MergedVal != SI.getOperand(0)) {
5668 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5669 PN->reserveOperandSpace(2);
5670 PN->addIncoming(SI.getOperand(0), SI.getParent());
5671 PN->addIncoming(OtherStore->getOperand(0), Other);
5672 MergedVal = InsertNewInstBefore(PN, Dest->front());
5673 }
5674
5675 // Advance to a place where it is safe to insert the new store and
5676 // insert it.
5677 BBI = Dest->begin();
5678 while (isa<PHINode>(BBI)) ++BBI;
5679 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5680 OtherStore->isVolatile()), *BBI);
5681
5682 // Nuke the old stores.
5683 removeFromWorkList(&SI);
5684 removeFromWorkList(OtherStore);
5685 SI.eraseFromParent();
5686 OtherStore->eraseFromParent();
5687 ++NumCombined;
5688 return 0;
5689 }
5690 }
5691 }
5692 }
5693
Chris Lattner31f486c2005-01-31 05:36:43 +00005694 return 0;
5695}
5696
5697
Chris Lattner9eef8a72003-06-04 04:46:00 +00005698Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5699 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00005700 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00005701 BasicBlock *TrueDest;
5702 BasicBlock *FalseDest;
5703 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
5704 !isa<Constant>(X)) {
5705 // Swap Destinations and condition...
5706 BI.setCondition(X);
5707 BI.setSuccessor(0, FalseDest);
5708 BI.setSuccessor(1, TrueDest);
5709 return &BI;
5710 }
5711
5712 // Cannonicalize setne -> seteq
5713 Instruction::BinaryOps Op; Value *Y;
5714 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
5715 TrueDest, FalseDest)))
5716 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
5717 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
5718 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
5719 std::string Name = I->getName(); I->setName("");
5720 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
5721 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00005722 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00005723 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00005724 BI.setSuccessor(0, FalseDest);
5725 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00005726 removeFromWorkList(I);
5727 I->getParent()->getInstList().erase(I);
5728 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00005729 return &BI;
5730 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005731
Chris Lattner9eef8a72003-06-04 04:46:00 +00005732 return 0;
5733}
Chris Lattner1085bdf2002-11-04 16:18:53 +00005734
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005735Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5736 Value *Cond = SI.getCondition();
5737 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5738 if (I->getOpcode() == Instruction::Add)
5739 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5740 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5741 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00005742 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005743 AddRHS));
5744 SI.setOperand(0, I->getOperand(0));
5745 WorkList.push_back(I);
5746 return &SI;
5747 }
5748 }
5749 return 0;
5750}
5751
Chris Lattner99f48c62002-09-02 04:59:56 +00005752void InstCombiner::removeFromWorkList(Instruction *I) {
5753 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5754 WorkList.end());
5755}
5756
Chris Lattner39c98bb2004-12-08 23:43:58 +00005757
5758/// TryToSinkInstruction - Try to move the specified instruction from its
5759/// current block into the beginning of DestBlock, which can only happen if it's
5760/// safe to move the instruction past all of the instructions between it and the
5761/// end of its block.
5762static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5763 assert(I->hasOneUse() && "Invariants didn't hold!");
5764
Chris Lattnerc4f67e62005-10-27 17:13:11 +00005765 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
5766 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005767
Chris Lattner39c98bb2004-12-08 23:43:58 +00005768 // Do not sink alloca instructions out of the entry block.
5769 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5770 return false;
5771
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005772 // We can only sink load instructions if there is nothing between the load and
5773 // the end of block that could change the value.
5774 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005775 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5776 Scan != E; ++Scan)
5777 if (Scan->mayWriteToMemory())
5778 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005779 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00005780
5781 BasicBlock::iterator InsertPos = DestBlock->begin();
5782 while (isa<PHINode>(InsertPos)) ++InsertPos;
5783
Chris Lattner9f269e42005-08-08 19:11:57 +00005784 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00005785 ++NumSunkInst;
5786 return true;
5787}
5788
Chris Lattner113f4f42002-06-25 16:13:24 +00005789bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00005790 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005791 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00005792
Chris Lattner4ed40f72005-07-07 20:40:38 +00005793 {
5794 // Populate the worklist with the reachable instructions.
5795 std::set<BasicBlock*> Visited;
5796 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
5797 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
5798 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
5799 WorkList.push_back(I);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005800
Chris Lattner4ed40f72005-07-07 20:40:38 +00005801 // Do a quick scan over the function. If we find any blocks that are
5802 // unreachable, remove any instructions inside of them. This prevents
5803 // the instcombine code from having to deal with some bad special cases.
5804 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5805 if (!Visited.count(BB)) {
5806 Instruction *Term = BB->getTerminator();
5807 while (Term != BB->begin()) { // Remove instrs bottom-up
5808 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00005809
Chris Lattner4ed40f72005-07-07 20:40:38 +00005810 DEBUG(std::cerr << "IC: DCE: " << *I);
5811 ++NumDeadInst;
5812
5813 if (!I->use_empty())
5814 I->replaceAllUsesWith(UndefValue::get(I->getType()));
5815 I->eraseFromParent();
5816 }
5817 }
5818 }
Chris Lattnerca081252001-12-14 16:52:21 +00005819
5820 while (!WorkList.empty()) {
5821 Instruction *I = WorkList.back(); // Get an instruction from the worklist
5822 WorkList.pop_back();
5823
Misha Brukman632df282002-10-29 23:06:16 +00005824 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00005825 // Check to see if we can DIE the instruction...
5826 if (isInstructionTriviallyDead(I)) {
5827 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005828 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00005829 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00005830 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005831
Chris Lattnercd517ff2005-01-28 19:32:01 +00005832 DEBUG(std::cerr << "IC: DCE: " << *I);
5833
5834 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005835 removeFromWorkList(I);
5836 continue;
5837 }
Chris Lattner99f48c62002-09-02 04:59:56 +00005838
Misha Brukman632df282002-10-29 23:06:16 +00005839 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00005840 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005841 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00005842 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005843 cast<Constant>(Ptr)->isNullValue() &&
5844 !isa<ConstantPointerNull>(C) &&
5845 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00005846 // If this is a constant expr gep that is effectively computing an
5847 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5848 bool isFoldableGEP = true;
5849 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5850 if (!isa<ConstantInt>(I->getOperand(i)))
5851 isFoldableGEP = false;
5852 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005853 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00005854 std::vector<Value*>(I->op_begin()+1, I->op_end()));
5855 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00005856 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00005857 C = ConstantExpr::getCast(C, I->getType());
5858 }
5859 }
5860
Chris Lattnercd517ff2005-01-28 19:32:01 +00005861 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5862
Chris Lattner99f48c62002-09-02 04:59:56 +00005863 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00005864 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00005865 ReplaceInstUsesWith(*I, C);
5866
Chris Lattner99f48c62002-09-02 04:59:56 +00005867 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005868 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00005869 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005870 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00005871 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005872
Chris Lattner39c98bb2004-12-08 23:43:58 +00005873 // See if we can trivially sink this instruction to a successor basic block.
5874 if (I->hasOneUse()) {
5875 BasicBlock *BB = I->getParent();
5876 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5877 if (UserParent != BB) {
5878 bool UserIsSuccessor = false;
5879 // See if the user is one of our successors.
5880 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5881 if (*SI == UserParent) {
5882 UserIsSuccessor = true;
5883 break;
5884 }
5885
5886 // If the user is one of our immediate successors, and if that successor
5887 // only has us as a predecessors (we'd have to split the critical edge
5888 // otherwise), we can keep going.
5889 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5890 next(pred_begin(UserParent)) == pred_end(UserParent))
5891 // Okay, the CFG is simple enough, try to sink this instruction.
5892 Changed |= TryToSinkInstruction(I, UserParent);
5893 }
5894 }
5895
Chris Lattnerca081252001-12-14 16:52:21 +00005896 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005897 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00005898 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00005899 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00005900 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005901 DEBUG(std::cerr << "IC: Old = " << *I
5902 << " New = " << *Result);
5903
Chris Lattner396dbfe2004-06-09 05:08:07 +00005904 // Everything uses the new instruction now.
5905 I->replaceAllUsesWith(Result);
5906
5907 // Push the new instruction and any users onto the worklist.
5908 WorkList.push_back(Result);
5909 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005910
5911 // Move the name to the new instruction first...
5912 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00005913 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005914
5915 // Insert the new instruction into the basic block...
5916 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00005917 BasicBlock::iterator InsertPos = I;
5918
5919 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5920 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5921 ++InsertPos;
5922
5923 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005924
Chris Lattner63d75af2004-05-01 23:27:23 +00005925 // Make sure that we reprocess all operands now that we reduced their
5926 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00005927 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5928 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5929 WorkList.push_back(OpI);
5930
Chris Lattner396dbfe2004-06-09 05:08:07 +00005931 // Instructions can end up on the worklist more than once. Make sure
5932 // we do not process an instruction that has been deleted.
5933 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005934
5935 // Erase the old instruction.
5936 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00005937 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005938 DEBUG(std::cerr << "IC: MOD = " << *I);
5939
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005940 // If the instruction was modified, it's possible that it is now dead.
5941 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00005942 if (isInstructionTriviallyDead(I)) {
5943 // Make sure we process all operands now that we are reducing their
5944 // use counts.
5945 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5946 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5947 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005948
Chris Lattner63d75af2004-05-01 23:27:23 +00005949 // Instructions may end up in the worklist more than once. Erase all
5950 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00005951 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00005952 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00005953 } else {
5954 WorkList.push_back(Result);
5955 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005956 }
Chris Lattner053c0932002-05-14 15:24:07 +00005957 }
Chris Lattner260ab202002-04-18 17:39:14 +00005958 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00005959 }
5960 }
5961
Chris Lattner260ab202002-04-18 17:39:14 +00005962 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00005963}
5964
Brian Gaeke38b79e82004-07-27 17:43:21 +00005965FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00005966 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00005967}
Brian Gaeke960707c2003-11-11 22:41:34 +00005968