blob: cd02410705dd4f5449fa180ccebc0141fd00eba4 [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 Lattner260ab202002-04-18 17:39:14 +0000230 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000231
Chris Lattnerc8b70922002-07-26 21:12:46 +0000232 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000233}
234
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000235// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000236// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000237static unsigned getComplexity(Value *V) {
238 if (isa<Instruction>(V)) {
239 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000240 return 3;
241 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000242 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000243 if (isa<Argument>(V)) return 3;
244 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000245}
Chris Lattner260ab202002-04-18 17:39:14 +0000246
Chris Lattner7fb29e12003-03-11 00:12:48 +0000247// isOnlyUse - Return true if this instruction will be deleted if we stop using
248// it.
249static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000250 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000251}
252
Chris Lattnere79e8542004-02-23 06:38:22 +0000253// getPromotedType - Return the specified type promoted as it would be to pass
254// though a va_arg area...
255static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000256 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000257 case Type::SByteTyID:
258 case Type::ShortTyID: return Type::IntTy;
259 case Type::UByteTyID:
260 case Type::UShortTyID: return Type::UIntTy;
261 case Type::FloatTyID: return Type::DoubleTy;
262 default: return Ty;
263 }
264}
265
Chris Lattner567b81f2005-09-13 00:40:14 +0000266/// isCast - If the specified operand is a CastInst or a constant expr cast,
267/// return the operand value, otherwise return null.
268static Value *isCast(Value *V) {
269 if (CastInst *I = dyn_cast<CastInst>(V))
270 return I->getOperand(0);
271 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
272 if (CE->getOpcode() == Instruction::Cast)
273 return CE->getOperand(0);
274 return 0;
275}
276
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000277// SimplifyCommutative - This performs a few simplifications for commutative
278// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000279//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000280// 1. Order operands such that they are listed from right (least complex) to
281// left (most complex). This puts constants before unary operators before
282// binary operators.
283//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000284// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
285// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000286//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000287bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000288 bool Changed = false;
289 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
290 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000291
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000292 if (!I.isAssociative()) return Changed;
293 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000294 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
295 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
296 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000297 Constant *Folded = ConstantExpr::get(I.getOpcode(),
298 cast<Constant>(I.getOperand(1)),
299 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000300 I.setOperand(0, Op->getOperand(0));
301 I.setOperand(1, Folded);
302 return true;
303 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
304 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
305 isOnlyUse(Op) && isOnlyUse(Op1)) {
306 Constant *C1 = cast<Constant>(Op->getOperand(1));
307 Constant *C2 = cast<Constant>(Op1->getOperand(1));
308
309 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000310 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000311 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
312 Op1->getOperand(0),
313 Op1->getName(), &I);
314 WorkList.push_back(New);
315 I.setOperand(0, New);
316 I.setOperand(1, Folded);
317 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000318 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000319 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000320 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000321}
Chris Lattnerca081252001-12-14 16:52:21 +0000322
Chris Lattnerbb74e222003-03-10 23:06:50 +0000323// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
324// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000325//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000326static inline Value *dyn_castNegVal(Value *V) {
327 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000328 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000329
Chris Lattner9ad0d552004-12-14 20:08:06 +0000330 // Constants can be considered to be negated values if they can be folded.
331 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
332 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000333 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000334}
335
Chris Lattnerbb74e222003-03-10 23:06:50 +0000336static inline Value *dyn_castNotVal(Value *V) {
337 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000338 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000339
340 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000341 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000342 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000343 return 0;
344}
345
Chris Lattner7fb29e12003-03-11 00:12:48 +0000346// dyn_castFoldableMul - If this value is a multiply that can be folded into
347// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000348// non-constant operand of the multiply, and set CST to point to the multiplier.
349// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000350//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000351static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000352 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000353 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000354 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000355 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000356 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000357 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000358 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000359 // The multiplier is really 1 << CST.
360 Constant *One = ConstantInt::get(V->getType(), 1);
361 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
362 return I->getOperand(0);
363 }
364 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000365 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000366}
Chris Lattner31ae8632002-08-14 17:51:49 +0000367
Chris Lattner0798af32005-01-13 20:14:25 +0000368/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
369/// expression, return it.
370static User *dyn_castGetElementPtr(Value *V) {
371 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
372 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
373 if (CE->getOpcode() == Instruction::GetElementPtr)
374 return cast<User>(V);
375 return false;
376}
377
Chris Lattner623826c2004-09-28 21:48:02 +0000378// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000379static ConstantInt *AddOne(ConstantInt *C) {
380 return cast<ConstantInt>(ConstantExpr::getAdd(C,
381 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000382}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000383static ConstantInt *SubOne(ConstantInt *C) {
384 return cast<ConstantInt>(ConstantExpr::getSub(C,
385 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000386}
387
388// isTrueWhenEqual - Return true if the specified setcondinst instruction is
389// true when both operands are equal...
390//
391static bool isTrueWhenEqual(Instruction &I) {
392 return I.getOpcode() == Instruction::SetEQ ||
393 I.getOpcode() == Instruction::SetGE ||
394 I.getOpcode() == Instruction::SetLE;
395}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000396
397/// AssociativeOpt - Perform an optimization on an associative operator. This
398/// function is designed to check a chain of associative operators for a
399/// potential to apply a certain optimization. Since the optimization may be
400/// applicable if the expression was reassociated, this checks the chain, then
401/// reassociates the expression as necessary to expose the optimization
402/// opportunity. This makes use of a special Functor, which must define
403/// 'shouldApply' and 'apply' methods.
404///
405template<typename Functor>
406Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
407 unsigned Opcode = Root.getOpcode();
408 Value *LHS = Root.getOperand(0);
409
410 // Quick check, see if the immediate LHS matches...
411 if (F.shouldApply(LHS))
412 return F.apply(Root);
413
414 // Otherwise, if the LHS is not of the same opcode as the root, return.
415 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000416 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000417 // Should we apply this transform to the RHS?
418 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
419
420 // If not to the RHS, check to see if we should apply to the LHS...
421 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
422 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
423 ShouldApply = true;
424 }
425
426 // If the functor wants to apply the optimization to the RHS of LHSI,
427 // reassociate the expression from ((? op A) op B) to (? op (A op B))
428 if (ShouldApply) {
429 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000430
Chris Lattnerb8b97502003-08-13 19:01:45 +0000431 // Now all of the instructions are in the current basic block, go ahead
432 // and perform the reassociation.
433 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
434
435 // First move the selected RHS to the LHS of the root...
436 Root.setOperand(0, LHSI->getOperand(1));
437
438 // Make what used to be the LHS of the root be the user of the root...
439 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000440 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000441 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
442 return 0;
443 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000444 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000445 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000446 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
447 BasicBlock::iterator ARI = &Root; ++ARI;
448 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
449 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000450
451 // Now propagate the ExtraOperand down the chain of instructions until we
452 // get to LHSI.
453 while (TmpLHSI != LHSI) {
454 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000455 // Move the instruction to immediately before the chain we are
456 // constructing to avoid breaking dominance properties.
457 NextLHSI->getParent()->getInstList().remove(NextLHSI);
458 BB->getInstList().insert(ARI, NextLHSI);
459 ARI = NextLHSI;
460
Chris Lattnerb8b97502003-08-13 19:01:45 +0000461 Value *NextOp = NextLHSI->getOperand(1);
462 NextLHSI->setOperand(1, ExtraOperand);
463 TmpLHSI = NextLHSI;
464 ExtraOperand = NextOp;
465 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000466
Chris Lattnerb8b97502003-08-13 19:01:45 +0000467 // Now that the instructions are reassociated, have the functor perform
468 // the transformation...
469 return F.apply(Root);
470 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000471
Chris Lattnerb8b97502003-08-13 19:01:45 +0000472 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
473 }
474 return 0;
475}
476
477
478// AddRHS - Implements: X + X --> X << 1
479struct AddRHS {
480 Value *RHS;
481 AddRHS(Value *rhs) : RHS(rhs) {}
482 bool shouldApply(Value *LHS) const { return LHS == RHS; }
483 Instruction *apply(BinaryOperator &Add) const {
484 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
485 ConstantInt::get(Type::UByteTy, 1));
486 }
487};
488
489// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
490// iff C1&C2 == 0
491struct AddMaskingAnd {
492 Constant *C2;
493 AddMaskingAnd(Constant *c) : C2(c) {}
494 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000495 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000496 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +0000497 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000498 }
499 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000500 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000501 }
502};
503
Chris Lattner86102b82005-01-01 16:22:27 +0000504static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000505 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +0000506 if (isa<CastInst>(I)) {
507 if (Constant *SOC = dyn_cast<Constant>(SO))
508 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000509
Chris Lattner86102b82005-01-01 16:22:27 +0000510 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
511 SO->getName() + ".cast"), I);
512 }
513
Chris Lattner183b3362004-04-09 19:05:30 +0000514 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000515 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
516 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000517
Chris Lattner183b3362004-04-09 19:05:30 +0000518 if (Constant *SOC = dyn_cast<Constant>(SO)) {
519 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +0000520 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
521 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000522 }
523
524 Value *Op0 = SO, *Op1 = ConstOperand;
525 if (!ConstIsRHS)
526 std::swap(Op0, Op1);
527 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +0000528 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
529 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
530 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
531 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000532 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000533 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000534 abort();
535 }
Chris Lattner86102b82005-01-01 16:22:27 +0000536 return IC->InsertNewInstBefore(New, I);
537}
538
539// FoldOpIntoSelect - Given an instruction with a select as one operand and a
540// constant as the other operand, try to fold the binary operator into the
541// select arguments. This also works for Cast instructions, which obviously do
542// not have a second operand.
543static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
544 InstCombiner *IC) {
545 // Don't modify shared select instructions
546 if (!SI->hasOneUse()) return 0;
547 Value *TV = SI->getOperand(1);
548 Value *FV = SI->getOperand(2);
549
550 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +0000551 // Bool selects with constant operands can be folded to logical ops.
552 if (SI->getType() == Type::BoolTy) return 0;
553
Chris Lattner86102b82005-01-01 16:22:27 +0000554 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
555 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
556
557 return new SelectInst(SI->getCondition(), SelectTrueVal,
558 SelectFalseVal);
559 }
560 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +0000561}
562
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000563
564/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
565/// node as operand #0, see if we can fold the instruction into the PHI (which
566/// is only possible if all operands to the PHI are constants).
567Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
568 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000569 unsigned NumPHIValues = PN->getNumIncomingValues();
570 if (!PN->hasOneUse() || NumPHIValues == 0 ||
571 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000572
573 // Check to see if all of the operands of the PHI are constants. If not, we
574 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000575 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000576 if (!isa<Constant>(PN->getIncomingValue(i)))
577 return 0;
578
579 // Okay, we can do the transformation: create the new PHI node.
580 PHINode *NewPN = new PHINode(I.getType(), I.getName());
581 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +0000582 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000583 InsertNewInstBefore(NewPN, *PN);
584
585 // Next, add all of the operands to the PHI.
586 if (I.getNumOperands() == 2) {
587 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000588 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000589 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
590 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
591 PN->getIncomingBlock(i));
592 }
593 } else {
594 assert(isa<CastInst>(I) && "Unary op should be a cast!");
595 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000596 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000597 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
598 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
599 PN->getIncomingBlock(i));
600 }
601 }
602 return ReplaceInstUsesWith(I, NewPN);
603}
604
Chris Lattner113f4f42002-06-25 16:13:24 +0000605Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000606 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000607 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000608
Chris Lattnercf4a9962004-04-10 22:01:55 +0000609 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000610 // X + undef -> undef
611 if (isa<UndefValue>(RHS))
612 return ReplaceInstUsesWith(I, RHS);
613
Chris Lattnercf4a9962004-04-10 22:01:55 +0000614 // X + 0 --> X
615 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
616 RHSC->isNullValue())
617 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000618
Chris Lattnercf4a9962004-04-10 22:01:55 +0000619 // X + (signbit) --> X ^ signbit
620 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000621 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnercf4a9962004-04-10 22:01:55 +0000622 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattner33eb9092004-11-05 04:45:43 +0000623 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000624 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000625 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000626
627 if (isa<PHINode>(LHS))
628 if (Instruction *NV = FoldOpIntoPhi(I))
629 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000630 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000631
Chris Lattnerb8b97502003-08-13 19:01:45 +0000632 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000633 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000634 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +0000635
636 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
637 if (RHSI->getOpcode() == Instruction::Sub)
638 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
639 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
640 }
641 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
642 if (LHSI->getOpcode() == Instruction::Sub)
643 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
644 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
645 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000646 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000647
Chris Lattner147e9752002-05-08 22:46:53 +0000648 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000649 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000650 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000651
652 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000653 if (!isa<Constant>(RHS))
654 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000655 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000656
Misha Brukmanb1c93172005-04-21 23:48:37 +0000657
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000658 ConstantInt *C2;
659 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
660 if (X == RHS) // X*C + X --> X * (C+1)
661 return BinaryOperator::createMul(RHS, AddOne(C2));
662
663 // X*C1 + X*C2 --> X * (C1+C2)
664 ConstantInt *C1;
665 if (X == dyn_castFoldableMul(RHS, C1))
666 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000667 }
668
669 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000670 if (dyn_castFoldableMul(RHS, C2) == LHS)
671 return BinaryOperator::createMul(LHS, AddOne(C2));
672
Chris Lattner57c8d992003-02-18 19:57:07 +0000673
Chris Lattnerb8b97502003-08-13 19:01:45 +0000674 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000675 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000676 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000677
Chris Lattnerb9cde762003-10-02 15:11:26 +0000678 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000679 Value *X;
680 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
681 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
682 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000683 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000684
Chris Lattnerbff91d92004-10-08 05:07:56 +0000685 // (X & FF00) + xx00 -> (X+xx00) & FF00
686 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
687 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
688 if (Anded == CRHS) {
689 // See if all bits from the first bit set in the Add RHS up are included
690 // in the mask. First, get the rightmost bit.
691 uint64_t AddRHSV = CRHS->getRawValue();
692
693 // Form a mask of all bits from the lowest bit added through the top.
694 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner2f1457f2005-04-24 17:46:05 +0000695 AddRHSHighBits &= ~0ULL >> (64-C2->getType()->getPrimitiveSizeInBits());
Chris Lattnerbff91d92004-10-08 05:07:56 +0000696
697 // See if the and mask includes all of these bits.
698 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000699
Chris Lattnerbff91d92004-10-08 05:07:56 +0000700 if (AddRHSHighBits == AddRHSHighBitsAnd) {
701 // Okay, the xform is safe. Insert the new add pronto.
702 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
703 LHS->getName()), I);
704 return BinaryOperator::createAnd(NewAdd, C2);
705 }
706 }
707 }
708
Chris Lattnerd4252a72004-07-30 07:50:03 +0000709 // Try to fold constant add into select arguments.
710 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +0000711 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +0000712 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000713 }
714
Chris Lattner113f4f42002-06-25 16:13:24 +0000715 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000716}
717
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000718// isSignBit - Return true if the value represented by the constant only has the
719// highest order bit set.
720static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000721 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +0000722 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000723}
724
Chris Lattner022167f2004-03-13 00:11:49 +0000725/// RemoveNoopCast - Strip off nonconverting casts from the value.
726///
727static Value *RemoveNoopCast(Value *V) {
728 if (CastInst *CI = dyn_cast<CastInst>(V)) {
729 const Type *CTy = CI->getType();
730 const Type *OpTy = CI->getOperand(0)->getType();
731 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000732 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +0000733 return RemoveNoopCast(CI->getOperand(0));
734 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
735 return RemoveNoopCast(CI->getOperand(0));
736 }
737 return V;
738}
739
Chris Lattner113f4f42002-06-25 16:13:24 +0000740Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000741 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000742
Chris Lattnere6794492002-08-12 21:17:25 +0000743 if (Op0 == Op1) // sub X, X -> 0
744 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000745
Chris Lattnere6794492002-08-12 21:17:25 +0000746 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000747 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000748 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000749
Chris Lattner81a7a232004-10-16 18:11:37 +0000750 if (isa<UndefValue>(Op0))
751 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
752 if (isa<UndefValue>(Op1))
753 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
754
Chris Lattner8f2f5982003-11-05 01:06:05 +0000755 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
756 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000757 if (C->isAllOnesValue())
758 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000759
Chris Lattner8f2f5982003-11-05 01:06:05 +0000760 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +0000761 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +0000762 if (match(Op1, m_Not(m_Value(X))))
763 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000764 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000765 // -((uint)X >> 31) -> ((int)X >> 31)
766 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000767 if (C->isNullValue()) {
768 Value *NoopCastedRHS = RemoveNoopCast(Op1);
769 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000770 if (SI->getOpcode() == Instruction::Shr)
771 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
772 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000773 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000774 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000775 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000776 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000777 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000778 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000779 // Ok, the transformation is safe. Insert a cast of the incoming
780 // value, then the new shift, then the new cast.
781 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
782 SI->getOperand(0)->getName());
783 Value *InV = InsertNewInstBefore(FirstCast, I);
784 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
785 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000786 if (NewShift->getType() == I.getType())
787 return NewShift;
788 else {
789 InV = InsertNewInstBefore(NewShift, I);
790 return new CastInst(NewShift, I.getType());
791 }
Chris Lattner92295c52004-03-12 23:53:13 +0000792 }
793 }
Chris Lattner022167f2004-03-13 00:11:49 +0000794 }
Chris Lattner183b3362004-04-09 19:05:30 +0000795
796 // Try to fold constant sub into select arguments.
797 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +0000798 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000799 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000800
801 if (isa<PHINode>(Op0))
802 if (Instruction *NV = FoldOpIntoPhi(I))
803 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000804 }
805
Chris Lattnera9be4492005-04-07 16:15:25 +0000806 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
807 if (Op1I->getOpcode() == Instruction::Add &&
808 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000809 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000810 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000811 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000812 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000813 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
814 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
815 // C1-(X+C2) --> (C1-C2)-X
816 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
817 Op1I->getOperand(0));
818 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000819 }
820
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000821 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000822 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
823 // is not used by anyone else...
824 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000825 if (Op1I->getOpcode() == Instruction::Sub &&
826 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000827 // Swap the two operands of the subexpr...
828 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
829 Op1I->setOperand(0, IIOp1);
830 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000831
Chris Lattner3082c5a2003-02-18 19:28:33 +0000832 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000833 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000834 }
835
836 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
837 //
838 if (Op1I->getOpcode() == Instruction::And &&
839 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
840 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
841
Chris Lattner396dbfe2004-06-09 05:08:07 +0000842 Value *NewNot =
843 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000844 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000845 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000846
Chris Lattner0aee4b72004-10-06 15:08:25 +0000847 // -(X sdiv C) -> (X sdiv -C)
848 if (Op1I->getOpcode() == Instruction::Div)
849 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +0000850 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +0000851 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +0000852 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +0000853 ConstantExpr::getNeg(DivRHS));
854
Chris Lattner57c8d992003-02-18 19:57:07 +0000855 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +0000856 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000857 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000858 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000859 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000860 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000861 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000862 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000863 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000864
Chris Lattner47060462005-04-07 17:14:51 +0000865 if (!Op0->getType()->isFloatingPoint())
866 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
867 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +0000868 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
869 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
870 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
871 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +0000872 } else if (Op0I->getOpcode() == Instruction::Sub) {
873 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
874 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +0000875 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000876
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000877 ConstantInt *C1;
878 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
879 if (X == Op1) { // X*C - X --> X * (C-1)
880 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
881 return BinaryOperator::createMul(Op1, CP1);
882 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000883
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000884 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
885 if (X == dyn_castFoldableMul(Op1, C2))
886 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
887 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000888 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000889}
890
Chris Lattnere79e8542004-02-23 06:38:22 +0000891/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
892/// really just returns true if the most significant (sign) bit is set.
893static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
894 if (RHS->getType()->isSigned()) {
895 // True if source is LHS < 0 or LHS <= -1
896 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
897 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
898 } else {
899 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
900 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
901 // the size of the integer type.
902 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000903 return RHSC->getValue() ==
904 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000905 if (Opcode == Instruction::SetGT)
906 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000907 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +0000908 }
909 return false;
910}
911
Chris Lattner113f4f42002-06-25 16:13:24 +0000912Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000913 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000914 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000915
Chris Lattner81a7a232004-10-16 18:11:37 +0000916 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
917 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
918
Chris Lattnere6794492002-08-12 21:17:25 +0000919 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000920 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
921 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000922
923 // ((X << C1)*C2) == (X * (C2 << C1))
924 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
925 if (SI->getOpcode() == Instruction::Shl)
926 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000927 return BinaryOperator::createMul(SI->getOperand(0),
928 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000929
Chris Lattnercce81be2003-09-11 22:24:54 +0000930 if (CI->isNullValue())
931 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
932 if (CI->equalsInt(1)) // X * 1 == X
933 return ReplaceInstUsesWith(I, Op0);
934 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000935 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000936
Chris Lattnercce81be2003-09-11 22:24:54 +0000937 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +0000938 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
939 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000940 return new ShiftInst(Instruction::Shl, Op0,
941 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +0000942 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000943 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000944 if (Op1F->isNullValue())
945 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000946
Chris Lattner3082c5a2003-02-18 19:28:33 +0000947 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
948 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
949 if (Op1F->getValue() == 1.0)
950 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
951 }
Chris Lattner183b3362004-04-09 19:05:30 +0000952
953 // Try to fold constant mul into select arguments.
954 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +0000955 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000956 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000957
958 if (isa<PHINode>(Op0))
959 if (Instruction *NV = FoldOpIntoPhi(I))
960 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000961 }
962
Chris Lattner934a64cf2003-03-10 23:23:04 +0000963 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
964 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000965 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000966
Chris Lattner2635b522004-02-23 05:39:21 +0000967 // If one of the operands of the multiply is a cast from a boolean value, then
968 // we know the bool is either zero or one, so this is a 'masking' multiply.
969 // See if we can simplify things based on how the boolean was originally
970 // formed.
971 CastInst *BoolCast = 0;
972 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
973 if (CI->getOperand(0)->getType() == Type::BoolTy)
974 BoolCast = CI;
975 if (!BoolCast)
976 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
977 if (CI->getOperand(0)->getType() == Type::BoolTy)
978 BoolCast = CI;
979 if (BoolCast) {
980 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
981 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
982 const Type *SCOpTy = SCIOp0->getType();
983
Chris Lattnere79e8542004-02-23 06:38:22 +0000984 // If the setcc is true iff the sign bit of X is set, then convert this
985 // multiply into a shift/and combination.
986 if (isa<ConstantInt>(SCIOp1) &&
987 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000988 // Shift the X value right to turn it into "all signbits".
989 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000990 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000991 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000992 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000993 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
994 SCIOp0->getName()), I);
995 }
996
997 Value *V =
998 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
999 BoolCast->getOperand(0)->getName()+
1000 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001001
1002 // If the multiply type is not the same as the source type, sign extend
1003 // or truncate to the multiply type.
1004 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001005 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001006
Chris Lattner2635b522004-02-23 05:39:21 +00001007 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001008 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001009 }
1010 }
1011 }
1012
Chris Lattner113f4f42002-06-25 16:13:24 +00001013 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001014}
1015
Chris Lattner113f4f42002-06-25 16:13:24 +00001016Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001017 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001018
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001019 if (isa<UndefValue>(Op0)) // undef / X -> 0
1020 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1021 if (isa<UndefValue>(Op1))
1022 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1023
1024 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001025 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001026 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001027 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001028
Chris Lattnere20c3342004-04-26 14:01:59 +00001029 // div X, -1 == -X
1030 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001031 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001032
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001033 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001034 if (LHS->getOpcode() == Instruction::Div)
1035 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001036 // (X / C1) / C2 -> X / (C1*C2)
1037 return BinaryOperator::createDiv(LHS->getOperand(0),
1038 ConstantExpr::getMul(RHS, LHSRHS));
1039 }
1040
Chris Lattner3082c5a2003-02-18 19:28:33 +00001041 // Check to see if this is an unsigned division with an exact power of 2,
1042 // if so, convert to a right shift.
1043 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1044 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001045 if (isPowerOf2_64(Val)) {
1046 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001047 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001048 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001049 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001050
Chris Lattner4ad08352004-10-09 02:50:40 +00001051 // -X/C -> X/-C
1052 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001053 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001054 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1055
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001056 if (!RHS->isNullValue()) {
1057 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001058 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001059 return R;
1060 if (isa<PHINode>(Op0))
1061 if (Instruction *NV = FoldOpIntoPhi(I))
1062 return NV;
1063 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001064 }
1065
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001066 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1067 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1068 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1069 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1070 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1071 if (STO->getValue() == 0) { // Couldn't be this argument.
1072 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001073 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001074 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001075 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001076 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001077 }
1078
Chris Lattner42362612005-04-08 04:03:26 +00001079 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001080 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1081 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001082 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1083 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1084 TC, SI->getName()+".t");
1085 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001086
Chris Lattner42362612005-04-08 04:03:26 +00001087 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1088 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1089 FC, SI->getName()+".f");
1090 FSI = InsertNewInstBefore(FSI, I);
1091 return new SelectInst(SI->getOperand(0), TSI, FSI);
1092 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001093 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001094
Chris Lattner3082c5a2003-02-18 19:28:33 +00001095 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001096 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001097 if (LHS->equalsInt(0))
1098 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1099
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001100 return 0;
1101}
1102
1103
Chris Lattner113f4f42002-06-25 16:13:24 +00001104Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001105 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner7fd5f072004-07-06 07:01:22 +00001106 if (I.getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001107 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001108 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001109 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001110 // X % -Y -> X % Y
1111 AddUsesToWorkList(I);
1112 I.setOperand(1, RHSNeg);
1113 return &I;
1114 }
1115
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001116 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001117 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001118 if (isa<UndefValue>(Op1))
1119 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001120
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001121 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001122 if (RHS->equalsInt(1)) // X % 1 == 0
1123 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1124
1125 // Check to see if this is an unsigned remainder with an exact power of 2,
1126 // if so, convert to a bitwise and.
1127 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1128 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001129 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001130 return BinaryOperator::createAnd(Op0,
1131 ConstantUInt::get(I.getType(), Val-1));
1132
1133 if (!RHS->isNullValue()) {
1134 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001135 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001136 return R;
1137 if (isa<PHINode>(Op0))
1138 if (Instruction *NV = FoldOpIntoPhi(I))
1139 return NV;
1140 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001141 }
1142
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001143 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1144 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1145 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1146 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1147 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1148 if (STO->getValue() == 0) { // Couldn't be this argument.
1149 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001150 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001151 } else if (SFO->getValue() == 0) {
1152 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001153 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001154 }
1155
1156 if (!(STO->getValue() & (STO->getValue()-1)) &&
1157 !(SFO->getValue() & (SFO->getValue()-1))) {
1158 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1159 SubOne(STO), SI->getName()+".t"), I);
1160 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1161 SubOne(SFO), SI->getName()+".f"), I);
1162 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1163 }
1164 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001165
Chris Lattner3082c5a2003-02-18 19:28:33 +00001166 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001167 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001168 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001169 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1170
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001171 return 0;
1172}
1173
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001174// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001175static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001176 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1177 // Calculate -1 casted to the right type...
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001178 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001179 uint64_t Val = ~0ULL; // All ones
1180 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1181 return CU->getValue() == Val-1;
1182 }
1183
1184 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001185
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001186 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001187 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001188 int64_t Val = INT64_MAX; // All ones
1189 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1190 return CS->getValue() == Val-1;
1191}
1192
1193// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001194static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001195 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1196 return CU->getValue() == 1;
1197
1198 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001199
1200 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001201 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001202 int64_t Val = -1; // All ones
1203 Val <<= TypeBits-1; // Shift over to the right spot
1204 return CS->getValue() == Val+1;
1205}
1206
Chris Lattner35167c32004-06-09 07:59:58 +00001207// isOneBitSet - Return true if there is exactly one bit set in the specified
1208// constant.
1209static bool isOneBitSet(const ConstantInt *CI) {
1210 uint64_t V = CI->getRawValue();
1211 return V && (V & (V-1)) == 0;
1212}
1213
Chris Lattner8fc5af42004-09-23 21:46:38 +00001214#if 0 // Currently unused
1215// isLowOnes - Return true if the constant is of the form 0+1+.
1216static bool isLowOnes(const ConstantInt *CI) {
1217 uint64_t V = CI->getRawValue();
1218
1219 // There won't be bits set in parts that the type doesn't contain.
1220 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1221
1222 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1223 return U && V && (U & V) == 0;
1224}
1225#endif
1226
1227// isHighOnes - Return true if the constant is of the form 1+0+.
1228// This is the same as lowones(~X).
1229static bool isHighOnes(const ConstantInt *CI) {
1230 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00001231 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00001232
1233 // There won't be bits set in parts that the type doesn't contain.
1234 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1235
1236 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1237 return U && V && (U & V) == 0;
1238}
1239
1240
Chris Lattner3ac7c262003-08-13 20:16:26 +00001241/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1242/// are carefully arranged to allow folding of expressions such as:
1243///
1244/// (A < B) | (A > B) --> (A != B)
1245///
1246/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1247/// represents that the comparison is true if A == B, and bit value '1' is true
1248/// if A < B.
1249///
1250static unsigned getSetCondCode(const SetCondInst *SCI) {
1251 switch (SCI->getOpcode()) {
1252 // False -> 0
1253 case Instruction::SetGT: return 1;
1254 case Instruction::SetEQ: return 2;
1255 case Instruction::SetGE: return 3;
1256 case Instruction::SetLT: return 4;
1257 case Instruction::SetNE: return 5;
1258 case Instruction::SetLE: return 6;
1259 // True -> 7
1260 default:
1261 assert(0 && "Invalid SetCC opcode!");
1262 return 0;
1263 }
1264}
1265
1266/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1267/// opcode and two operands into either a constant true or false, or a brand new
1268/// SetCC instruction.
1269static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1270 switch (Opcode) {
1271 case 0: return ConstantBool::False;
1272 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1273 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1274 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1275 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1276 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1277 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1278 case 7: return ConstantBool::True;
1279 default: assert(0 && "Illegal SetCCCode!"); return 0;
1280 }
1281}
1282
1283// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1284struct FoldSetCCLogical {
1285 InstCombiner &IC;
1286 Value *LHS, *RHS;
1287 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1288 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1289 bool shouldApply(Value *V) const {
1290 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1291 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1292 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1293 return false;
1294 }
1295 Instruction *apply(BinaryOperator &Log) const {
1296 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1297 if (SCI->getOperand(0) != LHS) {
1298 assert(SCI->getOperand(1) == LHS);
1299 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1300 }
1301
1302 unsigned LHSCode = getSetCondCode(SCI);
1303 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1304 unsigned Code;
1305 switch (Log.getOpcode()) {
1306 case Instruction::And: Code = LHSCode & RHSCode; break;
1307 case Instruction::Or: Code = LHSCode | RHSCode; break;
1308 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001309 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001310 }
1311
1312 Value *RV = getSetCCValue(Code, LHS, RHS);
1313 if (Instruction *I = dyn_cast<Instruction>(RV))
1314 return I;
1315 // Otherwise, it's a constant boolean value...
1316 return IC.ReplaceInstUsesWith(Log, RV);
1317 }
1318};
1319
1320
Chris Lattner86102b82005-01-01 16:22:27 +00001321/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1322/// this predicate to simplify operations downstream. V and Mask are known to
1323/// be the same type.
1324static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00001325 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
1326 // we cannot optimize based on the assumption that it is zero without changing
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001327 // to to an explicit zero. If we don't change it to zero, other code could
Chris Lattner18aa4d82005-07-20 18:49:28 +00001328 // optimized based on the contradictory assumption that it is non-zero.
1329 // Because instcombine aggressively folds operations with undef args anyway,
1330 // this won't lose us code quality.
1331 if (Mask->isNullValue())
Chris Lattner86102b82005-01-01 16:22:27 +00001332 return true;
1333 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
1334 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001335
Chris Lattner86102b82005-01-01 16:22:27 +00001336 if (Instruction *I = dyn_cast<Instruction>(V)) {
1337 switch (I->getOpcode()) {
1338 case Instruction::And:
1339 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
1340 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
1341 if (ConstantExpr::getAnd(CI, Mask)->isNullValue())
1342 return true;
1343 break;
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001344 case Instruction::Or:
1345 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001346 return MaskedValueIsZero(I->getOperand(1), Mask) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001347 MaskedValueIsZero(I->getOperand(0), Mask);
1348 case Instruction::Select:
1349 // If the T and F values are MaskedValueIsZero, the result is also zero.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001350 return MaskedValueIsZero(I->getOperand(2), Mask) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001351 MaskedValueIsZero(I->getOperand(1), Mask);
Chris Lattner86102b82005-01-01 16:22:27 +00001352 case Instruction::Cast: {
1353 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner4c2d3782005-05-06 01:53:19 +00001354 if (SrcTy == Type::BoolTy)
1355 return (Mask->getRawValue() & 1) == 0;
1356
1357 if (SrcTy->isInteger()) {
Chris Lattner86102b82005-01-01 16:22:27 +00001358 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
1359 if (SrcTy->isUnsigned() && // Only handle zero ext.
1360 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
1361 return true;
1362
1363 // If this is a noop cast, recurse.
Chris Lattner4c2d3782005-05-06 01:53:19 +00001364 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() == I->getType())||
1365 SrcTy->getSignedVersion() == I->getType()) {
1366 Constant *NewMask =
1367 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
1368 return MaskedValueIsZero(I->getOperand(0),
1369 cast<ConstantIntegral>(NewMask));
1370 }
Chris Lattner86102b82005-01-01 16:22:27 +00001371 }
1372 break;
1373 }
1374 case Instruction::Shl:
Chris Lattneref298a32005-05-06 04:53:20 +00001375 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1376 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1377 return MaskedValueIsZero(I->getOperand(0),
1378 cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)));
Chris Lattner86102b82005-01-01 16:22:27 +00001379 break;
1380 case Instruction::Shr:
1381 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1382 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1383 if (I->getType()->isUnsigned()) {
1384 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1385 C1 = ConstantExpr::getShr(C1, SA);
1386 C1 = ConstantExpr::getAnd(C1, Mask);
1387 if (C1->isNullValue())
1388 return true;
1389 }
1390 break;
1391 }
1392 }
1393
1394 return false;
1395}
1396
Chris Lattnerba1cb382003-09-19 17:17:26 +00001397// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1398// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1399// guaranteed to be either a shift instruction or a binary operator.
1400Instruction *InstCombiner::OptAndOp(Instruction *Op,
1401 ConstantIntegral *OpRHS,
1402 ConstantIntegral *AndRHS,
1403 BinaryOperator &TheAnd) {
1404 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001405 Constant *Together = 0;
1406 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001407 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001408
Chris Lattnerba1cb382003-09-19 17:17:26 +00001409 switch (Op->getOpcode()) {
1410 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001411 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001412 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1413 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001414 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001415 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001416 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001417 }
1418 break;
1419 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001420 if (Together == AndRHS) // (X | C) & C --> C
1421 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001422
Chris Lattner86102b82005-01-01 16:22:27 +00001423 if (Op->hasOneUse() && Together != OpRHS) {
1424 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1425 std::string Op0Name = Op->getName(); Op->setName("");
1426 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1427 InsertNewInstBefore(Or, TheAnd);
1428 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001429 }
1430 break;
1431 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001432 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001433 // Adding a one to a single bit bit-field should be turned into an XOR
1434 // of the bit. First thing to check is to see if this AND is with a
1435 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001436 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001437
1438 // Clear bits that are not part of the constant.
Chris Lattner2f1457f2005-04-24 17:46:05 +00001439 AndRHSV &= ~0ULL >> (64-AndRHS->getType()->getPrimitiveSizeInBits());
Chris Lattnerba1cb382003-09-19 17:17:26 +00001440
1441 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001442 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001443 // Ok, at this point, we know that we are masking the result of the
1444 // ADD down to exactly one bit. If the constant we are adding has
1445 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001446 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001447
Chris Lattnerba1cb382003-09-19 17:17:26 +00001448 // Check to see if any bits below the one bit set in AndRHSV are set.
1449 if ((AddRHS & (AndRHSV-1)) == 0) {
1450 // If not, the only thing that can effect the output of the AND is
1451 // the bit specified by AndRHSV. If that bit is set, the effect of
1452 // the XOR is to toggle the bit. If it is clear, then the ADD has
1453 // no effect.
1454 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1455 TheAnd.setOperand(0, X);
1456 return &TheAnd;
1457 } else {
1458 std::string Name = Op->getName(); Op->setName("");
1459 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001460 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001461 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001462 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001463 }
1464 }
1465 }
1466 }
1467 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001468
1469 case Instruction::Shl: {
1470 // We know that the AND will not produce any of the bits shifted in, so if
1471 // the anded constant includes them, clear them now!
1472 //
1473 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001474 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1475 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001476
Chris Lattner7e794272004-09-24 15:21:34 +00001477 if (CI == ShlMask) { // Masking out bits that the shift already masks
1478 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1479 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001480 TheAnd.setOperand(1, CI);
1481 return &TheAnd;
1482 }
1483 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001484 }
Chris Lattner2da29172003-09-19 19:05:02 +00001485 case Instruction::Shr:
1486 // We know that the AND will not produce any of the bits shifted in, so if
1487 // the anded constant includes them, clear them now! This only applies to
1488 // unsigned shifts, because a signed shr may bring in set bits!
1489 //
1490 if (AndRHS->getType()->isUnsigned()) {
1491 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001492 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1493 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1494
1495 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1496 return ReplaceInstUsesWith(TheAnd, Op);
1497 } else if (CI != AndRHS) {
1498 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001499 return &TheAnd;
1500 }
Chris Lattner7e794272004-09-24 15:21:34 +00001501 } else { // Signed shr.
1502 // See if this is shifting in some sign extension, then masking it out
1503 // with an and.
1504 if (Op->hasOneUse()) {
1505 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1506 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1507 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001508 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001509 // Make the argument unsigned.
1510 Value *ShVal = Op->getOperand(0);
1511 ShVal = InsertCastBefore(ShVal,
1512 ShVal->getType()->getUnsignedVersion(),
1513 TheAnd);
1514 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1515 OpRHS, Op->getName()),
1516 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001517 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1518 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1519 TheAnd.getName()),
1520 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001521 return new CastInst(ShVal, Op->getType());
1522 }
1523 }
Chris Lattner2da29172003-09-19 19:05:02 +00001524 }
1525 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001526 }
1527 return 0;
1528}
1529
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001530
Chris Lattner6862fbd2004-09-29 17:40:11 +00001531/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1532/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1533/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1534/// insert new instructions.
1535Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1536 bool Inside, Instruction &IB) {
1537 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1538 "Lo is not <= Hi in range emission code!");
1539 if (Inside) {
1540 if (Lo == Hi) // Trivially false.
1541 return new SetCondInst(Instruction::SetNE, V, V);
1542 if (cast<ConstantIntegral>(Lo)->isMinValue())
1543 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001544
Chris Lattner6862fbd2004-09-29 17:40:11 +00001545 Constant *AddCST = ConstantExpr::getNeg(Lo);
1546 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1547 InsertNewInstBefore(Add, IB);
1548 // Convert to unsigned for the comparison.
1549 const Type *UnsType = Add->getType()->getUnsignedVersion();
1550 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1551 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1552 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1553 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1554 }
1555
1556 if (Lo == Hi) // Trivially true.
1557 return new SetCondInst(Instruction::SetEQ, V, V);
1558
1559 Hi = SubOne(cast<ConstantInt>(Hi));
1560 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1561 return new SetCondInst(Instruction::SetGT, V, Hi);
1562
1563 // Emit X-Lo > Hi-Lo-1
1564 Constant *AddCST = ConstantExpr::getNeg(Lo);
1565 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1566 InsertNewInstBefore(Add, IB);
1567 // Convert to unsigned for the comparison.
1568 const Type *UnsType = Add->getType()->getUnsignedVersion();
1569 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1570 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1571 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1572 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1573}
1574
Chris Lattneraf517572005-09-18 04:24:45 +00001575/// FoldLogicalPlusAnd - We know that Mask is of the form 0+1+, and that this is
1576/// part of an expression (LHS +/- RHS) & Mask, where isSub determines whether
1577/// the operator is a sub. If we can fold one of the following xforms:
1578///
1579/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1580/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1581/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1582///
1583/// return (A +/- B).
1584///
1585Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1586 ConstantIntegral *Mask, bool isSub,
1587 Instruction &I) {
1588 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1589 if (!LHSI || LHSI->getNumOperands() != 2 ||
1590 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1591
1592 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1593
1594 switch (LHSI->getOpcode()) {
1595 default: return 0;
1596 case Instruction::And:
1597 if (ConstantExpr::getAnd(N, Mask) == Mask)
1598 break;
1599 return 0;
1600 case Instruction::Or:
1601 case Instruction::Xor:
1602 if (ConstantExpr::getAnd(N, Mask)->isNullValue())
1603 break;
1604 return 0;
1605 }
1606
1607 Instruction *New;
1608 if (isSub)
1609 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
1610 else
1611 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
1612 return InsertNewInstBefore(New, I);
1613}
1614
Chris Lattner6862fbd2004-09-29 17:40:11 +00001615
Chris Lattner113f4f42002-06-25 16:13:24 +00001616Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001617 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001618 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001619
Chris Lattner81a7a232004-10-16 18:11:37 +00001620 if (isa<UndefValue>(Op1)) // X & undef -> 0
1621 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1622
Chris Lattner86102b82005-01-01 16:22:27 +00001623 // and X, X = X
1624 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00001625 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001626
Chris Lattner86102b82005-01-01 16:22:27 +00001627 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001628 // and X, -1 == X
1629 if (AndRHS->isAllOnesValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001630 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001631
Chris Lattner86102b82005-01-01 16:22:27 +00001632 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1633 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1634
1635 // If the mask is not masking out any bits, there is no reason to do the
1636 // and in the first place.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001637 ConstantIntegral *NotAndRHS =
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001638 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001639 if (MaskedValueIsZero(Op0, NotAndRHS))
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001640 return ReplaceInstUsesWith(I, Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001641
Chris Lattnerba1cb382003-09-19 17:17:26 +00001642 // Optimize a variety of ((val OP C1) & C2) combinations...
1643 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1644 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001645 Value *Op0LHS = Op0I->getOperand(0);
1646 Value *Op0RHS = Op0I->getOperand(1);
1647 switch (Op0I->getOpcode()) {
1648 case Instruction::Xor:
1649 case Instruction::Or:
1650 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1651 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1652 if (MaskedValueIsZero(Op0LHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001653 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattner86102b82005-01-01 16:22:27 +00001654 if (MaskedValueIsZero(Op0RHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001655 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001656
1657 // If the mask is only needed on one incoming arm, push it up.
1658 if (Op0I->hasOneUse()) {
1659 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1660 // Not masking anything out for the LHS, move to RHS.
1661 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1662 Op0RHS->getName()+".masked");
1663 InsertNewInstBefore(NewRHS, I);
1664 return BinaryOperator::create(
1665 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001666 }
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001667 if (!isa<Constant>(NotAndRHS) &&
1668 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1669 // Not masking anything out for the RHS, move to LHS.
1670 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1671 Op0LHS->getName()+".masked");
1672 InsertNewInstBefore(NewLHS, I);
1673 return BinaryOperator::create(
1674 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1675 }
1676 }
1677
Chris Lattner86102b82005-01-01 16:22:27 +00001678 break;
1679 case Instruction::And:
1680 // (X & V) & C2 --> 0 iff (V & C2) == 0
1681 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1682 MaskedValueIsZero(Op0RHS, AndRHS))
1683 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1684 break;
Chris Lattneraf517572005-09-18 04:24:45 +00001685 case Instruction::Add:
1686 // If the AndRHS is a power of two minus one (0+1+).
1687 if ((AndRHS->getRawValue() & AndRHS->getRawValue()+1) == 0) {
1688 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1689 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1690 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1691 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1692 return BinaryOperator::createAnd(V, AndRHS);
1693 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1694 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
1695 }
1696 break;
1697
1698 case Instruction::Sub:
1699 // If the AndRHS is a power of two minus one (0+1+).
1700 if ((AndRHS->getRawValue() & AndRHS->getRawValue()+1) == 0) {
1701 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1702 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1703 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1704 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1705 return BinaryOperator::createAnd(V, AndRHS);
1706 }
1707 break;
Chris Lattner86102b82005-01-01 16:22:27 +00001708 }
1709
Chris Lattner16464b32003-07-23 19:25:52 +00001710 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00001711 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001712 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00001713 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1714 const Type *SrcTy = CI->getOperand(0)->getType();
1715
Chris Lattner2c14cf72005-08-07 07:03:10 +00001716 // If this is an integer truncation or change from signed-to-unsigned, and
1717 // if the source is an and/or with immediate, transform it. This
1718 // frequently occurs for bitfield accesses.
1719 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
1720 if (SrcTy->getPrimitiveSizeInBits() >=
1721 I.getType()->getPrimitiveSizeInBits() &&
1722 CastOp->getNumOperands() == 2)
1723 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
1724 if (CastOp->getOpcode() == Instruction::And) {
1725 // Change: and (cast (and X, C1) to T), C2
1726 // into : and (cast X to T), trunc(C1)&C2
1727 // This will folds the two ands together, which may allow other
1728 // simplifications.
1729 Instruction *NewCast =
1730 new CastInst(CastOp->getOperand(0), I.getType(),
1731 CastOp->getName()+".shrunk");
1732 NewCast = InsertNewInstBefore(NewCast, I);
1733
1734 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1735 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
1736 return BinaryOperator::createAnd(NewCast, C3);
1737 } else if (CastOp->getOpcode() == Instruction::Or) {
1738 // Change: and (cast (or X, C1) to T), C2
1739 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
1740 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1741 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
1742 return ReplaceInstUsesWith(I, AndRHS);
1743 }
1744 }
1745
1746
Chris Lattner86102b82005-01-01 16:22:27 +00001747 // If this is an integer sign or zero extension instruction.
1748 if (SrcTy->isIntegral() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001749 SrcTy->getPrimitiveSizeInBits() <
1750 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00001751
1752 if (SrcTy->isUnsigned()) {
1753 // See if this and is clearing out bits that are known to be zero
1754 // anyway (due to the zero extension).
1755 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1756 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1757 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1758 if (Result == Mask) // The "and" isn't doing anything, remove it.
1759 return ReplaceInstUsesWith(I, CI);
1760 if (Result != AndRHS) { // Reduce the and RHS constant.
1761 I.setOperand(1, Result);
1762 return &I;
1763 }
1764
1765 } else {
1766 if (CI->hasOneUse() && SrcTy->isInteger()) {
1767 // We can only do this if all of the sign bits brought in are masked
1768 // out. Compute this by first getting 0000011111, then inverting
1769 // it.
1770 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1771 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1772 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1773 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1774 // If the and is clearing all of the sign bits, change this to a
1775 // zero extension cast. To do this, cast the cast input to
1776 // unsigned, then to the requested size.
1777 Value *CastOp = CI->getOperand(0);
1778 Instruction *NC =
1779 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1780 CI->getName()+".uns");
1781 NC = InsertNewInstBefore(NC, I);
1782 // Finally, insert a replacement for CI.
1783 NC = new CastInst(NC, CI->getType(), CI->getName());
1784 CI->setName("");
1785 NC = InsertNewInstBefore(NC, I);
1786 WorkList.push_back(CI); // Delete CI later.
1787 I.setOperand(0, NC);
1788 return &I; // The AND operand was modified.
1789 }
1790 }
1791 }
1792 }
Chris Lattner33217db2003-07-23 19:36:21 +00001793 }
Chris Lattner183b3362004-04-09 19:05:30 +00001794
1795 // Try to fold constant and into select arguments.
1796 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001797 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001798 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001799 if (isa<PHINode>(Op0))
1800 if (Instruction *NV = FoldOpIntoPhi(I))
1801 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001802 }
1803
Chris Lattnerbb74e222003-03-10 23:06:50 +00001804 Value *Op0NotVal = dyn_castNotVal(Op0);
1805 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001806
Chris Lattner023a4832004-06-18 06:07:51 +00001807 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1808 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1809
Misha Brukman9c003d82004-07-30 12:50:08 +00001810 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001811 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001812 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1813 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001814 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001815 return BinaryOperator::createNot(Or);
1816 }
1817
Chris Lattner623826c2004-09-28 21:48:02 +00001818 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1819 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001820 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1821 return R;
1822
Chris Lattner623826c2004-09-28 21:48:02 +00001823 Value *LHSVal, *RHSVal;
1824 ConstantInt *LHSCst, *RHSCst;
1825 Instruction::BinaryOps LHSCC, RHSCC;
1826 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1827 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1828 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1829 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001830 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00001831 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1832 // Ensure that the larger constant is on the RHS.
1833 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1834 SetCondInst *LHS = cast<SetCondInst>(Op0);
1835 if (cast<ConstantBool>(Cmp)->getValue()) {
1836 std::swap(LHS, RHS);
1837 std::swap(LHSCst, RHSCst);
1838 std::swap(LHSCC, RHSCC);
1839 }
1840
1841 // At this point, we know we have have two setcc instructions
1842 // comparing a value against two constants and and'ing the result
1843 // together. Because of the above check, we know that we only have
1844 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1845 // FoldSetCCLogical check above), that the two constants are not
1846 // equal.
1847 assert(LHSCst != RHSCst && "Compares not folded above?");
1848
1849 switch (LHSCC) {
1850 default: assert(0 && "Unknown integer condition code!");
1851 case Instruction::SetEQ:
1852 switch (RHSCC) {
1853 default: assert(0 && "Unknown integer condition code!");
1854 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1855 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1856 return ReplaceInstUsesWith(I, ConstantBool::False);
1857 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1858 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1859 return ReplaceInstUsesWith(I, LHS);
1860 }
1861 case Instruction::SetNE:
1862 switch (RHSCC) {
1863 default: assert(0 && "Unknown integer condition code!");
1864 case Instruction::SetLT:
1865 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1866 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1867 break; // (X != 13 & X < 15) -> no change
1868 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1869 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1870 return ReplaceInstUsesWith(I, RHS);
1871 case Instruction::SetNE:
1872 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1873 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1874 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1875 LHSVal->getName()+".off");
1876 InsertNewInstBefore(Add, I);
1877 const Type *UnsType = Add->getType()->getUnsignedVersion();
1878 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1879 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1880 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1881 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1882 }
1883 break; // (X != 13 & X != 15) -> no change
1884 }
1885 break;
1886 case Instruction::SetLT:
1887 switch (RHSCC) {
1888 default: assert(0 && "Unknown integer condition code!");
1889 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1890 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1891 return ReplaceInstUsesWith(I, ConstantBool::False);
1892 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1893 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1894 return ReplaceInstUsesWith(I, LHS);
1895 }
1896 case Instruction::SetGT:
1897 switch (RHSCC) {
1898 default: assert(0 && "Unknown integer condition code!");
1899 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1900 return ReplaceInstUsesWith(I, LHS);
1901 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1902 return ReplaceInstUsesWith(I, RHS);
1903 case Instruction::SetNE:
1904 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1905 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1906 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001907 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1908 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001909 }
1910 }
1911 }
1912 }
1913
Chris Lattner113f4f42002-06-25 16:13:24 +00001914 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001915}
1916
Chris Lattner113f4f42002-06-25 16:13:24 +00001917Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001918 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001919 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001920
Chris Lattner81a7a232004-10-16 18:11:37 +00001921 if (isa<UndefValue>(Op1))
1922 return ReplaceInstUsesWith(I, // X | undef -> -1
1923 ConstantIntegral::getAllOnesValue(I.getType()));
1924
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001925 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001926 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1927 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001928
1929 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001930 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001931 // If X is known to only contain bits that already exist in RHS, just
1932 // replace this instruction with RHS directly.
1933 if (MaskedValueIsZero(Op0,
1934 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
1935 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001936
Chris Lattnerd4252a72004-07-30 07:50:03 +00001937 ConstantInt *C1; Value *X;
1938 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1939 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00001940 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
1941 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00001942 InsertNewInstBefore(Or, I);
1943 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1944 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001945
Chris Lattnerd4252a72004-07-30 07:50:03 +00001946 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1947 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1948 std::string Op0Name = Op0->getName(); Op0->setName("");
1949 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1950 InsertNewInstBefore(Or, I);
1951 return BinaryOperator::createXor(Or,
1952 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001953 }
Chris Lattner183b3362004-04-09 19:05:30 +00001954
1955 // Try to fold constant and into select arguments.
1956 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001957 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001958 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001959 if (isa<PHINode>(Op0))
1960 if (Instruction *NV = FoldOpIntoPhi(I))
1961 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001962 }
1963
Chris Lattnerd4252a72004-07-30 07:50:03 +00001964 Value *A, *B; ConstantInt *C1, *C2;
Chris Lattner4294cec2005-05-07 23:49:08 +00001965
1966 if (match(Op0, m_And(m_Value(A), m_Value(B))))
1967 if (A == Op1 || B == Op1) // (A & ?) | A --> A
1968 return ReplaceInstUsesWith(I, Op1);
1969 if (match(Op1, m_And(m_Value(A), m_Value(B))))
1970 if (A == Op0 || B == Op0) // A | (A & ?) --> A
1971 return ReplaceInstUsesWith(I, Op0);
1972
Chris Lattnerb62f5082005-05-09 04:58:36 +00001973 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1974 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1975 MaskedValueIsZero(Op1, C1)) {
1976 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
1977 Op0->setName("");
1978 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
1979 }
1980
1981 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1982 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1983 MaskedValueIsZero(Op0, C1)) {
1984 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
1985 Op0->setName("");
1986 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
1987 }
1988
Chris Lattner15212982005-09-18 03:42:07 +00001989 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001990 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00001991 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
1992
1993 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
1994 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
1995
1996
Chris Lattner01f56c62005-09-18 06:02:59 +00001997 // If we have: ((V + N) & C1) | (V & C2)
1998 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1999 // replace with V+N.
2000 if (C1 == ConstantExpr::getNot(C2)) {
2001 Value *V1, *V2;
2002 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2003 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2004 // Add commutes, try both ways.
2005 if (V1 == B && MaskedValueIsZero(V2, C2))
2006 return ReplaceInstUsesWith(I, A);
2007 if (V2 == B && MaskedValueIsZero(V1, C2))
2008 return ReplaceInstUsesWith(I, A);
2009 }
2010 // Or commutes, try both ways.
2011 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2012 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2013 // Add commutes, try both ways.
2014 if (V1 == A && MaskedValueIsZero(V2, C1))
2015 return ReplaceInstUsesWith(I, B);
2016 if (V2 == A && MaskedValueIsZero(V1, C1))
2017 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00002018 }
2019 }
2020 }
Chris Lattner812aab72003-08-12 19:11:07 +00002021
Chris Lattnerd4252a72004-07-30 07:50:03 +00002022 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2023 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00002024 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002025 ConstantIntegral::getAllOnesValue(I.getType()));
2026 } else {
2027 A = 0;
2028 }
Chris Lattner4294cec2005-05-07 23:49:08 +00002029 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00002030 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2031 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00002032 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002033 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00002034
Misha Brukman9c003d82004-07-30 12:50:08 +00002035 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00002036 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2037 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2038 I.getName()+".demorgan"), I);
2039 return BinaryOperator::createNot(And);
2040 }
Chris Lattner3e327a42003-03-10 23:13:59 +00002041 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002042
Chris Lattner3ac7c262003-08-13 20:16:26 +00002043 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002044 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002045 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2046 return R;
2047
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002048 Value *LHSVal, *RHSVal;
2049 ConstantInt *LHSCst, *RHSCst;
2050 Instruction::BinaryOps LHSCC, RHSCC;
2051 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2052 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2053 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2054 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002055 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002056 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2057 // Ensure that the larger constant is on the RHS.
2058 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2059 SetCondInst *LHS = cast<SetCondInst>(Op0);
2060 if (cast<ConstantBool>(Cmp)->getValue()) {
2061 std::swap(LHS, RHS);
2062 std::swap(LHSCst, RHSCst);
2063 std::swap(LHSCC, RHSCC);
2064 }
2065
2066 // At this point, we know we have have two setcc instructions
2067 // comparing a value against two constants and or'ing the result
2068 // together. Because of the above check, we know that we only have
2069 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2070 // FoldSetCCLogical check above), that the two constants are not
2071 // equal.
2072 assert(LHSCst != RHSCst && "Compares not folded above?");
2073
2074 switch (LHSCC) {
2075 default: assert(0 && "Unknown integer condition code!");
2076 case Instruction::SetEQ:
2077 switch (RHSCC) {
2078 default: assert(0 && "Unknown integer condition code!");
2079 case Instruction::SetEQ:
2080 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2081 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2082 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2083 LHSVal->getName()+".off");
2084 InsertNewInstBefore(Add, I);
2085 const Type *UnsType = Add->getType()->getUnsignedVersion();
2086 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2087 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2088 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2089 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2090 }
2091 break; // (X == 13 | X == 15) -> no change
2092
Chris Lattner5c219462005-04-19 06:04:18 +00002093 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2094 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002095 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2096 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2097 return ReplaceInstUsesWith(I, RHS);
2098 }
2099 break;
2100 case Instruction::SetNE:
2101 switch (RHSCC) {
2102 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002103 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2104 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2105 return ReplaceInstUsesWith(I, LHS);
2106 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00002107 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002108 return ReplaceInstUsesWith(I, ConstantBool::True);
2109 }
2110 break;
2111 case Instruction::SetLT:
2112 switch (RHSCC) {
2113 default: assert(0 && "Unknown integer condition code!");
2114 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2115 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002116 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2117 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002118 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2119 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2120 return ReplaceInstUsesWith(I, RHS);
2121 }
2122 break;
2123 case Instruction::SetGT:
2124 switch (RHSCC) {
2125 default: assert(0 && "Unknown integer condition code!");
2126 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2127 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2128 return ReplaceInstUsesWith(I, LHS);
2129 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2130 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2131 return ReplaceInstUsesWith(I, ConstantBool::True);
2132 }
2133 }
2134 }
2135 }
Chris Lattner15212982005-09-18 03:42:07 +00002136
Chris Lattner113f4f42002-06-25 16:13:24 +00002137 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002138}
2139
Chris Lattnerc2076352004-02-16 01:20:27 +00002140// XorSelf - Implements: X ^ X --> 0
2141struct XorSelf {
2142 Value *RHS;
2143 XorSelf(Value *rhs) : RHS(rhs) {}
2144 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2145 Instruction *apply(BinaryOperator &Xor) const {
2146 return &Xor;
2147 }
2148};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002149
2150
Chris Lattner113f4f42002-06-25 16:13:24 +00002151Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002152 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002153 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002154
Chris Lattner81a7a232004-10-16 18:11:37 +00002155 if (isa<UndefValue>(Op1))
2156 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2157
Chris Lattnerc2076352004-02-16 01:20:27 +00002158 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2159 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2160 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002161 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002162 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002163
Chris Lattner97638592003-07-23 21:37:07 +00002164 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002165 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00002166 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00002167 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002168
Chris Lattner97638592003-07-23 21:37:07 +00002169 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002170 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002171 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002172 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002173 return new SetCondInst(SCI->getInverseCondition(),
2174 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002175
Chris Lattner8f2f5982003-11-05 01:06:05 +00002176 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002177 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2178 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002179 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2180 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002181 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002182 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002183 }
Chris Lattner023a4832004-06-18 06:07:51 +00002184
2185 // ~(~X & Y) --> (X | ~Y)
2186 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2187 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2188 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2189 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002190 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002191 Op0I->getOperand(1)->getName()+".not");
2192 InsertNewInstBefore(NotY, I);
2193 return BinaryOperator::createOr(Op0NotVal, NotY);
2194 }
2195 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002196
Chris Lattner97638592003-07-23 21:37:07 +00002197 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002198 switch (Op0I->getOpcode()) {
2199 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002200 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002201 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002202 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2203 return BinaryOperator::createSub(
2204 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002205 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002206 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002207 }
Chris Lattnere5806662003-11-04 23:50:51 +00002208 break;
2209 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002210 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002211 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2212 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002213 break;
2214 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002215 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002216 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002217 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002218 break;
2219 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002220 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002221 }
Chris Lattner183b3362004-04-09 19:05:30 +00002222
2223 // Try to fold constant and into select arguments.
2224 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002225 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002226 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002227 if (isa<PHINode>(Op0))
2228 if (Instruction *NV = FoldOpIntoPhi(I))
2229 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002230 }
2231
Chris Lattnerbb74e222003-03-10 23:06:50 +00002232 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002233 if (X == Op1)
2234 return ReplaceInstUsesWith(I,
2235 ConstantIntegral::getAllOnesValue(I.getType()));
2236
Chris Lattnerbb74e222003-03-10 23:06:50 +00002237 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002238 if (X == Op0)
2239 return ReplaceInstUsesWith(I,
2240 ConstantIntegral::getAllOnesValue(I.getType()));
2241
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002242 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002243 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002244 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2245 cast<BinaryOperator>(Op1I)->swapOperands();
2246 I.swapOperands();
2247 std::swap(Op0, Op1);
2248 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2249 I.swapOperands();
2250 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002251 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002252 } else if (Op1I->getOpcode() == Instruction::Xor) {
2253 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2254 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2255 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2256 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2257 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002258
2259 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002260 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002261 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2262 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002263 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002264 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2265 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002266 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002267 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002268 } else if (Op0I->getOpcode() == Instruction::Xor) {
2269 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2270 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2271 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2272 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002273 }
2274
Chris Lattner7aa2d472004-08-01 19:42:59 +00002275 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002276 Value *A, *B; ConstantInt *C1, *C2;
2277 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2278 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002279 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002280 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002281
Chris Lattner3ac7c262003-08-13 20:16:26 +00002282 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2283 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2284 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2285 return R;
2286
Chris Lattner113f4f42002-06-25 16:13:24 +00002287 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002288}
2289
Chris Lattner6862fbd2004-09-29 17:40:11 +00002290/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2291/// overflowed for this type.
2292static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2293 ConstantInt *In2) {
2294 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2295 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2296}
2297
2298static bool isPositive(ConstantInt *C) {
2299 return cast<ConstantSInt>(C)->getValue() >= 0;
2300}
2301
2302/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2303/// overflowed for this type.
2304static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2305 ConstantInt *In2) {
2306 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2307
2308 if (In1->getType()->isUnsigned())
2309 return cast<ConstantUInt>(Result)->getValue() <
2310 cast<ConstantUInt>(In1)->getValue();
2311 if (isPositive(In1) != isPositive(In2))
2312 return false;
2313 if (isPositive(In1))
2314 return cast<ConstantSInt>(Result)->getValue() <
2315 cast<ConstantSInt>(In1)->getValue();
2316 return cast<ConstantSInt>(Result)->getValue() >
2317 cast<ConstantSInt>(In1)->getValue();
2318}
2319
Chris Lattner0798af32005-01-13 20:14:25 +00002320/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2321/// code necessary to compute the offset from the base pointer (without adding
2322/// in the base pointer). Return the result as a signed integer of intptr size.
2323static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2324 TargetData &TD = IC.getTargetData();
2325 gep_type_iterator GTI = gep_type_begin(GEP);
2326 const Type *UIntPtrTy = TD.getIntPtrType();
2327 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2328 Value *Result = Constant::getNullValue(SIntPtrTy);
2329
2330 // Build a mask for high order bits.
2331 uint64_t PtrSizeMask = ~0ULL;
2332 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2333
Chris Lattner0798af32005-01-13 20:14:25 +00002334 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2335 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002336 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002337 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2338 SIntPtrTy);
2339 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2340 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002341 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002342 Scale = ConstantExpr::getMul(OpC, Scale);
2343 if (Constant *RC = dyn_cast<Constant>(Result))
2344 Result = ConstantExpr::getAdd(RC, Scale);
2345 else {
2346 // Emit an add instruction.
2347 Result = IC.InsertNewInstBefore(
2348 BinaryOperator::createAdd(Result, Scale,
2349 GEP->getName()+".offs"), I);
2350 }
2351 }
2352 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002353 // Convert to correct type.
2354 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2355 Op->getName()+".c"), I);
2356 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002357 // We'll let instcombine(mul) convert this to a shl if possible.
2358 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2359 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002360
2361 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002362 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002363 GEP->getName()+".offs"), I);
2364 }
2365 }
2366 return Result;
2367}
2368
2369/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2370/// else. At this point we know that the GEP is on the LHS of the comparison.
2371Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2372 Instruction::BinaryOps Cond,
2373 Instruction &I) {
2374 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002375
2376 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2377 if (isa<PointerType>(CI->getOperand(0)->getType()))
2378 RHS = CI->getOperand(0);
2379
Chris Lattner0798af32005-01-13 20:14:25 +00002380 Value *PtrBase = GEPLHS->getOperand(0);
2381 if (PtrBase == RHS) {
2382 // As an optimization, we don't actually have to compute the actual value of
2383 // OFFSET if this is a seteq or setne comparison, just return whether each
2384 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002385 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2386 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002387 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2388 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00002389 bool EmitIt = true;
2390 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2391 if (isa<UndefValue>(C)) // undef index -> undef.
2392 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2393 if (C->isNullValue())
2394 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002395 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2396 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00002397 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00002398 return ReplaceInstUsesWith(I, // No comparison is needed here.
2399 ConstantBool::get(Cond == Instruction::SetNE));
2400 }
2401
2402 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002403 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00002404 new SetCondInst(Cond, GEPLHS->getOperand(i),
2405 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2406 if (InVal == 0)
2407 InVal = Comp;
2408 else {
2409 InVal = InsertNewInstBefore(InVal, I);
2410 InsertNewInstBefore(Comp, I);
2411 if (Cond == Instruction::SetNE) // True if any are unequal
2412 InVal = BinaryOperator::createOr(InVal, Comp);
2413 else // True if all are equal
2414 InVal = BinaryOperator::createAnd(InVal, Comp);
2415 }
2416 }
2417 }
2418
2419 if (InVal)
2420 return InVal;
2421 else
2422 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2423 ConstantBool::get(Cond == Instruction::SetEQ));
2424 }
Chris Lattner0798af32005-01-13 20:14:25 +00002425
2426 // Only lower this if the setcc is the only user of the GEP or if we expect
2427 // the result to fold to a constant!
2428 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2429 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2430 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2431 return new SetCondInst(Cond, Offset,
2432 Constant::getNullValue(Offset->getType()));
2433 }
2434 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002435 // If the base pointers are different, but the indices are the same, just
2436 // compare the base pointer.
2437 if (PtrBase != GEPRHS->getOperand(0)) {
2438 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002439 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00002440 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002441 if (IndicesTheSame)
2442 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2443 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2444 IndicesTheSame = false;
2445 break;
2446 }
2447
2448 // If all indices are the same, just compare the base pointers.
2449 if (IndicesTheSame)
2450 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2451 GEPRHS->getOperand(0));
2452
2453 // Otherwise, the base pointers are different and the indices are
2454 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00002455 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002456 }
Chris Lattner0798af32005-01-13 20:14:25 +00002457
Chris Lattner81e84172005-01-13 22:25:21 +00002458 // If one of the GEPs has all zero indices, recurse.
2459 bool AllZeros = true;
2460 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2461 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2462 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2463 AllZeros = false;
2464 break;
2465 }
2466 if (AllZeros)
2467 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2468 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00002469
2470 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00002471 AllZeros = true;
2472 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2473 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2474 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2475 AllZeros = false;
2476 break;
2477 }
2478 if (AllZeros)
2479 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2480
Chris Lattner4fa89822005-01-14 00:20:05 +00002481 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2482 // If the GEPs only differ by one index, compare it.
2483 unsigned NumDifferences = 0; // Keep track of # differences.
2484 unsigned DiffOperand = 0; // The operand that differs.
2485 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2486 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002487 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2488 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002489 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00002490 NumDifferences = 2;
2491 break;
2492 } else {
2493 if (NumDifferences++) break;
2494 DiffOperand = i;
2495 }
2496 }
2497
2498 if (NumDifferences == 0) // SAME GEP?
2499 return ReplaceInstUsesWith(I, // No comparison is needed here.
2500 ConstantBool::get(Cond == Instruction::SetEQ));
2501 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002502 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2503 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00002504
2505 // Convert the operands to signed values to make sure to perform a
2506 // signed comparison.
2507 const Type *NewTy = LHSV->getType()->getSignedVersion();
2508 if (LHSV->getType() != NewTy)
2509 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2510 LHSV->getName()), I);
2511 if (RHSV->getType() != NewTy)
2512 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2513 RHSV->getName()), I);
2514 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00002515 }
2516 }
2517
Chris Lattner0798af32005-01-13 20:14:25 +00002518 // Only lower this if the setcc is the only user of the GEP or if we expect
2519 // the result to fold to a constant!
2520 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2521 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2522 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2523 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2524 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2525 return new SetCondInst(Cond, L, R);
2526 }
2527 }
2528 return 0;
2529}
2530
2531
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002532Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002533 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002534 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2535 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002536
2537 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002538 if (Op0 == Op1)
2539 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002540
Chris Lattner81a7a232004-10-16 18:11:37 +00002541 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2542 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2543
Chris Lattner15ff1e12004-11-14 07:33:16 +00002544 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2545 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002546 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2547 isa<ConstantPointerNull>(Op0)) &&
2548 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00002549 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002550 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2551
2552 // setcc's with boolean values can always be turned into bitwise operations
2553 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002554 switch (I.getOpcode()) {
2555 default: assert(0 && "Invalid setcc instruction!");
2556 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002557 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002558 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002559 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002560 }
Chris Lattner4456da62004-08-11 00:50:51 +00002561 case Instruction::SetNE:
2562 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002563
Chris Lattner4456da62004-08-11 00:50:51 +00002564 case Instruction::SetGT:
2565 std::swap(Op0, Op1); // Change setgt -> setlt
2566 // FALL THROUGH
2567 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2568 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2569 InsertNewInstBefore(Not, I);
2570 return BinaryOperator::createAnd(Not, Op1);
2571 }
2572 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002573 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002574 // FALL THROUGH
2575 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2576 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2577 InsertNewInstBefore(Not, I);
2578 return BinaryOperator::createOr(Not, Op1);
2579 }
2580 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002581 }
2582
Chris Lattner2dd01742004-06-09 04:24:29 +00002583 // See if we are doing a comparison between a constant and an instruction that
2584 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002585 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002586 // Check to see if we are comparing against the minimum or maximum value...
2587 if (CI->isMinValue()) {
2588 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2589 return ReplaceInstUsesWith(I, ConstantBool::False);
2590 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2591 return ReplaceInstUsesWith(I, ConstantBool::True);
2592 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2593 return BinaryOperator::createSetEQ(Op0, Op1);
2594 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2595 return BinaryOperator::createSetNE(Op0, Op1);
2596
2597 } else if (CI->isMaxValue()) {
2598 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2599 return ReplaceInstUsesWith(I, ConstantBool::False);
2600 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2601 return ReplaceInstUsesWith(I, ConstantBool::True);
2602 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2603 return BinaryOperator::createSetEQ(Op0, Op1);
2604 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2605 return BinaryOperator::createSetNE(Op0, Op1);
2606
2607 // Comparing against a value really close to min or max?
2608 } else if (isMinValuePlusOne(CI)) {
2609 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2610 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2611 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2612 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2613
2614 } else if (isMaxValueMinusOne(CI)) {
2615 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2616 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2617 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2618 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2619 }
2620
2621 // If we still have a setle or setge instruction, turn it into the
2622 // appropriate setlt or setgt instruction. Since the border cases have
2623 // already been handled above, this requires little checking.
2624 //
2625 if (I.getOpcode() == Instruction::SetLE)
2626 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2627 if (I.getOpcode() == Instruction::SetGE)
2628 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2629
Chris Lattnere1e10e12004-05-25 06:32:08 +00002630 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002631 switch (LHSI->getOpcode()) {
2632 case Instruction::And:
2633 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2634 LHSI->getOperand(0)->hasOneUse()) {
2635 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2636 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2637 // happens a LOT in code produced by the C front-end, for bitfield
2638 // access.
2639 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2640 ConstantUInt *ShAmt;
2641 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2642 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2643 const Type *Ty = LHSI->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002644
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002645 // We can fold this as long as we can't shift unknown bits
2646 // into the mask. This can only happen with signed shift
2647 // rights, as they sign-extend.
2648 if (ShAmt) {
2649 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002650 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002651 if (!CanFold) {
2652 // To test for the bad case of the signed shr, see if any
2653 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00002654 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2655 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2656
2657 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002658 Constant *ShVal =
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002659 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2660 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2661 CanFold = true;
2662 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002663
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002664 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002665 Constant *NewCst;
2666 if (Shift->getOpcode() == Instruction::Shl)
2667 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2668 else
2669 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002670
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002671 // Check to see if we are shifting out any of the bits being
2672 // compared.
2673 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2674 // If we shifted bits out, the fold is not going to work out.
2675 // As a special case, check to see if this means that the
2676 // result is always true or false now.
2677 if (I.getOpcode() == Instruction::SetEQ)
2678 return ReplaceInstUsesWith(I, ConstantBool::False);
2679 if (I.getOpcode() == Instruction::SetNE)
2680 return ReplaceInstUsesWith(I, ConstantBool::True);
2681 } else {
2682 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002683 Constant *NewAndCST;
2684 if (Shift->getOpcode() == Instruction::Shl)
2685 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2686 else
2687 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2688 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002689 LHSI->setOperand(0, Shift->getOperand(0));
2690 WorkList.push_back(Shift); // Shift is dead.
2691 AddUsesToWorkList(I);
2692 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002693 }
2694 }
Chris Lattner35167c32004-06-09 07:59:58 +00002695 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002696 }
2697 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002698
Chris Lattner272d5ca2004-09-28 18:22:15 +00002699 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2700 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2701 switch (I.getOpcode()) {
2702 default: break;
2703 case Instruction::SetEQ:
2704 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002705 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2706
2707 // Check that the shift amount is in range. If not, don't perform
2708 // undefined shifts. When the shift is visited it will be
2709 // simplified.
2710 if (ShAmt->getValue() >= TypeBits)
2711 break;
2712
Chris Lattner272d5ca2004-09-28 18:22:15 +00002713 // If we are comparing against bits always shifted out, the
2714 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002715 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00002716 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2717 if (Comp != CI) {// Comparing against a bit that we know is zero.
2718 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2719 Constant *Cst = ConstantBool::get(IsSetNE);
2720 return ReplaceInstUsesWith(I, Cst);
2721 }
2722
2723 if (LHSI->hasOneUse()) {
2724 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002725 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002726 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2727
2728 Constant *Mask;
2729 if (CI->getType()->isUnsigned()) {
2730 Mask = ConstantUInt::get(CI->getType(), Val);
2731 } else if (ShAmtVal != 0) {
2732 Mask = ConstantSInt::get(CI->getType(), Val);
2733 } else {
2734 Mask = ConstantInt::getAllOnesValue(CI->getType());
2735 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002736
Chris Lattner272d5ca2004-09-28 18:22:15 +00002737 Instruction *AndI =
2738 BinaryOperator::createAnd(LHSI->getOperand(0),
2739 Mask, LHSI->getName()+".mask");
2740 Value *And = InsertNewInstBefore(AndI, I);
2741 return new SetCondInst(I.getOpcode(), And,
2742 ConstantExpr::getUShr(CI, ShAmt));
2743 }
2744 }
2745 }
2746 }
2747 break;
2748
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002749 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002750 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002751 switch (I.getOpcode()) {
2752 default: break;
2753 case Instruction::SetEQ:
2754 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002755
2756 // Check that the shift amount is in range. If not, don't perform
2757 // undefined shifts. When the shift is visited it will be
2758 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00002759 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00002760 if (ShAmt->getValue() >= TypeBits)
2761 break;
2762
Chris Lattner1023b872004-09-27 16:18:50 +00002763 // If we are comparing against bits always shifted out, the
2764 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002765 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00002766 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002767
Chris Lattner1023b872004-09-27 16:18:50 +00002768 if (Comp != CI) {// Comparing against a bit that we know is zero.
2769 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2770 Constant *Cst = ConstantBool::get(IsSetNE);
2771 return ReplaceInstUsesWith(I, Cst);
2772 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002773
Chris Lattner1023b872004-09-27 16:18:50 +00002774 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002775 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002776
Chris Lattner1023b872004-09-27 16:18:50 +00002777 // Otherwise strength reduce the shift into an and.
2778 uint64_t Val = ~0ULL; // All ones.
2779 Val <<= ShAmtVal; // Shift over to the right spot.
2780
2781 Constant *Mask;
2782 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00002783 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00002784 Mask = ConstantUInt::get(CI->getType(), Val);
2785 } else {
2786 Mask = ConstantSInt::get(CI->getType(), Val);
2787 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002788
Chris Lattner1023b872004-09-27 16:18:50 +00002789 Instruction *AndI =
2790 BinaryOperator::createAnd(LHSI->getOperand(0),
2791 Mask, LHSI->getName()+".mask");
2792 Value *And = InsertNewInstBefore(AndI, I);
2793 return new SetCondInst(I.getOpcode(), And,
2794 ConstantExpr::getShl(CI, ShAmt));
2795 }
2796 break;
2797 }
2798 }
2799 }
2800 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002801
Chris Lattner6862fbd2004-09-29 17:40:11 +00002802 case Instruction::Div:
2803 // Fold: (div X, C1) op C2 -> range check
2804 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2805 // Fold this div into the comparison, producing a range check.
2806 // Determine, based on the divide type, what the range is being
2807 // checked. If there is an overflow on the low or high side, remember
2808 // it, otherwise compute the range [low, hi) bounding the new value.
2809 bool LoOverflow = false, HiOverflow = 0;
2810 ConstantInt *LoBound = 0, *HiBound = 0;
2811
2812 ConstantInt *Prod;
2813 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2814
Chris Lattnera92af962004-10-11 19:40:04 +00002815 Instruction::BinaryOps Opcode = I.getOpcode();
2816
Chris Lattner6862fbd2004-09-29 17:40:11 +00002817 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2818 } else if (LHSI->getType()->isUnsigned()) { // udiv
2819 LoBound = Prod;
2820 LoOverflow = ProdOV;
2821 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2822 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2823 if (CI->isNullValue()) { // (X / pos) op 0
2824 // Can't overflow.
2825 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2826 HiBound = DivRHS;
2827 } else if (isPositive(CI)) { // (X / pos) op pos
2828 LoBound = Prod;
2829 LoOverflow = ProdOV;
2830 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2831 } else { // (X / pos) op neg
2832 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2833 LoOverflow = AddWithOverflow(LoBound, Prod,
2834 cast<ConstantInt>(DivRHSH));
2835 HiBound = Prod;
2836 HiOverflow = ProdOV;
2837 }
2838 } else { // Divisor is < 0.
2839 if (CI->isNullValue()) { // (X / neg) op 0
2840 LoBound = AddOne(DivRHS);
2841 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00002842 if (HiBound == DivRHS)
2843 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00002844 } else if (isPositive(CI)) { // (X / neg) op pos
2845 HiOverflow = LoOverflow = ProdOV;
2846 if (!LoOverflow)
2847 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2848 HiBound = AddOne(Prod);
2849 } else { // (X / neg) op neg
2850 LoBound = Prod;
2851 LoOverflow = HiOverflow = ProdOV;
2852 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2853 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002854
Chris Lattnera92af962004-10-11 19:40:04 +00002855 // Dividing by a negate swaps the condition.
2856 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002857 }
2858
2859 if (LoBound) {
2860 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002861 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002862 default: assert(0 && "Unhandled setcc opcode!");
2863 case Instruction::SetEQ:
2864 if (LoOverflow && HiOverflow)
2865 return ReplaceInstUsesWith(I, ConstantBool::False);
2866 else if (HiOverflow)
2867 return new SetCondInst(Instruction::SetGE, X, LoBound);
2868 else if (LoOverflow)
2869 return new SetCondInst(Instruction::SetLT, X, HiBound);
2870 else
2871 return InsertRangeTest(X, LoBound, HiBound, true, I);
2872 case Instruction::SetNE:
2873 if (LoOverflow && HiOverflow)
2874 return ReplaceInstUsesWith(I, ConstantBool::True);
2875 else if (HiOverflow)
2876 return new SetCondInst(Instruction::SetLT, X, LoBound);
2877 else if (LoOverflow)
2878 return new SetCondInst(Instruction::SetGE, X, HiBound);
2879 else
2880 return InsertRangeTest(X, LoBound, HiBound, false, I);
2881 case Instruction::SetLT:
2882 if (LoOverflow)
2883 return ReplaceInstUsesWith(I, ConstantBool::False);
2884 return new SetCondInst(Instruction::SetLT, X, LoBound);
2885 case Instruction::SetGT:
2886 if (HiOverflow)
2887 return ReplaceInstUsesWith(I, ConstantBool::False);
2888 return new SetCondInst(Instruction::SetGE, X, HiBound);
2889 }
2890 }
2891 }
2892 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002893 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002894
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002895 // Simplify seteq and setne instructions...
2896 if (I.getOpcode() == Instruction::SetEQ ||
2897 I.getOpcode() == Instruction::SetNE) {
2898 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2899
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002900 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002901 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002902 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2903 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002904 case Instruction::Rem:
2905 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2906 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2907 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00002908 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
2909 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
2910 if (isPowerOf2_64(V)) {
2911 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00002912 const Type *UTy = BO->getType()->getUnsignedVersion();
2913 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2914 UTy, "tmp"), I);
2915 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2916 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2917 RHSCst, BO->getName()), I);
2918 return BinaryOperator::create(I.getOpcode(), NewRem,
2919 Constant::getNullValue(UTy));
2920 }
Chris Lattner22d00a82005-08-02 19:16:58 +00002921 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002922 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00002923
Chris Lattnerc992add2003-08-13 05:33:12 +00002924 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002925 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2926 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002927 if (BO->hasOneUse())
2928 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2929 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002930 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002931 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2932 // efficiently invertible, or if the add has just this one use.
2933 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002934
Chris Lattnerc992add2003-08-13 05:33:12 +00002935 if (Value *NegVal = dyn_castNegVal(BOp1))
2936 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2937 else if (Value *NegVal = dyn_castNegVal(BOp0))
2938 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002939 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002940 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2941 BO->setName("");
2942 InsertNewInstBefore(Neg, I);
2943 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2944 }
2945 }
2946 break;
2947 case Instruction::Xor:
2948 // For the xor case, we can xor two constants together, eliminating
2949 // the explicit xor.
2950 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2951 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002952 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002953
2954 // FALLTHROUGH
2955 case Instruction::Sub:
2956 // Replace (([sub|xor] A, B) != 0) with (A != B)
2957 if (CI->isNullValue())
2958 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2959 BO->getOperand(1));
2960 break;
2961
2962 case Instruction::Or:
2963 // If bits are being or'd in that are not present in the constant we
2964 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002965 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002966 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002967 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002968 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002969 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002970 break;
2971
2972 case Instruction::And:
2973 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002974 // If bits are being compared against that are and'd out, then the
2975 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002976 if (!ConstantExpr::getAnd(CI,
2977 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002978 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002979
Chris Lattner35167c32004-06-09 07:59:58 +00002980 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002981 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002982 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2983 Instruction::SetNE, Op0,
2984 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002985
Chris Lattnerc992add2003-08-13 05:33:12 +00002986 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2987 // to be a signed value as appropriate.
2988 if (isSignBit(BOC)) {
2989 Value *X = BO->getOperand(0);
2990 // If 'X' is not signed, insert a cast now...
2991 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002992 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002993 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002994 }
2995 return new SetCondInst(isSetNE ? Instruction::SetLT :
2996 Instruction::SetGE, X,
2997 Constant::getNullValue(X->getType()));
2998 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002999
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003000 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00003001 if (CI->isNullValue() && isHighOnes(BOC)) {
3002 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003003 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003004
3005 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003006 if (NegX->getType()->isSigned()) {
3007 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3008 X = InsertCastBefore(X, DestTy, I);
3009 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003010 }
3011
3012 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003013 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003014 }
3015
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003016 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003017 default: break;
3018 }
3019 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00003020 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00003021 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00003022 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3023 Value *CastOp = Cast->getOperand(0);
3024 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003025 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00003026 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003027 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003028 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00003029 "Source and destination signednesses should differ!");
3030 if (Cast->getType()->isSigned()) {
3031 // If this is a signed comparison, check for comparisons in the
3032 // vicinity of zero.
3033 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3034 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003035 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003036 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003037 else if (I.getOpcode() == Instruction::SetGT &&
3038 cast<ConstantSInt>(CI)->getValue() == -1)
3039 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003040 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003041 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003042 } else {
3043 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3044 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003045 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00003046 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003047 return BinaryOperator::createSetGT(CastOp,
3048 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003049 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003050 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00003051 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003052 return BinaryOperator::createSetLT(CastOp,
3053 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003054 }
3055 }
3056 }
Chris Lattnere967b342003-06-04 05:10:11 +00003057 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003058 }
3059
Chris Lattner77c32c32005-04-23 15:31:55 +00003060 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3061 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3062 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3063 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00003064 case Instruction::GetElementPtr:
3065 if (RHSC->isNullValue()) {
3066 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3067 bool isAllZeros = true;
3068 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3069 if (!isa<Constant>(LHSI->getOperand(i)) ||
3070 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3071 isAllZeros = false;
3072 break;
3073 }
3074 if (isAllZeros)
3075 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3076 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3077 }
3078 break;
3079
Chris Lattner77c32c32005-04-23 15:31:55 +00003080 case Instruction::PHI:
3081 if (Instruction *NV = FoldOpIntoPhi(I))
3082 return NV;
3083 break;
3084 case Instruction::Select:
3085 // If either operand of the select is a constant, we can fold the
3086 // comparison into the select arms, which will cause one to be
3087 // constant folded and the select turned into a bitwise or.
3088 Value *Op1 = 0, *Op2 = 0;
3089 if (LHSI->hasOneUse()) {
3090 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3091 // Fold the known value into the constant operand.
3092 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3093 // Insert a new SetCC of the other select operand.
3094 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3095 LHSI->getOperand(2), RHSC,
3096 I.getName()), I);
3097 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3098 // Fold the known value into the constant operand.
3099 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3100 // Insert a new SetCC of the other select operand.
3101 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3102 LHSI->getOperand(1), RHSC,
3103 I.getName()), I);
3104 }
3105 }
Jeff Cohen82639852005-04-23 21:38:35 +00003106
Chris Lattner77c32c32005-04-23 15:31:55 +00003107 if (Op1)
3108 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3109 break;
3110 }
3111 }
3112
Chris Lattner0798af32005-01-13 20:14:25 +00003113 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3114 if (User *GEP = dyn_castGetElementPtr(Op0))
3115 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3116 return NI;
3117 if (User *GEP = dyn_castGetElementPtr(Op1))
3118 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3119 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3120 return NI;
3121
Chris Lattner16930792003-11-03 04:25:02 +00003122 // Test to see if the operands of the setcc are casted versions of other
3123 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00003124 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3125 Value *CastOp0 = CI->getOperand(0);
3126 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00003127 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00003128 (I.getOpcode() == Instruction::SetEQ ||
3129 I.getOpcode() == Instruction::SetNE)) {
3130 // We keep moving the cast from the left operand over to the right
3131 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00003132 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003133
Chris Lattner16930792003-11-03 04:25:02 +00003134 // If operand #1 is a cast instruction, see if we can eliminate it as
3135 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00003136 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3137 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00003138 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00003139 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003140
Chris Lattner16930792003-11-03 04:25:02 +00003141 // If Op1 is a constant, we can fold the cast into the constant.
3142 if (Op1->getType() != Op0->getType())
3143 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3144 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3145 } else {
3146 // Otherwise, cast the RHS right before the setcc
3147 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3148 InsertNewInstBefore(cast<Instruction>(Op1), I);
3149 }
3150 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3151 }
3152
Chris Lattner6444c372003-11-03 05:17:03 +00003153 // Handle the special case of: setcc (cast bool to X), <cst>
3154 // This comes up when you have code like
3155 // int X = A < B;
3156 // if (X) ...
3157 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003158 // with a constant or another cast from the same type.
3159 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3160 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3161 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00003162 }
Chris Lattner113f4f42002-06-25 16:13:24 +00003163 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003164}
3165
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003166// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3167// We only handle extending casts so far.
3168//
3169Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3170 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3171 const Type *SrcTy = LHSCIOp->getType();
3172 const Type *DestTy = SCI.getOperand(0)->getType();
3173 Value *RHSCIOp;
3174
3175 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00003176 return 0;
3177
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003178 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3179 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3180 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3181
3182 // Is this a sign or zero extension?
3183 bool isSignSrc = SrcTy->isSigned();
3184 bool isSignDest = DestTy->isSigned();
3185
3186 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3187 // Not an extension from the same type?
3188 RHSCIOp = CI->getOperand(0);
3189 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3190 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3191 // Compute the constant that would happen if we truncated to SrcTy then
3192 // reextended to DestTy.
3193 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3194
3195 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3196 RHSCIOp = Res;
3197 } else {
3198 // If the value cannot be represented in the shorter type, we cannot emit
3199 // a simple comparison.
3200 if (SCI.getOpcode() == Instruction::SetEQ)
3201 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3202 if (SCI.getOpcode() == Instruction::SetNE)
3203 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3204
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003205 // Evaluate the comparison for LT.
3206 Value *Result;
3207 if (DestTy->isSigned()) {
3208 // We're performing a signed comparison.
3209 if (isSignSrc) {
3210 // Signed extend and signed comparison.
3211 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3212 Result = ConstantBool::False;
3213 else
3214 Result = ConstantBool::True; // X < (large) --> true
3215 } else {
3216 // Unsigned extend and signed comparison.
3217 if (cast<ConstantSInt>(CI)->getValue() < 0)
3218 Result = ConstantBool::False;
3219 else
3220 Result = ConstantBool::True;
3221 }
3222 } else {
3223 // We're performing an unsigned comparison.
3224 if (!isSignSrc) {
3225 // Unsigned extend & compare -> always true.
3226 Result = ConstantBool::True;
3227 } else {
3228 // We're performing an unsigned comp with a sign extended value.
3229 // This is true if the input is >= 0. [aka >s -1]
3230 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3231 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3232 NegOne, SCI.getName()), SCI);
3233 }
Reid Spencer279fa252004-11-28 21:31:15 +00003234 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003235
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003236 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003237 if (SCI.getOpcode() == Instruction::SetLT) {
3238 return ReplaceInstUsesWith(SCI, Result);
3239 } else {
3240 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3241 if (Constant *CI = dyn_cast<Constant>(Result))
3242 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3243 else
3244 return BinaryOperator::createNot(Result);
3245 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003246 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003247 } else {
3248 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00003249 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003250
Chris Lattner252a8452005-06-16 03:00:08 +00003251 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003252 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3253}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003254
Chris Lattnere8d6c602003-03-10 19:16:08 +00003255Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003256 assert(I.getOperand(1)->getType() == Type::UByteTy);
3257 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003258 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003259
3260 // shl X, 0 == X and shr X, 0 == X
3261 // shl 0, X == 0 and shr 0, X == 0
3262 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003263 Op0 == Constant::getNullValue(Op0->getType()))
3264 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003265
Chris Lattner81a7a232004-10-16 18:11:37 +00003266 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3267 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003268 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003269 else // undef << X -> 0 AND undef >>u X -> 0
3270 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3271 }
3272 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00003273 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00003274 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3275 else
3276 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3277 }
3278
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003279 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3280 if (!isLeftShift)
3281 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3282 if (CSI->isAllOnesValue())
3283 return ReplaceInstUsesWith(I, CSI);
3284
Chris Lattner183b3362004-04-09 19:05:30 +00003285 // Try to fold constant and into select arguments.
3286 if (isa<Constant>(Op0))
3287 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003288 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003289 return R;
3290
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00003291 // See if we can turn a signed shr into an unsigned shr.
3292 if (!isLeftShift && I.getType()->isSigned()) {
3293 if (MaskedValueIsZero(Op0, ConstantInt::getMinValue(I.getType()))) {
3294 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3295 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3296 I.getName()), I);
3297 return new CastInst(V, I.getType());
3298 }
3299 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003300
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003301 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003302 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3303 // of a signed value.
3304 //
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003305 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003306 if (CUI->getValue() >= TypeBits) {
3307 if (!Op0->getType()->isSigned() || isLeftShift)
3308 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3309 else {
3310 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3311 return &I;
3312 }
3313 }
Chris Lattner55f3d942002-09-10 23:04:09 +00003314
Chris Lattnerede3fe02003-08-13 04:18:28 +00003315 // ((X*C1) << C2) == (X * (C1 << C2))
3316 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3317 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3318 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003319 return BinaryOperator::createMul(BO->getOperand(0),
3320 ConstantExpr::getShl(BOOp, CUI));
Misha Brukmanb1c93172005-04-21 23:48:37 +00003321
Chris Lattner183b3362004-04-09 19:05:30 +00003322 // Try to fold constant and into select arguments.
3323 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003324 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003325 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003326 if (isa<PHINode>(Op0))
3327 if (Instruction *NV = FoldOpIntoPhi(I))
3328 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00003329
Chris Lattner86102b82005-01-01 16:22:27 +00003330 if (Op0->hasOneUse()) {
3331 // If this is a SHL of a sign-extending cast, see if we can turn the input
3332 // into a zero extending cast (a simple strength reduction).
3333 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3334 const Type *SrcTy = CI->getOperand(0)->getType();
3335 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003336 SrcTy->getPrimitiveSizeInBits() <
3337 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00003338 // We can change it to a zero extension if we are shifting out all of
3339 // the sign extended bits. To check this, form a mask of all of the
3340 // sign extend bits, then shift them left and see if we have anything
3341 // left.
3342 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3343 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3344 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3345 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3346 // If the shift is nuking all of the sign bits, change this to a
3347 // zero extension cast. To do this, cast the cast input to
3348 // unsigned, then to the requested size.
3349 Value *CastOp = CI->getOperand(0);
3350 Instruction *NC =
3351 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3352 CI->getName()+".uns");
3353 NC = InsertNewInstBefore(NC, I);
3354 // Finally, insert a replacement for CI.
3355 NC = new CastInst(NC, CI->getType(), CI->getName());
3356 CI->setName("");
3357 NC = InsertNewInstBefore(NC, I);
3358 WorkList.push_back(CI); // Delete CI later.
3359 I.setOperand(0, NC);
3360 return &I; // The SHL operand was modified.
3361 }
3362 }
3363 }
3364
Chris Lattner27cb9db2005-09-18 05:12:10 +00003365 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3366 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003367 Value *V1, *V2, *V3;
3368 ConstantInt *CC;
Chris Lattner27cb9db2005-09-18 05:12:10 +00003369 switch (Op0BO->getOpcode()) {
3370 default: break;
3371 case Instruction::Add:
3372 case Instruction::And:
3373 case Instruction::Or:
3374 case Instruction::Xor:
3375 // These operators commute.
3376 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003377 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3378 match(Op0BO->getOperand(1),
3379 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == CUI) {
3380 Instruction *YS = new ShiftInst(Instruction::Shl,
3381 Op0BO->getOperand(0), CUI,
3382 Op0BO->getName());
3383 InsertNewInstBefore(YS, I); // (Y << C)
3384 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3385 V1,
3386 Op0BO->getOperand(1)->getName());
3387 InsertNewInstBefore(X, I); // (X + (Y << C))
3388 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3389 C2 = ConstantExpr::getShl(C2, CUI);
3390 return BinaryOperator::createAnd(X, C2);
3391 }
3392
3393 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
3394 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3395 match(Op0BO->getOperand(1),
3396 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3397 m_ConstantInt(CC))) && V2 == CUI &&
3398 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
3399 Instruction *YS = new ShiftInst(Instruction::Shl,
3400 Op0BO->getOperand(0), CUI,
3401 Op0BO->getName());
3402 InsertNewInstBefore(YS, I); // (Y << C)
3403 Instruction *XM =
3404 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, CUI),
3405 V1->getName()+".mask");
3406 InsertNewInstBefore(XM, I); // X & (CC << C)
3407
3408 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3409 }
3410
3411 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00003412 case Instruction::Sub:
3413 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003414 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3415 match(Op0BO->getOperand(0),
3416 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == CUI) {
3417 Instruction *YS = new ShiftInst(Instruction::Shl,
3418 Op0BO->getOperand(1), CUI,
3419 Op0BO->getName());
3420 InsertNewInstBefore(YS, I); // (Y << C)
3421 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3422 V1,
3423 Op0BO->getOperand(0)->getName());
3424 InsertNewInstBefore(X, I); // (X + (Y << C))
3425 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3426 C2 = ConstantExpr::getShl(C2, CUI);
3427 return BinaryOperator::createAnd(X, C2);
3428 }
3429
3430 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3431 match(Op0BO->getOperand(0),
3432 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3433 m_ConstantInt(CC))) && V2 == CUI &&
3434 cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
3435 Instruction *YS = new ShiftInst(Instruction::Shl,
3436 Op0BO->getOperand(1), CUI,
3437 Op0BO->getName());
3438 InsertNewInstBefore(YS, I); // (Y << C)
3439 Instruction *XM =
3440 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, CUI),
3441 V1->getName()+".mask");
3442 InsertNewInstBefore(XM, I); // X & (CC << C)
3443
3444 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3445 }
3446
Chris Lattner27cb9db2005-09-18 05:12:10 +00003447 break;
3448 }
3449
3450
3451 // If the operand is an bitwise operator with a constant RHS, and the
3452 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003453 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3454 bool isValid = true; // Valid only for And, Or, Xor
3455 bool highBitSet = false; // Transform if high bit of constant set?
3456
3457 switch (Op0BO->getOpcode()) {
3458 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003459 case Instruction::Add:
3460 isValid = isLeftShift;
3461 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003462 case Instruction::Or:
3463 case Instruction::Xor:
3464 highBitSet = false;
3465 break;
3466 case Instruction::And:
3467 highBitSet = true;
3468 break;
3469 }
3470
3471 // If this is a signed shift right, and the high bit is modified
3472 // by the logical operation, do not perform the transformation.
3473 // The highBitSet boolean indicates the value of the high bit of
3474 // the constant which would cause it to be modified for this
3475 // operation.
3476 //
3477 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3478 uint64_t Val = Op0C->getRawValue();
3479 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3480 }
3481
3482 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003483 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003484
3485 Instruction *NewShift =
3486 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3487 Op0BO->getName());
3488 Op0BO->setName("");
3489 InsertNewInstBefore(NewShift, I);
3490
3491 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3492 NewRHS);
3493 }
3494 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00003495 }
Chris Lattner86102b82005-01-01 16:22:27 +00003496 }
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003497
Chris Lattner3204d4e2003-07-24 17:52:58 +00003498 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003499 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00003500 if (ConstantUInt *ShiftAmt1C =
3501 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003502 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3503 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003504
Chris Lattner3204d4e2003-07-24 17:52:58 +00003505 // Check for (A << c1) << c2 and (A >> c1) >> c2
3506 if (I.getOpcode() == Op0SI->getOpcode()) {
3507 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003508 if (Op0->getType()->getPrimitiveSizeInBits() < Amt)
3509 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner3204d4e2003-07-24 17:52:58 +00003510 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3511 ConstantUInt::get(Type::UByteTy, Amt));
3512 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003513
Chris Lattnerab780df2003-07-24 18:38:56 +00003514 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3515 // signed types, we can only support the (A >> c1) << c2 configuration,
3516 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003517 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003518 // Calculate bitmask for what gets shifted off the edge...
3519 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003520 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003521 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003522 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003523 C = ConstantExpr::getShr(C, ShiftAmt1C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003524
Chris Lattner3204d4e2003-07-24 17:52:58 +00003525 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003526 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3527 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00003528 InsertNewInstBefore(Mask, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003529
Chris Lattner3204d4e2003-07-24 17:52:58 +00003530 // Figure out what flavor of shift we should use...
3531 if (ShiftAmt1 == ShiftAmt2)
3532 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3533 else if (ShiftAmt1 < ShiftAmt2) {
3534 return new ShiftInst(I.getOpcode(), Mask,
3535 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3536 } else {
3537 return new ShiftInst(Op0SI->getOpcode(), Mask,
3538 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3539 }
3540 }
3541 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003542 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00003543
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003544 return 0;
3545}
3546
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003547enum CastType {
3548 Noop = 0,
3549 Truncate = 1,
3550 Signext = 2,
3551 Zeroext = 3
3552};
3553
3554/// getCastType - In the future, we will split the cast instruction into these
3555/// various types. Until then, we have to do the analysis here.
3556static CastType getCastType(const Type *Src, const Type *Dest) {
3557 assert(Src->isIntegral() && Dest->isIntegral() &&
3558 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003559 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3560 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003561
3562 if (SrcSize == DestSize) return Noop;
3563 if (SrcSize > DestSize) return Truncate;
3564 if (Src->isSigned()) return Signext;
3565 return Zeroext;
3566}
3567
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003568
Chris Lattner48a44f72002-05-02 17:06:02 +00003569// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3570// instruction.
3571//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003572static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00003573 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003574
Chris Lattner650b6da2002-08-02 20:00:25 +00003575 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00003576 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003577 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003578 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003579 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003580
Chris Lattner4fbad962004-07-21 04:27:24 +00003581 // If we are casting between pointer and integer types, treat pointers as
3582 // integers of the appropriate size for the code below.
3583 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3584 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3585 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003586
Chris Lattner48a44f72002-05-02 17:06:02 +00003587 // Allow free casting and conversion of sizes as long as the sign doesn't
3588 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003589 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003590 CastType FirstCast = getCastType(SrcTy, MidTy);
3591 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003592
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003593 // Capture the effect of these two casts. If the result is a legal cast,
3594 // the CastType is stored here, otherwise a special code is used.
3595 static const unsigned CastResult[] = {
3596 // First cast is noop
3597 0, 1, 2, 3,
3598 // First cast is a truncate
3599 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3600 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003601 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003602 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003603 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003604 };
3605
3606 unsigned Result = CastResult[FirstCast*4+SecondCast];
3607 switch (Result) {
3608 default: assert(0 && "Illegal table value!");
3609 case 0:
3610 case 1:
3611 case 2:
3612 case 3:
3613 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3614 // truncates, we could eliminate more casts.
3615 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3616 case 4:
3617 return false; // Not possible to eliminate this here.
3618 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00003619 // Sign or zero extend followed by truncate is always ok if the result
3620 // is a truncate or noop.
3621 CastType ResultCast = getCastType(SrcTy, DstTy);
3622 if (ResultCast == Noop || ResultCast == Truncate)
3623 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003624 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00003625 // result will match the sign/zeroextendness of the result.
3626 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00003627 }
Chris Lattner650b6da2002-08-02 20:00:25 +00003628 }
Chris Lattner48a44f72002-05-02 17:06:02 +00003629 return false;
3630}
3631
Chris Lattner11ffd592004-07-20 05:21:00 +00003632static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003633 if (V->getType() == Ty || isa<Constant>(V)) return false;
3634 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00003635 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3636 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003637 return false;
3638 return true;
3639}
3640
3641/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3642/// InsertBefore instruction. This is specialized a bit to avoid inserting
3643/// casts that are known to not do anything...
3644///
3645Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3646 Instruction *InsertBefore) {
3647 if (V->getType() == DestTy) return V;
3648 if (Constant *C = dyn_cast<Constant>(V))
3649 return ConstantExpr::getCast(C, DestTy);
3650
3651 CastInst *CI = new CastInst(V, DestTy, V->getName());
3652 InsertNewInstBefore(CI, *InsertBefore);
3653 return CI;
3654}
Chris Lattner48a44f72002-05-02 17:06:02 +00003655
3656// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00003657//
Chris Lattner113f4f42002-06-25 16:13:24 +00003658Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00003659 Value *Src = CI.getOperand(0);
3660
Chris Lattner48a44f72002-05-02 17:06:02 +00003661 // If the user is casting a value to the same type, eliminate this cast
3662 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00003663 if (CI.getType() == Src->getType())
3664 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00003665
Chris Lattner81a7a232004-10-16 18:11:37 +00003666 if (isa<UndefValue>(Src)) // cast undef -> undef
3667 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3668
Chris Lattner48a44f72002-05-02 17:06:02 +00003669 // If casting the result of another cast instruction, try to eliminate this
3670 // one!
3671 //
Chris Lattner86102b82005-01-01 16:22:27 +00003672 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3673 Value *A = CSrc->getOperand(0);
3674 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3675 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003676 // This instruction now refers directly to the cast's src operand. This
3677 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00003678 CI.setOperand(0, CSrc->getOperand(0));
3679 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00003680 }
3681
Chris Lattner650b6da2002-08-02 20:00:25 +00003682 // If this is an A->B->A cast, and we are dealing with integral types, try
3683 // to convert this into a logical 'and' instruction.
3684 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00003685 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003686 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00003687 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003688 CSrc->getType()->getPrimitiveSizeInBits() <
3689 CI.getType()->getPrimitiveSizeInBits()&&
3690 A->getType()->getPrimitiveSizeInBits() ==
3691 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00003692 assert(CSrc->getType() != Type::ULongTy &&
3693 "Cannot have type bigger than ulong!");
Chris Lattner2f1457f2005-04-24 17:46:05 +00003694 uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
Chris Lattner86102b82005-01-01 16:22:27 +00003695 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3696 AndValue);
3697 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3698 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3699 if (And->getType() != CI.getType()) {
3700 And->setName(CSrc->getName()+".mask");
3701 InsertNewInstBefore(And, CI);
3702 And = new CastInst(And, CI.getType());
3703 }
3704 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00003705 }
3706 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003707
Chris Lattner03841652004-05-25 04:29:21 +00003708 // If this is a cast to bool, turn it into the appropriate setne instruction.
3709 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003710 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00003711 Constant::getNullValue(CI.getOperand(0)->getType()));
3712
Chris Lattnerd0d51602003-06-21 23:12:02 +00003713 // If casting the result of a getelementptr instruction with no offset, turn
3714 // this into a cast of the original pointer!
3715 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00003716 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00003717 bool AllZeroOperands = true;
3718 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3719 if (!isa<Constant>(GEP->getOperand(i)) ||
3720 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3721 AllZeroOperands = false;
3722 break;
3723 }
3724 if (AllZeroOperands) {
3725 CI.setOperand(0, GEP->getOperand(0));
3726 return &CI;
3727 }
3728 }
3729
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003730 // If we are casting a malloc or alloca to a pointer to a type of the same
3731 // size, rewrite the allocation instruction to allocate the "right" type.
3732 //
3733 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00003734 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003735 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
3736 // Get the type really allocated and the type casted to...
3737 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003738 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003739 if (AllocElTy->isSized() && CastElTy->isSized()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003740 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3741 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00003742
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003743 // If the allocation is for an even multiple of the cast type size
3744 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003745 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003746 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003747 std::string Name = AI->getName(); AI->setName("");
3748 AllocationInst *New;
3749 if (isa<MallocInst>(AI))
3750 New = new MallocInst(CastElTy, Amt, Name);
3751 else
3752 New = new AllocaInst(CastElTy, Amt, Name);
3753 InsertNewInstBefore(New, *AI);
3754 return ReplaceInstUsesWith(CI, New);
3755 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003756 }
3757 }
3758
Chris Lattner86102b82005-01-01 16:22:27 +00003759 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
3760 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
3761 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003762 if (isa<PHINode>(Src))
3763 if (Instruction *NV = FoldOpIntoPhi(CI))
3764 return NV;
3765
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003766 // If the source value is an instruction with only this use, we can attempt to
3767 // propagate the cast into the instruction. Also, only handle integral types
3768 // for now.
3769 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003770 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003771 CI.getType()->isInteger()) { // Don't mess with casts to bool here
3772 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003773 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
3774 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003775
3776 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3777 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3778
3779 switch (SrcI->getOpcode()) {
3780 case Instruction::Add:
3781 case Instruction::Mul:
3782 case Instruction::And:
3783 case Instruction::Or:
3784 case Instruction::Xor:
3785 // If we are discarding information, or just changing the sign, rewrite.
3786 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3787 // Don't insert two casts if they cannot be eliminated. We allow two
3788 // casts to be inserted if the sizes are the same. This could only be
3789 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00003790 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3791 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003792 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3793 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3794 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3795 ->getOpcode(), Op0c, Op1c);
3796 }
3797 }
Chris Lattner72086162005-05-06 02:07:39 +00003798
3799 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
3800 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
3801 Op1 == ConstantBool::True &&
3802 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
3803 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
3804 return BinaryOperator::createXor(New,
3805 ConstantInt::get(CI.getType(), 1));
3806 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003807 break;
3808 case Instruction::Shl:
3809 // Allow changing the sign of the source operand. Do not allow changing
3810 // the size of the shift, UNLESS the shift amount is a constant. We
3811 // mush not change variable sized shifts to a smaller size, because it
3812 // is undefined to shift more bits out than exist in the value.
3813 if (DestBitSize == SrcBitSize ||
3814 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3815 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3816 return new ShiftInst(Instruction::Shl, Op0c, Op1);
3817 }
3818 break;
Chris Lattner87380412005-05-06 04:18:52 +00003819 case Instruction::Shr:
3820 // If this is a signed shr, and if all bits shifted in are about to be
3821 // truncated off, turn it into an unsigned shr to allow greater
3822 // simplifications.
3823 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
3824 isa<ConstantInt>(Op1)) {
3825 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
3826 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
3827 // Convert to unsigned.
3828 Value *N1 = InsertOperandCastBefore(Op0,
3829 Op0->getType()->getUnsignedVersion(), &CI);
3830 // Insert the new shift, which is now unsigned.
3831 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
3832 Op1, Src->getName()), CI);
3833 return new CastInst(N1, CI.getType());
3834 }
3835 }
3836 break;
3837
Chris Lattner809dfac2005-05-04 19:10:26 +00003838 case Instruction::SetNE:
Chris Lattner809dfac2005-05-04 19:10:26 +00003839 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00003840 if (Op1C->getRawValue() == 0) {
3841 // If the input only has the low bit set, simplify directly.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003842 Constant *Not1 =
Chris Lattner809dfac2005-05-04 19:10:26 +00003843 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattner4c2d3782005-05-06 01:53:19 +00003844 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattner809dfac2005-05-04 19:10:26 +00003845 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
3846 if (CI.getType() == Op0->getType())
3847 return ReplaceInstUsesWith(CI, Op0);
3848 else
3849 return new CastInst(Op0, CI.getType());
3850 }
Chris Lattner4c2d3782005-05-06 01:53:19 +00003851
3852 // If the input is an and with a single bit, shift then simplify.
3853 ConstantInt *AndRHS;
3854 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
3855 if (AndRHS->getRawValue() &&
3856 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattner22d00a82005-08-02 19:16:58 +00003857 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattner4c2d3782005-05-06 01:53:19 +00003858 // Perform an unsigned shr by shiftamt. Convert input to
3859 // unsigned if it is signed.
3860 Value *In = Op0;
3861 if (In->getType()->isSigned())
3862 In = InsertNewInstBefore(new CastInst(In,
3863 In->getType()->getUnsignedVersion(), In->getName()),CI);
3864 // Insert the shift to put the result in the low bit.
3865 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
3866 ConstantInt::get(Type::UByteTy, ShiftAmt),
3867 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00003868 if (CI.getType() == In->getType())
3869 return ReplaceInstUsesWith(CI, In);
3870 else
3871 return new CastInst(In, CI.getType());
3872 }
3873 }
3874 }
3875 break;
3876 case Instruction::SetEQ:
3877 // We if we are just checking for a seteq of a single bit and casting it
3878 // to an integer. If so, shift the bit to the appropriate place then
3879 // cast to integer to avoid the comparison.
3880 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
3881 // Is Op1C a power of two or zero?
3882 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
3883 // cast (X == 1) to int -> X iff X has only the low bit set.
3884 if (Op1C->getRawValue() == 1) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003885 Constant *Not1 =
Chris Lattner4c2d3782005-05-06 01:53:19 +00003886 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
3887 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
3888 if (CI.getType() == Op0->getType())
3889 return ReplaceInstUsesWith(CI, Op0);
3890 else
3891 return new CastInst(Op0, CI.getType());
3892 }
3893 }
Chris Lattner809dfac2005-05-04 19:10:26 +00003894 }
3895 }
3896 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003897 }
3898 }
Chris Lattner260ab202002-04-18 17:39:14 +00003899 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00003900}
3901
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003902/// GetSelectFoldableOperands - We want to turn code that looks like this:
3903/// %C = or %A, %B
3904/// %D = select %cond, %C, %A
3905/// into:
3906/// %C = select %cond, %B, 0
3907/// %D = or %A, %C
3908///
3909/// Assuming that the specified instruction is an operand to the select, return
3910/// a bitmask indicating which operands of this instruction are foldable if they
3911/// equal the other incoming value of the select.
3912///
3913static unsigned GetSelectFoldableOperands(Instruction *I) {
3914 switch (I->getOpcode()) {
3915 case Instruction::Add:
3916 case Instruction::Mul:
3917 case Instruction::And:
3918 case Instruction::Or:
3919 case Instruction::Xor:
3920 return 3; // Can fold through either operand.
3921 case Instruction::Sub: // Can only fold on the amount subtracted.
3922 case Instruction::Shl: // Can only fold on the shift amount.
3923 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00003924 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003925 default:
3926 return 0; // Cannot fold
3927 }
3928}
3929
3930/// GetSelectFoldableConstant - For the same transformation as the previous
3931/// function, return the identity constant that goes into the select.
3932static Constant *GetSelectFoldableConstant(Instruction *I) {
3933 switch (I->getOpcode()) {
3934 default: assert(0 && "This cannot happen!"); abort();
3935 case Instruction::Add:
3936 case Instruction::Sub:
3937 case Instruction::Or:
3938 case Instruction::Xor:
3939 return Constant::getNullValue(I->getType());
3940 case Instruction::Shl:
3941 case Instruction::Shr:
3942 return Constant::getNullValue(Type::UByteTy);
3943 case Instruction::And:
3944 return ConstantInt::getAllOnesValue(I->getType());
3945 case Instruction::Mul:
3946 return ConstantInt::get(I->getType(), 1);
3947 }
3948}
3949
Chris Lattner411336f2005-01-19 21:50:18 +00003950/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
3951/// have the same opcode and only one use each. Try to simplify this.
3952Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
3953 Instruction *FI) {
3954 if (TI->getNumOperands() == 1) {
3955 // If this is a non-volatile load or a cast from the same type,
3956 // merge.
3957 if (TI->getOpcode() == Instruction::Cast) {
3958 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
3959 return 0;
3960 } else {
3961 return 0; // unknown unary op.
3962 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003963
Chris Lattner411336f2005-01-19 21:50:18 +00003964 // Fold this by inserting a select from the input values.
3965 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
3966 FI->getOperand(0), SI.getName()+".v");
3967 InsertNewInstBefore(NewSI, SI);
3968 return new CastInst(NewSI, TI->getType());
3969 }
3970
3971 // Only handle binary operators here.
3972 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
3973 return 0;
3974
3975 // Figure out if the operations have any operands in common.
3976 Value *MatchOp, *OtherOpT, *OtherOpF;
3977 bool MatchIsOpZero;
3978 if (TI->getOperand(0) == FI->getOperand(0)) {
3979 MatchOp = TI->getOperand(0);
3980 OtherOpT = TI->getOperand(1);
3981 OtherOpF = FI->getOperand(1);
3982 MatchIsOpZero = true;
3983 } else if (TI->getOperand(1) == FI->getOperand(1)) {
3984 MatchOp = TI->getOperand(1);
3985 OtherOpT = TI->getOperand(0);
3986 OtherOpF = FI->getOperand(0);
3987 MatchIsOpZero = false;
3988 } else if (!TI->isCommutative()) {
3989 return 0;
3990 } else if (TI->getOperand(0) == FI->getOperand(1)) {
3991 MatchOp = TI->getOperand(0);
3992 OtherOpT = TI->getOperand(1);
3993 OtherOpF = FI->getOperand(0);
3994 MatchIsOpZero = true;
3995 } else if (TI->getOperand(1) == FI->getOperand(0)) {
3996 MatchOp = TI->getOperand(1);
3997 OtherOpT = TI->getOperand(0);
3998 OtherOpF = FI->getOperand(1);
3999 MatchIsOpZero = true;
4000 } else {
4001 return 0;
4002 }
4003
4004 // If we reach here, they do have operations in common.
4005 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4006 OtherOpF, SI.getName()+".v");
4007 InsertNewInstBefore(NewSI, SI);
4008
4009 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4010 if (MatchIsOpZero)
4011 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4012 else
4013 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4014 } else {
4015 if (MatchIsOpZero)
4016 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4017 else
4018 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4019 }
4020}
4021
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004022Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00004023 Value *CondVal = SI.getCondition();
4024 Value *TrueVal = SI.getTrueValue();
4025 Value *FalseVal = SI.getFalseValue();
4026
4027 // select true, X, Y -> X
4028 // select false, X, Y -> Y
4029 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004030 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00004031 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004032 else {
4033 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00004034 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004035 }
Chris Lattner533bc492004-03-30 19:37:13 +00004036
4037 // select C, X, X -> X
4038 if (TrueVal == FalseVal)
4039 return ReplaceInstUsesWith(SI, TrueVal);
4040
Chris Lattner81a7a232004-10-16 18:11:37 +00004041 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4042 return ReplaceInstUsesWith(SI, FalseVal);
4043 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4044 return ReplaceInstUsesWith(SI, TrueVal);
4045 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4046 if (isa<Constant>(TrueVal))
4047 return ReplaceInstUsesWith(SI, TrueVal);
4048 else
4049 return ReplaceInstUsesWith(SI, FalseVal);
4050 }
4051
Chris Lattner1c631e82004-04-08 04:43:23 +00004052 if (SI.getType() == Type::BoolTy)
4053 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4054 if (C == ConstantBool::True) {
4055 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004056 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004057 } else {
4058 // Change: A = select B, false, C --> A = and !B, C
4059 Value *NotCond =
4060 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4061 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004062 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004063 }
4064 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4065 if (C == ConstantBool::False) {
4066 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004067 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004068 } else {
4069 // Change: A = select B, C, true --> A = or !B, C
4070 Value *NotCond =
4071 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4072 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004073 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004074 }
4075 }
4076
Chris Lattner183b3362004-04-09 19:05:30 +00004077 // Selecting between two integer constants?
4078 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4079 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4080 // select C, 1, 0 -> cast C to int
4081 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4082 return new CastInst(CondVal, SI.getType());
4083 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4084 // select C, 0, 1 -> cast !C to int
4085 Value *NotCond =
4086 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00004087 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00004088 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00004089 }
Chris Lattner35167c32004-06-09 07:59:58 +00004090
4091 // If one of the constants is zero (we know they can't both be) and we
4092 // have a setcc instruction with zero, and we have an 'and' with the
4093 // non-constant value, eliminate this whole mess. This corresponds to
4094 // cases like this: ((X & 27) ? 27 : 0)
4095 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4096 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4097 if ((IC->getOpcode() == Instruction::SetEQ ||
4098 IC->getOpcode() == Instruction::SetNE) &&
4099 isa<ConstantInt>(IC->getOperand(1)) &&
4100 cast<Constant>(IC->getOperand(1))->isNullValue())
4101 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4102 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004103 isa<ConstantInt>(ICA->getOperand(1)) &&
4104 (ICA->getOperand(1) == TrueValC ||
4105 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00004106 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4107 // Okay, now we know that everything is set up, we just don't
4108 // know whether we have a setne or seteq and whether the true or
4109 // false val is the zero.
4110 bool ShouldNotVal = !TrueValC->isNullValue();
4111 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4112 Value *V = ICA;
4113 if (ShouldNotVal)
4114 V = InsertNewInstBefore(BinaryOperator::create(
4115 Instruction::Xor, V, ICA->getOperand(1)), SI);
4116 return ReplaceInstUsesWith(SI, V);
4117 }
Chris Lattner533bc492004-03-30 19:37:13 +00004118 }
Chris Lattner623fba12004-04-10 22:21:27 +00004119
4120 // See if we are selecting two values based on a comparison of the two values.
4121 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4122 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4123 // Transform (X == Y) ? X : Y -> Y
4124 if (SCI->getOpcode() == Instruction::SetEQ)
4125 return ReplaceInstUsesWith(SI, FalseVal);
4126 // Transform (X != Y) ? X : Y -> X
4127 if (SCI->getOpcode() == Instruction::SetNE)
4128 return ReplaceInstUsesWith(SI, TrueVal);
4129 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4130
4131 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4132 // Transform (X == Y) ? Y : X -> X
4133 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00004134 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004135 // Transform (X != Y) ? Y : X -> Y
4136 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00004137 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004138 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4139 }
4140 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004141
Chris Lattnera04c9042005-01-13 22:52:24 +00004142 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4143 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4144 if (TI->hasOneUse() && FI->hasOneUse()) {
4145 bool isInverse = false;
4146 Instruction *AddOp = 0, *SubOp = 0;
4147
Chris Lattner411336f2005-01-19 21:50:18 +00004148 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4149 if (TI->getOpcode() == FI->getOpcode())
4150 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4151 return IV;
4152
4153 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4154 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00004155 if (TI->getOpcode() == Instruction::Sub &&
4156 FI->getOpcode() == Instruction::Add) {
4157 AddOp = FI; SubOp = TI;
4158 } else if (FI->getOpcode() == Instruction::Sub &&
4159 TI->getOpcode() == Instruction::Add) {
4160 AddOp = TI; SubOp = FI;
4161 }
4162
4163 if (AddOp) {
4164 Value *OtherAddOp = 0;
4165 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4166 OtherAddOp = AddOp->getOperand(1);
4167 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4168 OtherAddOp = AddOp->getOperand(0);
4169 }
4170
4171 if (OtherAddOp) {
4172 // So at this point we know we have:
4173 // select C, (add X, Y), (sub X, ?)
4174 // We can do the transform profitably if either 'Y' = '?' or '?' is
4175 // a constant.
4176 if (SubOp->getOperand(1) == AddOp ||
4177 isa<Constant>(SubOp->getOperand(1))) {
4178 Value *NegVal;
4179 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4180 NegVal = ConstantExpr::getNeg(C);
4181 } else {
4182 NegVal = InsertNewInstBefore(
4183 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4184 }
4185
Chris Lattner51726c42005-01-14 17:35:12 +00004186 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00004187 Value *NewFalseOp = NegVal;
4188 if (AddOp != TI)
4189 std::swap(NewTrueOp, NewFalseOp);
4190 Instruction *NewSel =
4191 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanb1c93172005-04-21 23:48:37 +00004192
Chris Lattnera04c9042005-01-13 22:52:24 +00004193 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00004194 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00004195 }
4196 }
4197 }
4198 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004199
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004200 // See if we can fold the select into one of our operands.
4201 if (SI.getType()->isInteger()) {
4202 // See the comment above GetSelectFoldableOperands for a description of the
4203 // transformation we are doing here.
4204 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4205 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4206 !isa<Constant>(FalseVal))
4207 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4208 unsigned OpToFold = 0;
4209 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4210 OpToFold = 1;
4211 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4212 OpToFold = 2;
4213 }
4214
4215 if (OpToFold) {
4216 Constant *C = GetSelectFoldableConstant(TVI);
4217 std::string Name = TVI->getName(); TVI->setName("");
4218 Instruction *NewSel =
4219 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4220 Name);
4221 InsertNewInstBefore(NewSel, SI);
4222 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4223 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4224 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4225 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4226 else {
4227 assert(0 && "Unknown instruction!!");
4228 }
4229 }
4230 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00004231
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004232 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4233 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4234 !isa<Constant>(TrueVal))
4235 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4236 unsigned OpToFold = 0;
4237 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4238 OpToFold = 1;
4239 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4240 OpToFold = 2;
4241 }
4242
4243 if (OpToFold) {
4244 Constant *C = GetSelectFoldableConstant(FVI);
4245 std::string Name = FVI->getName(); FVI->setName("");
4246 Instruction *NewSel =
4247 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4248 Name);
4249 InsertNewInstBefore(NewSel, SI);
4250 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4251 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4252 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4253 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4254 else {
4255 assert(0 && "Unknown instruction!!");
4256 }
4257 }
4258 }
4259 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00004260
4261 if (BinaryOperator::isNot(CondVal)) {
4262 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4263 SI.setOperand(1, FalseVal);
4264 SI.setOperand(2, TrueVal);
4265 return &SI;
4266 }
4267
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004268 return 0;
4269}
4270
4271
Chris Lattner970c33a2003-06-19 17:00:31 +00004272// CallInst simplification
4273//
4274Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00004275 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4276 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00004277 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
4278 bool Changed = false;
4279
4280 // memmove/cpy/set of zero bytes is a noop.
4281 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4282 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4283
4284 // FIXME: Increase alignment here.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004285
Chris Lattner00648e12004-10-12 04:52:52 +00004286 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4287 if (CI->getRawValue() == 1) {
4288 // Replace the instruction with just byte operations. We would
4289 // transform other cases to loads/stores, but we don't know if
4290 // alignment is sufficient.
4291 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004292 }
4293
Chris Lattner00648e12004-10-12 04:52:52 +00004294 // If we have a memmove and the source operation is a constant global,
4295 // then the source and dest pointers can't alias, so we can change this
4296 // into a call to memcpy.
4297 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
4298 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4299 if (GVSrc->isConstant()) {
4300 Module *M = CI.getParent()->getParent()->getParent();
4301 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4302 CI.getCalledFunction()->getFunctionType());
4303 CI.setOperand(0, MemCpy);
4304 Changed = true;
4305 }
4306
4307 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00004308 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
4309 // If this stoppoint is at the same source location as the previous
4310 // stoppoint in the chain, it is not needed.
4311 if (DbgStopPointInst *PrevSPI =
4312 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4313 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4314 SPI->getColNo() == PrevSPI->getColNo()) {
4315 SPI->replaceAllUsesWith(PrevSPI);
4316 return EraseInstFromFunction(CI);
4317 }
Chris Lattner00648e12004-10-12 04:52:52 +00004318 }
4319
Chris Lattneraec3d942003-10-07 22:32:43 +00004320 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00004321}
4322
4323// InvokeInst simplification
4324//
4325Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00004326 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00004327}
4328
Chris Lattneraec3d942003-10-07 22:32:43 +00004329// visitCallSite - Improvements for call and invoke instructions.
4330//
4331Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004332 bool Changed = false;
4333
4334 // If the callee is a constexpr cast of a function, attempt to move the cast
4335 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00004336 if (transformConstExprCastCall(CS)) return 0;
4337
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004338 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00004339
Chris Lattner61d9d812005-05-13 07:09:09 +00004340 if (Function *CalleeF = dyn_cast<Function>(Callee))
4341 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4342 Instruction *OldCall = CS.getInstruction();
4343 // If the call and callee calling conventions don't match, this call must
4344 // be unreachable, as the call is undefined.
4345 new StoreInst(ConstantBool::True,
4346 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4347 if (!OldCall->use_empty())
4348 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4349 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4350 return EraseInstFromFunction(*OldCall);
4351 return 0;
4352 }
4353
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004354 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4355 // This instruction is not reachable, just remove it. We insert a store to
4356 // undef so that we know that this code is not reachable, despite the fact
4357 // that we can't modify the CFG here.
4358 new StoreInst(ConstantBool::True,
4359 UndefValue::get(PointerType::get(Type::BoolTy)),
4360 CS.getInstruction());
4361
4362 if (!CS.getInstruction()->use_empty())
4363 CS.getInstruction()->
4364 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4365
4366 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4367 // Don't break the CFG, insert a dummy cond branch.
4368 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4369 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00004370 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004371 return EraseInstFromFunction(*CS.getInstruction());
4372 }
Chris Lattner81a7a232004-10-16 18:11:37 +00004373
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004374 const PointerType *PTy = cast<PointerType>(Callee->getType());
4375 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4376 if (FTy->isVarArg()) {
4377 // See if we can optimize any arguments passed through the varargs area of
4378 // the call.
4379 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4380 E = CS.arg_end(); I != E; ++I)
4381 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4382 // If this cast does not effect the value passed through the varargs
4383 // area, we can eliminate the use of the cast.
4384 Value *Op = CI->getOperand(0);
4385 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4386 *I = Op;
4387 Changed = true;
4388 }
4389 }
4390 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004391
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004392 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00004393}
4394
Chris Lattner970c33a2003-06-19 17:00:31 +00004395// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4396// attempt to move the cast to the arguments of the call/invoke.
4397//
4398bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4399 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4400 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00004401 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00004402 return false;
Reid Spencer87436872004-07-18 00:38:32 +00004403 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00004404 Instruction *Caller = CS.getInstruction();
4405
4406 // Okay, this is a cast from a function to a different type. Unless doing so
4407 // would cause a type conversion of one of our arguments, change this call to
4408 // be a direct call with arguments casted to the appropriate types.
4409 //
4410 const FunctionType *FT = Callee->getFunctionType();
4411 const Type *OldRetTy = Caller->getType();
4412
Chris Lattner1f7942f2004-01-14 06:06:08 +00004413 // Check to see if we are changing the return type...
4414 if (OldRetTy != FT->getReturnType()) {
4415 if (Callee->isExternal() &&
4416 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4417 !Caller->use_empty())
4418 return false; // Cannot transform this return value...
4419
4420 // If the callsite is an invoke instruction, and the return value is used by
4421 // a PHI node in a successor, we cannot change the return type of the call
4422 // because there is no place to put the cast instruction (without breaking
4423 // the critical edge). Bail out in this case.
4424 if (!Caller->use_empty())
4425 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4426 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4427 UI != E; ++UI)
4428 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4429 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004430 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00004431 return false;
4432 }
Chris Lattner970c33a2003-06-19 17:00:31 +00004433
4434 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4435 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004436
Chris Lattner970c33a2003-06-19 17:00:31 +00004437 CallSite::arg_iterator AI = CS.arg_begin();
4438 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4439 const Type *ParamTy = FT->getParamType(i);
4440 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004441 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00004442 }
4443
4444 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4445 Callee->isExternal())
4446 return false; // Do not delete arguments unless we have a function body...
4447
4448 // Okay, we decided that this is a safe thing to do: go ahead and start
4449 // inserting cast instructions as necessary...
4450 std::vector<Value*> Args;
4451 Args.reserve(NumActualArgs);
4452
4453 AI = CS.arg_begin();
4454 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4455 const Type *ParamTy = FT->getParamType(i);
4456 if ((*AI)->getType() == ParamTy) {
4457 Args.push_back(*AI);
4458 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00004459 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4460 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00004461 }
4462 }
4463
4464 // If the function takes more arguments than the call was taking, add them
4465 // now...
4466 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4467 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4468
4469 // If we are removing arguments to the function, emit an obnoxious warning...
4470 if (FT->getNumParams() < NumActualArgs)
4471 if (!FT->isVarArg()) {
4472 std::cerr << "WARNING: While resolving call to function '"
4473 << Callee->getName() << "' arguments were dropped!\n";
4474 } else {
4475 // Add all of the arguments in their promoted form to the arg list...
4476 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4477 const Type *PTy = getPromotedType((*AI)->getType());
4478 if (PTy != (*AI)->getType()) {
4479 // Must promote to pass through va_arg area!
4480 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4481 InsertNewInstBefore(Cast, *Caller);
4482 Args.push_back(Cast);
4483 } else {
4484 Args.push_back(*AI);
4485 }
4486 }
4487 }
4488
4489 if (FT->getReturnType() == Type::VoidTy)
4490 Caller->setName(""); // Void type should not have a name...
4491
4492 Instruction *NC;
4493 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004494 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00004495 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00004496 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004497 } else {
4498 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00004499 if (cast<CallInst>(Caller)->isTailCall())
4500 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00004501 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004502 }
4503
4504 // Insert a cast of the return type as necessary...
4505 Value *NV = NC;
4506 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4507 if (NV->getType() != Type::VoidTy) {
4508 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00004509
4510 // If this is an invoke instruction, we should insert it after the first
4511 // non-phi, instruction in the normal successor block.
4512 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4513 BasicBlock::iterator I = II->getNormalDest()->begin();
4514 while (isa<PHINode>(I)) ++I;
4515 InsertNewInstBefore(NC, *I);
4516 } else {
4517 // Otherwise, it's a call, just insert cast right after the call instr
4518 InsertNewInstBefore(NC, *Caller);
4519 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004520 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00004521 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00004522 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00004523 }
4524 }
4525
4526 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4527 Caller->replaceAllUsesWith(NV);
4528 Caller->getParent()->getInstList().erase(Caller);
4529 removeFromWorkList(Caller);
4530 return true;
4531}
4532
4533
Chris Lattner7515cab2004-11-14 19:13:23 +00004534// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4535// operator and they all are only used by the PHI, PHI together their
4536// inputs, and do the operation once, to the result of the PHI.
4537Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4538 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4539
4540 // Scan the instruction, looking for input operations that can be folded away.
4541 // If all input operands to the phi are the same instruction (e.g. a cast from
4542 // the same type or "+42") we can pull the operation through the PHI, reducing
4543 // code size and simplifying code.
4544 Constant *ConstantOp = 0;
4545 const Type *CastSrcTy = 0;
4546 if (isa<CastInst>(FirstInst)) {
4547 CastSrcTy = FirstInst->getOperand(0)->getType();
4548 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4549 // Can fold binop or shift if the RHS is a constant.
4550 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4551 if (ConstantOp == 0) return 0;
4552 } else {
4553 return 0; // Cannot fold this operation.
4554 }
4555
4556 // Check to see if all arguments are the same operation.
4557 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4558 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4559 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4560 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4561 return 0;
4562 if (CastSrcTy) {
4563 if (I->getOperand(0)->getType() != CastSrcTy)
4564 return 0; // Cast operation must match.
4565 } else if (I->getOperand(1) != ConstantOp) {
4566 return 0;
4567 }
4568 }
4569
4570 // Okay, they are all the same operation. Create a new PHI node of the
4571 // correct type, and PHI together all of the LHS's of the instructions.
4572 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4573 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00004574 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00004575
4576 Value *InVal = FirstInst->getOperand(0);
4577 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00004578
4579 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00004580 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4581 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4582 if (NewInVal != InVal)
4583 InVal = 0;
4584 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4585 }
4586
4587 Value *PhiVal;
4588 if (InVal) {
4589 // The new PHI unions all of the same values together. This is really
4590 // common, so we handle it intelligently here for compile-time speed.
4591 PhiVal = InVal;
4592 delete NewPN;
4593 } else {
4594 InsertNewInstBefore(NewPN, PN);
4595 PhiVal = NewPN;
4596 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004597
Chris Lattner7515cab2004-11-14 19:13:23 +00004598 // Insert and return the new operation.
4599 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004600 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00004601 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004602 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004603 else
4604 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00004605 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004606}
Chris Lattner48a44f72002-05-02 17:06:02 +00004607
Chris Lattner71536432005-01-17 05:10:15 +00004608/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4609/// that is dead.
4610static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4611 if (PN->use_empty()) return true;
4612 if (!PN->hasOneUse()) return false;
4613
4614 // Remember this node, and if we find the cycle, return.
4615 if (!PotentiallyDeadPHIs.insert(PN).second)
4616 return true;
4617
4618 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4619 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004620
Chris Lattner71536432005-01-17 05:10:15 +00004621 return false;
4622}
4623
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004624// PHINode simplification
4625//
Chris Lattner113f4f42002-06-25 16:13:24 +00004626Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00004627 if (Value *V = PN.hasConstantValue())
4628 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00004629
4630 // If the only user of this instruction is a cast instruction, and all of the
4631 // incoming values are constants, change this PHI to merge together the casted
4632 // constants.
4633 if (PN.hasOneUse())
4634 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4635 if (CI->getType() != PN.getType()) { // noop casts will be folded
4636 bool AllConstant = true;
4637 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4638 if (!isa<Constant>(PN.getIncomingValue(i))) {
4639 AllConstant = false;
4640 break;
4641 }
4642 if (AllConstant) {
4643 // Make a new PHI with all casted values.
4644 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4645 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4646 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4647 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4648 PN.getIncomingBlock(i));
4649 }
4650
4651 // Update the cast instruction.
4652 CI->setOperand(0, New);
4653 WorkList.push_back(CI); // revisit the cast instruction to fold.
4654 WorkList.push_back(New); // Make sure to revisit the new Phi
4655 return &PN; // PN is now dead!
4656 }
4657 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004658
4659 // If all PHI operands are the same operation, pull them through the PHI,
4660 // reducing code size.
4661 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4662 PN.getIncomingValue(0)->hasOneUse())
4663 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4664 return Result;
4665
Chris Lattner71536432005-01-17 05:10:15 +00004666 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4667 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4668 // PHI)... break the cycle.
4669 if (PN.hasOneUse())
4670 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4671 std::set<PHINode*> PotentiallyDeadPHIs;
4672 PotentiallyDeadPHIs.insert(&PN);
4673 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4674 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4675 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004676
Chris Lattner91daeb52003-12-19 05:58:40 +00004677 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004678}
4679
Chris Lattner69193f92004-04-05 01:30:19 +00004680static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4681 Instruction *InsertPoint,
4682 InstCombiner *IC) {
4683 unsigned PS = IC->getTargetData().getPointerSize();
4684 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00004685 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4686 // We must insert a cast to ensure we sign-extend.
4687 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4688 V->getName()), *InsertPoint);
4689 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4690 *InsertPoint);
4691}
4692
Chris Lattner48a44f72002-05-02 17:06:02 +00004693
Chris Lattner113f4f42002-06-25 16:13:24 +00004694Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004695 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00004696 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00004697 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004698 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00004699 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004700
Chris Lattner81a7a232004-10-16 18:11:37 +00004701 if (isa<UndefValue>(GEP.getOperand(0)))
4702 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4703
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004704 bool HasZeroPointerIndex = false;
4705 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4706 HasZeroPointerIndex = C->isNullValue();
4707
4708 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00004709 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00004710
Chris Lattner69193f92004-04-05 01:30:19 +00004711 // Eliminate unneeded casts for indices.
4712 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00004713 gep_type_iterator GTI = gep_type_begin(GEP);
4714 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4715 if (isa<SequentialType>(*GTI)) {
4716 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4717 Value *Src = CI->getOperand(0);
4718 const Type *SrcTy = Src->getType();
4719 const Type *DestTy = CI->getType();
4720 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004721 if (SrcTy->getPrimitiveSizeInBits() ==
4722 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004723 // We can always eliminate a cast from ulong or long to the other.
4724 // We can always eliminate a cast from uint to int or the other on
4725 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004726 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00004727 MadeChange = true;
4728 GEP.setOperand(i, Src);
4729 }
4730 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4731 SrcTy->getPrimitiveSize() == 4) {
4732 // We can always eliminate a cast from int to [u]long. We can
4733 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4734 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004735 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004736 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004737 MadeChange = true;
4738 GEP.setOperand(i, Src);
4739 }
Chris Lattner69193f92004-04-05 01:30:19 +00004740 }
4741 }
4742 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00004743 // If we are using a wider index than needed for this platform, shrink it
4744 // to what we need. If the incoming value needs a cast instruction,
4745 // insert it. This explicit cast can make subsequent optimizations more
4746 // obvious.
4747 Value *Op = GEP.getOperand(i);
4748 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004749 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00004750 GEP.setOperand(i, ConstantExpr::getCast(C,
4751 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004752 MadeChange = true;
4753 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004754 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4755 Op->getName()), GEP);
4756 GEP.setOperand(i, Op);
4757 MadeChange = true;
4758 }
Chris Lattner44d0b952004-07-20 01:48:15 +00004759
4760 // If this is a constant idx, make sure to canonicalize it to be a signed
4761 // operand, otherwise CSE and other optimizations are pessimized.
4762 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
4763 GEP.setOperand(i, ConstantExpr::getCast(CUI,
4764 CUI->getType()->getSignedVersion()));
4765 MadeChange = true;
4766 }
Chris Lattner69193f92004-04-05 01:30:19 +00004767 }
4768 if (MadeChange) return &GEP;
4769
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004770 // Combine Indices - If the source pointer to this getelementptr instruction
4771 // is a getelementptr instruction, combine the indices of the two
4772 // getelementptr instructions into a single instruction.
4773 //
Chris Lattner57c67b02004-03-25 22:59:29 +00004774 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00004775 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00004776 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00004777
4778 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004779 // Note that if our source is a gep chain itself that we wait for that
4780 // chain to be resolved before we perform this transformation. This
4781 // avoids us creating a TON of code in some cases.
4782 //
4783 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
4784 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
4785 return 0; // Wait until our source is folded to completion.
4786
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004787 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00004788
4789 // Find out whether the last index in the source GEP is a sequential idx.
4790 bool EndsWithSequential = false;
4791 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
4792 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00004793 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004794
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004795 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00004796 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00004797 // Replace: gep (gep %P, long B), long A, ...
4798 // With: T = long A+B; gep %P, T, ...
4799 //
Chris Lattner5f667a62004-05-07 22:09:22 +00004800 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00004801 if (SO1 == Constant::getNullValue(SO1->getType())) {
4802 Sum = GO1;
4803 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
4804 Sum = SO1;
4805 } else {
4806 // If they aren't the same type, convert both to an integer of the
4807 // target's pointer size.
4808 if (SO1->getType() != GO1->getType()) {
4809 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
4810 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
4811 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
4812 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
4813 } else {
4814 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00004815 if (SO1->getType()->getPrimitiveSize() == PS) {
4816 // Convert GO1 to SO1's type.
4817 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
4818
4819 } else if (GO1->getType()->getPrimitiveSize() == PS) {
4820 // Convert SO1 to GO1's type.
4821 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
4822 } else {
4823 const Type *PT = TD->getIntPtrType();
4824 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
4825 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
4826 }
4827 }
4828 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004829 if (isa<Constant>(SO1) && isa<Constant>(GO1))
4830 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
4831 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004832 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
4833 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00004834 }
Chris Lattner69193f92004-04-05 01:30:19 +00004835 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004836
4837 // Recycle the GEP we already have if possible.
4838 if (SrcGEPOperands.size() == 2) {
4839 GEP.setOperand(0, SrcGEPOperands[0]);
4840 GEP.setOperand(1, Sum);
4841 return &GEP;
4842 } else {
4843 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4844 SrcGEPOperands.end()-1);
4845 Indices.push_back(Sum);
4846 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
4847 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004848 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00004849 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004850 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004851 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00004852 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4853 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004854 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
4855 }
4856
4857 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00004858 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004859
Chris Lattner5f667a62004-05-07 22:09:22 +00004860 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004861 // GEP of global variable. If all of the indices for this GEP are
4862 // constants, we can promote this to a constexpr instead of an instruction.
4863
4864 // Scan for nonconstants...
4865 std::vector<Constant*> Indices;
4866 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
4867 for (; I != E && isa<Constant>(*I); ++I)
4868 Indices.push_back(cast<Constant>(*I));
4869
4870 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00004871 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004872
4873 // Replace all uses of the GEP with the new constexpr...
4874 return ReplaceInstUsesWith(GEP, CE);
4875 }
Chris Lattner567b81f2005-09-13 00:40:14 +00004876 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
4877 if (!isa<PointerType>(X->getType())) {
4878 // Not interesting. Source pointer must be a cast from pointer.
4879 } else if (HasZeroPointerIndex) {
4880 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
4881 // into : GEP [10 x ubyte]* X, long 0, ...
4882 //
4883 // This occurs when the program declares an array extern like "int X[];"
4884 //
4885 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
4886 const PointerType *XTy = cast<PointerType>(X->getType());
4887 if (const ArrayType *XATy =
4888 dyn_cast<ArrayType>(XTy->getElementType()))
4889 if (const ArrayType *CATy =
4890 dyn_cast<ArrayType>(CPTy->getElementType()))
4891 if (CATy->getElementType() == XATy->getElementType()) {
4892 // At this point, we know that the cast source type is a pointer
4893 // to an array of the same type as the destination pointer
4894 // array. Because the array type is never stepped over (there
4895 // is a leading zero) we can fold the cast into this GEP.
4896 GEP.setOperand(0, X);
4897 return &GEP;
4898 }
4899 } else if (GEP.getNumOperands() == 2) {
4900 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00004901 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
4902 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00004903 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4904 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
4905 if (isa<ArrayType>(SrcElTy) &&
4906 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
4907 TD->getTypeSize(ResElTy)) {
4908 Value *V = InsertNewInstBefore(
4909 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
4910 GEP.getOperand(1), GEP.getName()), GEP);
4911 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004912 }
Chris Lattner2a893292005-09-13 18:36:04 +00004913
4914 // Transform things like:
4915 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
4916 // (where tmp = 8*tmp2) into:
4917 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
4918
4919 if (isa<ArrayType>(SrcElTy) &&
4920 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
4921 uint64_t ArrayEltSize =
4922 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
4923
4924 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
4925 // allow either a mul, shift, or constant here.
4926 Value *NewIdx = 0;
4927 ConstantInt *Scale = 0;
4928 if (ArrayEltSize == 1) {
4929 NewIdx = GEP.getOperand(1);
4930 Scale = ConstantInt::get(NewIdx->getType(), 1);
4931 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00004932 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00004933 Scale = CI;
4934 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
4935 if (Inst->getOpcode() == Instruction::Shl &&
4936 isa<ConstantInt>(Inst->getOperand(1))) {
4937 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
4938 if (Inst->getType()->isSigned())
4939 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
4940 else
4941 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
4942 NewIdx = Inst->getOperand(0);
4943 } else if (Inst->getOpcode() == Instruction::Mul &&
4944 isa<ConstantInt>(Inst->getOperand(1))) {
4945 Scale = cast<ConstantInt>(Inst->getOperand(1));
4946 NewIdx = Inst->getOperand(0);
4947 }
4948 }
4949
4950 // If the index will be to exactly the right offset with the scale taken
4951 // out, perform the transformation.
4952 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
4953 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
4954 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00004955 (int64_t)C->getRawValue() /
4956 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00004957 else
4958 Scale = ConstantUInt::get(Scale->getType(),
4959 Scale->getRawValue() / ArrayEltSize);
4960 if (Scale->getRawValue() != 1) {
4961 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
4962 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
4963 NewIdx = InsertNewInstBefore(Sc, GEP);
4964 }
4965
4966 // Insert the new GEP instruction.
4967 Instruction *Idx =
4968 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
4969 NewIdx, GEP.getName());
4970 Idx = InsertNewInstBefore(Idx, GEP);
4971 return new CastInst(Idx, GEP.getType());
4972 }
4973 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004974 }
Chris Lattnerca081252001-12-14 16:52:21 +00004975 }
4976
Chris Lattnerca081252001-12-14 16:52:21 +00004977 return 0;
4978}
4979
Chris Lattner1085bdf2002-11-04 16:18:53 +00004980Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
4981 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
4982 if (AI.isArrayAllocation()) // Check C != 1
4983 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
4984 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004985 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00004986
4987 // Create and insert the replacement instruction...
4988 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00004989 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004990 else {
4991 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00004992 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004993 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004994
4995 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004996
Chris Lattner1085bdf2002-11-04 16:18:53 +00004997 // Scan to the end of the allocation instructions, to skip over a block of
4998 // allocas if possible...
4999 //
5000 BasicBlock::iterator It = New;
5001 while (isa<AllocationInst>(*It)) ++It;
5002
5003 // Now that I is pointing to the first non-allocation-inst in the block,
5004 // insert our getelementptr instruction...
5005 //
Chris Lattner809dfac2005-05-04 19:10:26 +00005006 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5007 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5008 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00005009
5010 // Now make everything use the getelementptr instead of the original
5011 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00005012 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00005013 } else if (isa<UndefValue>(AI.getArraySize())) {
5014 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00005015 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005016
5017 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5018 // Note that we only do this for alloca's, because malloc should allocate and
5019 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005020 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00005021 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00005022 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5023
Chris Lattner1085bdf2002-11-04 16:18:53 +00005024 return 0;
5025}
5026
Chris Lattner8427bff2003-12-07 01:24:23 +00005027Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5028 Value *Op = FI.getOperand(0);
5029
5030 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5031 if (CastInst *CI = dyn_cast<CastInst>(Op))
5032 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5033 FI.setOperand(0, CI->getOperand(0));
5034 return &FI;
5035 }
5036
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005037 // free undef -> unreachable.
5038 if (isa<UndefValue>(Op)) {
5039 // Insert a new store to null because we cannot modify the CFG here.
5040 new StoreInst(ConstantBool::True,
5041 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5042 return EraseInstFromFunction(FI);
5043 }
5044
Chris Lattnerf3a36602004-02-28 04:57:37 +00005045 // If we have 'free null' delete the instruction. This can happen in stl code
5046 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005047 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00005048 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00005049
Chris Lattner8427bff2003-12-07 01:24:23 +00005050 return 0;
5051}
5052
5053
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005054/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
5055/// constantexpr, return the constant value being addressed by the constant
5056/// expression, or null if something is funny.
5057///
5058static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00005059 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005060 return 0; // Do not allow stepping over the value!
5061
5062 // Loop over all of the operands, tracking down which value we are
5063 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00005064 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
5065 for (++I; I != E; ++I)
5066 if (const StructType *STy = dyn_cast<StructType>(*I)) {
5067 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
5068 assert(CU->getValue() < STy->getNumElements() &&
5069 "Struct index out of range!");
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00005070 unsigned El = (unsigned)CU->getValue();
Chris Lattnered79d8a2004-05-27 17:30:27 +00005071 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00005072 C = CS->getOperand(El);
Chris Lattnered79d8a2004-05-27 17:30:27 +00005073 } else if (isa<ConstantAggregateZero>(C)) {
Jeff Cohen82639852005-04-23 21:38:35 +00005074 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattner81a7a232004-10-16 18:11:37 +00005075 } else if (isa<UndefValue>(C)) {
Jeff Cohen82639852005-04-23 21:38:35 +00005076 C = UndefValue::get(STy->getElementType(El));
Chris Lattnered79d8a2004-05-27 17:30:27 +00005077 } else {
5078 return 0;
5079 }
5080 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
5081 const ArrayType *ATy = cast<ArrayType>(*I);
5082 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
5083 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00005084 C = CA->getOperand((unsigned)CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00005085 else if (isa<ConstantAggregateZero>(C))
5086 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00005087 else if (isa<UndefValue>(C))
5088 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00005089 else
5090 return 0;
5091 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005092 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00005093 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005094 return C;
5095}
5096
Chris Lattner72684fe2005-01-31 05:51:45 +00005097/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00005098static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5099 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005100 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00005101
5102 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005103 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00005104 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005105
5106 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5107 // If the source is an array, the code below will not succeed. Check to
5108 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5109 // constants.
5110 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5111 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5112 if (ASrcTy->getNumElements() != 0) {
5113 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5114 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5115 SrcTy = cast<PointerType>(CastOp->getType());
5116 SrcPTy = SrcTy->getElementType();
5117 }
5118
5119 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00005120 // Do not allow turning this into a load of an integer, which is then
5121 // casted to a pointer, this pessimizes pointer analysis a lot.
5122 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005123 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005124 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00005125
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005126 // Okay, we are casting from one integer or pointer type to another of
5127 // the same size. Instead of casting the pointer before the load, cast
5128 // the result of the loaded value.
5129 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5130 CI->getName(),
5131 LI.isVolatile()),LI);
5132 // Now cast the result of the load.
5133 return new CastInst(NewLoad, LI.getType());
5134 }
Chris Lattner35e24772004-07-13 01:49:43 +00005135 }
5136 }
5137 return 0;
5138}
5139
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005140/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00005141/// from this value cannot trap. If it is not obviously safe to load from the
5142/// specified pointer, we do a quick local scan of the basic block containing
5143/// ScanFrom, to determine if the address is already accessed.
5144static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5145 // If it is an alloca or global variable, it is always safe to load from.
5146 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5147
5148 // Otherwise, be a little bit agressive by scanning the local block where we
5149 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005150 // from/to. If so, the previous load or store would have already trapped,
5151 // so there is no harm doing an extra load (also, CSE will later eliminate
5152 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00005153 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5154
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005155 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00005156 --BBI;
5157
5158 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5159 if (LI->getOperand(0) == V) return true;
5160 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5161 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005162
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005163 }
Chris Lattnere6f13092004-09-19 19:18:10 +00005164 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005165}
5166
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005167Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5168 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00005169
Chris Lattnera9d84e32005-05-01 04:24:53 +00005170 // load (cast X) --> cast (load X) iff safe
5171 if (CastInst *CI = dyn_cast<CastInst>(Op))
5172 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5173 return Res;
5174
5175 // None of the following transforms are legal for volatile loads.
5176 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005177
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005178 if (&LI.getParent()->front() != &LI) {
5179 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005180 // If the instruction immediately before this is a store to the same
5181 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005182 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5183 if (SI->getOperand(1) == LI.getOperand(0))
5184 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005185 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5186 if (LIB->getOperand(0) == LI.getOperand(0))
5187 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005188 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00005189
5190 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5191 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5192 isa<UndefValue>(GEPI->getOperand(0))) {
5193 // Insert a new store to null instruction before the load to indicate
5194 // that this code is not reachable. We do this instead of inserting
5195 // an unreachable instruction directly because we cannot modify the
5196 // CFG.
5197 new StoreInst(UndefValue::get(LI.getType()),
5198 Constant::getNullValue(Op->getType()), &LI);
5199 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5200 }
5201
Chris Lattner81a7a232004-10-16 18:11:37 +00005202 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00005203 // load null/undef -> undef
5204 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005205 // Insert a new store to null instruction before the load to indicate that
5206 // this code is not reachable. We do this instead of inserting an
5207 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00005208 new StoreInst(UndefValue::get(LI.getType()),
5209 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00005210 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005211 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005212
Chris Lattner81a7a232004-10-16 18:11:37 +00005213 // Instcombine load (constant global) into the value loaded.
5214 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5215 if (GV->isConstant() && !GV->isExternal())
5216 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00005217
Chris Lattner81a7a232004-10-16 18:11:37 +00005218 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5219 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5220 if (CE->getOpcode() == Instruction::GetElementPtr) {
5221 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5222 if (GV->isConstant() && !GV->isExternal())
5223 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
5224 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00005225 if (CE->getOperand(0)->isNullValue()) {
5226 // Insert a new store to null instruction before the load to indicate
5227 // that this code is not reachable. We do this instead of inserting
5228 // an unreachable instruction directly because we cannot modify the
5229 // CFG.
5230 new StoreInst(UndefValue::get(LI.getType()),
5231 Constant::getNullValue(Op->getType()), &LI);
5232 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5233 }
5234
Chris Lattner81a7a232004-10-16 18:11:37 +00005235 } else if (CE->getOpcode() == Instruction::Cast) {
5236 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5237 return Res;
5238 }
5239 }
Chris Lattnere228ee52004-04-08 20:39:49 +00005240
Chris Lattnera9d84e32005-05-01 04:24:53 +00005241 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005242 // Change select and PHI nodes to select values instead of addresses: this
5243 // helps alias analysis out a lot, allows many others simplifications, and
5244 // exposes redundancy in the code.
5245 //
5246 // Note that we cannot do the transformation unless we know that the
5247 // introduced loads cannot trap! Something like this is valid as long as
5248 // the condition is always false: load (select bool %C, int* null, int* %G),
5249 // but it would not be valid if we transformed it to load from null
5250 // unconditionally.
5251 //
5252 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5253 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00005254 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5255 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005256 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00005257 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005258 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00005259 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005260 return new SelectInst(SI->getCondition(), V1, V2);
5261 }
5262
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00005263 // load (select (cond, null, P)) -> load P
5264 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5265 if (C->isNullValue()) {
5266 LI.setOperand(0, SI->getOperand(2));
5267 return &LI;
5268 }
5269
5270 // load (select (cond, P, null)) -> load P
5271 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5272 if (C->isNullValue()) {
5273 LI.setOperand(0, SI->getOperand(1));
5274 return &LI;
5275 }
5276
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005277 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5278 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00005279 bool Safe = PN->getParent() == LI.getParent();
5280
5281 // Scan all of the instructions between the PHI and the load to make
5282 // sure there are no instructions that might possibly alter the value
5283 // loaded from the PHI.
5284 if (Safe) {
5285 BasicBlock::iterator I = &LI;
5286 for (--I; !isa<PHINode>(I); --I)
5287 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5288 Safe = false;
5289 break;
5290 }
5291 }
5292
5293 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00005294 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00005295 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005296 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00005297
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005298 if (Safe) {
5299 // Create the PHI.
5300 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5301 InsertNewInstBefore(NewPN, *PN);
5302 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5303
5304 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5305 BasicBlock *BB = PN->getIncomingBlock(i);
5306 Value *&TheLoad = LoadMap[BB];
5307 if (TheLoad == 0) {
5308 Value *InVal = PN->getIncomingValue(i);
5309 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5310 InVal->getName()+".val"),
5311 *BB->getTerminator());
5312 }
5313 NewPN->addIncoming(TheLoad, BB);
5314 }
5315 return ReplaceInstUsesWith(LI, NewPN);
5316 }
5317 }
5318 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005319 return 0;
5320}
5321
Chris Lattner72684fe2005-01-31 05:51:45 +00005322/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5323/// when possible.
5324static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5325 User *CI = cast<User>(SI.getOperand(1));
5326 Value *CastOp = CI->getOperand(0);
5327
5328 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5329 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5330 const Type *SrcPTy = SrcTy->getElementType();
5331
5332 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5333 // If the source is an array, the code below will not succeed. Check to
5334 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5335 // constants.
5336 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5337 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5338 if (ASrcTy->getNumElements() != 0) {
5339 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5340 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5341 SrcTy = cast<PointerType>(CastOp->getType());
5342 SrcPTy = SrcTy->getElementType();
5343 }
5344
5345 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005346 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00005347 IC.getTargetData().getTypeSize(DestPTy)) {
5348
5349 // Okay, we are casting from one integer or pointer type to another of
5350 // the same size. Instead of casting the pointer before the store, cast
5351 // the value to be stored.
5352 Value *NewCast;
5353 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5354 NewCast = ConstantExpr::getCast(C, SrcPTy);
5355 else
5356 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5357 SrcPTy,
5358 SI.getOperand(0)->getName()+".c"), SI);
5359
5360 return new StoreInst(NewCast, CastOp);
5361 }
5362 }
5363 }
5364 return 0;
5365}
5366
Chris Lattner31f486c2005-01-31 05:36:43 +00005367Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5368 Value *Val = SI.getOperand(0);
5369 Value *Ptr = SI.getOperand(1);
5370
5371 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5372 removeFromWorkList(&SI);
5373 SI.eraseFromParent();
5374 ++NumCombined;
5375 return 0;
5376 }
5377
5378 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5379
5380 // store X, null -> turns into 'unreachable' in SimplifyCFG
5381 if (isa<ConstantPointerNull>(Ptr)) {
5382 if (!isa<UndefValue>(Val)) {
5383 SI.setOperand(0, UndefValue::get(Val->getType()));
5384 if (Instruction *U = dyn_cast<Instruction>(Val))
5385 WorkList.push_back(U); // Dropped a use.
5386 ++NumCombined;
5387 }
5388 return 0; // Do not modify these!
5389 }
5390
5391 // store undef, Ptr -> noop
5392 if (isa<UndefValue>(Val)) {
5393 removeFromWorkList(&SI);
5394 SI.eraseFromParent();
5395 ++NumCombined;
5396 return 0;
5397 }
5398
Chris Lattner72684fe2005-01-31 05:51:45 +00005399 // If the pointer destination is a cast, see if we can fold the cast into the
5400 // source instead.
5401 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5402 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5403 return Res;
5404 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5405 if (CE->getOpcode() == Instruction::Cast)
5406 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5407 return Res;
5408
Chris Lattner219175c2005-09-12 23:23:25 +00005409
5410 // If this store is the last instruction in the basic block, and if the block
5411 // ends with an unconditional branch, try to move it to the successor block.
5412 BasicBlock::iterator BBI = &SI; ++BBI;
5413 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5414 if (BI->isUnconditional()) {
5415 // Check to see if the successor block has exactly two incoming edges. If
5416 // so, see if the other predecessor contains a store to the same location.
5417 // if so, insert a PHI node (if needed) and move the stores down.
5418 BasicBlock *Dest = BI->getSuccessor(0);
5419
5420 pred_iterator PI = pred_begin(Dest);
5421 BasicBlock *Other = 0;
5422 if (*PI != BI->getParent())
5423 Other = *PI;
5424 ++PI;
5425 if (PI != pred_end(Dest)) {
5426 if (*PI != BI->getParent())
5427 if (Other)
5428 Other = 0;
5429 else
5430 Other = *PI;
5431 if (++PI != pred_end(Dest))
5432 Other = 0;
5433 }
5434 if (Other) { // If only one other pred...
5435 BBI = Other->getTerminator();
5436 // Make sure this other block ends in an unconditional branch and that
5437 // there is an instruction before the branch.
5438 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5439 BBI != Other->begin()) {
5440 --BBI;
5441 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5442
5443 // If this instruction is a store to the same location.
5444 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5445 // Okay, we know we can perform this transformation. Insert a PHI
5446 // node now if we need it.
5447 Value *MergedVal = OtherStore->getOperand(0);
5448 if (MergedVal != SI.getOperand(0)) {
5449 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5450 PN->reserveOperandSpace(2);
5451 PN->addIncoming(SI.getOperand(0), SI.getParent());
5452 PN->addIncoming(OtherStore->getOperand(0), Other);
5453 MergedVal = InsertNewInstBefore(PN, Dest->front());
5454 }
5455
5456 // Advance to a place where it is safe to insert the new store and
5457 // insert it.
5458 BBI = Dest->begin();
5459 while (isa<PHINode>(BBI)) ++BBI;
5460 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5461 OtherStore->isVolatile()), *BBI);
5462
5463 // Nuke the old stores.
5464 removeFromWorkList(&SI);
5465 removeFromWorkList(OtherStore);
5466 SI.eraseFromParent();
5467 OtherStore->eraseFromParent();
5468 ++NumCombined;
5469 return 0;
5470 }
5471 }
5472 }
5473 }
5474
Chris Lattner31f486c2005-01-31 05:36:43 +00005475 return 0;
5476}
5477
5478
Chris Lattner9eef8a72003-06-04 04:46:00 +00005479Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5480 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00005481 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00005482 BasicBlock *TrueDest;
5483 BasicBlock *FalseDest;
5484 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
5485 !isa<Constant>(X)) {
5486 // Swap Destinations and condition...
5487 BI.setCondition(X);
5488 BI.setSuccessor(0, FalseDest);
5489 BI.setSuccessor(1, TrueDest);
5490 return &BI;
5491 }
5492
5493 // Cannonicalize setne -> seteq
5494 Instruction::BinaryOps Op; Value *Y;
5495 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
5496 TrueDest, FalseDest)))
5497 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
5498 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
5499 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
5500 std::string Name = I->getName(); I->setName("");
5501 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
5502 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00005503 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00005504 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00005505 BI.setSuccessor(0, FalseDest);
5506 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00005507 removeFromWorkList(I);
5508 I->getParent()->getInstList().erase(I);
5509 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00005510 return &BI;
5511 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005512
Chris Lattner9eef8a72003-06-04 04:46:00 +00005513 return 0;
5514}
Chris Lattner1085bdf2002-11-04 16:18:53 +00005515
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005516Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5517 Value *Cond = SI.getCondition();
5518 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5519 if (I->getOpcode() == Instruction::Add)
5520 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5521 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5522 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00005523 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005524 AddRHS));
5525 SI.setOperand(0, I->getOperand(0));
5526 WorkList.push_back(I);
5527 return &SI;
5528 }
5529 }
5530 return 0;
5531}
5532
Chris Lattnerca081252001-12-14 16:52:21 +00005533
Chris Lattner99f48c62002-09-02 04:59:56 +00005534void InstCombiner::removeFromWorkList(Instruction *I) {
5535 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5536 WorkList.end());
5537}
5538
Chris Lattner39c98bb2004-12-08 23:43:58 +00005539
5540/// TryToSinkInstruction - Try to move the specified instruction from its
5541/// current block into the beginning of DestBlock, which can only happen if it's
5542/// safe to move the instruction past all of the instructions between it and the
5543/// end of its block.
5544static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5545 assert(I->hasOneUse() && "Invariants didn't hold!");
5546
5547 // Cannot move control-flow-involving instructions.
5548 if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005549
Chris Lattner39c98bb2004-12-08 23:43:58 +00005550 // Do not sink alloca instructions out of the entry block.
5551 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5552 return false;
5553
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005554 // We can only sink load instructions if there is nothing between the load and
5555 // the end of block that could change the value.
5556 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5557 if (LI->isVolatile()) return false; // Don't sink volatile loads.
5558
5559 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5560 Scan != E; ++Scan)
5561 if (Scan->mayWriteToMemory())
5562 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005563 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00005564
5565 BasicBlock::iterator InsertPos = DestBlock->begin();
5566 while (isa<PHINode>(InsertPos)) ++InsertPos;
5567
Chris Lattner9f269e42005-08-08 19:11:57 +00005568 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00005569 ++NumSunkInst;
5570 return true;
5571}
5572
Chris Lattner113f4f42002-06-25 16:13:24 +00005573bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00005574 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005575 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00005576
Chris Lattner4ed40f72005-07-07 20:40:38 +00005577 {
5578 // Populate the worklist with the reachable instructions.
5579 std::set<BasicBlock*> Visited;
5580 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
5581 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
5582 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
5583 WorkList.push_back(I);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005584
Chris Lattner4ed40f72005-07-07 20:40:38 +00005585 // Do a quick scan over the function. If we find any blocks that are
5586 // unreachable, remove any instructions inside of them. This prevents
5587 // the instcombine code from having to deal with some bad special cases.
5588 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5589 if (!Visited.count(BB)) {
5590 Instruction *Term = BB->getTerminator();
5591 while (Term != BB->begin()) { // Remove instrs bottom-up
5592 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00005593
Chris Lattner4ed40f72005-07-07 20:40:38 +00005594 DEBUG(std::cerr << "IC: DCE: " << *I);
5595 ++NumDeadInst;
5596
5597 if (!I->use_empty())
5598 I->replaceAllUsesWith(UndefValue::get(I->getType()));
5599 I->eraseFromParent();
5600 }
5601 }
5602 }
Chris Lattnerca081252001-12-14 16:52:21 +00005603
5604 while (!WorkList.empty()) {
5605 Instruction *I = WorkList.back(); // Get an instruction from the worklist
5606 WorkList.pop_back();
5607
Misha Brukman632df282002-10-29 23:06:16 +00005608 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00005609 // Check to see if we can DIE the instruction...
5610 if (isInstructionTriviallyDead(I)) {
5611 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005612 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00005613 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00005614 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005615
Chris Lattnercd517ff2005-01-28 19:32:01 +00005616 DEBUG(std::cerr << "IC: DCE: " << *I);
5617
5618 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005619 removeFromWorkList(I);
5620 continue;
5621 }
Chris Lattner99f48c62002-09-02 04:59:56 +00005622
Misha Brukman632df282002-10-29 23:06:16 +00005623 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00005624 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005625 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00005626 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005627 cast<Constant>(Ptr)->isNullValue() &&
5628 !isa<ConstantPointerNull>(C) &&
5629 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00005630 // If this is a constant expr gep that is effectively computing an
5631 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5632 bool isFoldableGEP = true;
5633 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5634 if (!isa<ConstantInt>(I->getOperand(i)))
5635 isFoldableGEP = false;
5636 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005637 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00005638 std::vector<Value*>(I->op_begin()+1, I->op_end()));
5639 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00005640 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00005641 C = ConstantExpr::getCast(C, I->getType());
5642 }
5643 }
5644
Chris Lattnercd517ff2005-01-28 19:32:01 +00005645 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5646
Chris Lattner99f48c62002-09-02 04:59:56 +00005647 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00005648 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00005649 ReplaceInstUsesWith(*I, C);
5650
Chris Lattner99f48c62002-09-02 04:59:56 +00005651 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005652 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00005653 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005654 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00005655 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005656
Chris Lattner39c98bb2004-12-08 23:43:58 +00005657 // See if we can trivially sink this instruction to a successor basic block.
5658 if (I->hasOneUse()) {
5659 BasicBlock *BB = I->getParent();
5660 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5661 if (UserParent != BB) {
5662 bool UserIsSuccessor = false;
5663 // See if the user is one of our successors.
5664 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5665 if (*SI == UserParent) {
5666 UserIsSuccessor = true;
5667 break;
5668 }
5669
5670 // If the user is one of our immediate successors, and if that successor
5671 // only has us as a predecessors (we'd have to split the critical edge
5672 // otherwise), we can keep going.
5673 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5674 next(pred_begin(UserParent)) == pred_end(UserParent))
5675 // Okay, the CFG is simple enough, try to sink this instruction.
5676 Changed |= TryToSinkInstruction(I, UserParent);
5677 }
5678 }
5679
Chris Lattnerca081252001-12-14 16:52:21 +00005680 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005681 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00005682 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00005683 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00005684 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005685 DEBUG(std::cerr << "IC: Old = " << *I
5686 << " New = " << *Result);
5687
Chris Lattner396dbfe2004-06-09 05:08:07 +00005688 // Everything uses the new instruction now.
5689 I->replaceAllUsesWith(Result);
5690
5691 // Push the new instruction and any users onto the worklist.
5692 WorkList.push_back(Result);
5693 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005694
5695 // Move the name to the new instruction first...
5696 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00005697 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005698
5699 // Insert the new instruction into the basic block...
5700 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00005701 BasicBlock::iterator InsertPos = I;
5702
5703 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5704 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5705 ++InsertPos;
5706
5707 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005708
Chris Lattner63d75af2004-05-01 23:27:23 +00005709 // Make sure that we reprocess all operands now that we reduced their
5710 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00005711 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5712 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5713 WorkList.push_back(OpI);
5714
Chris Lattner396dbfe2004-06-09 05:08:07 +00005715 // Instructions can end up on the worklist more than once. Make sure
5716 // we do not process an instruction that has been deleted.
5717 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005718
5719 // Erase the old instruction.
5720 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00005721 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005722 DEBUG(std::cerr << "IC: MOD = " << *I);
5723
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005724 // If the instruction was modified, it's possible that it is now dead.
5725 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00005726 if (isInstructionTriviallyDead(I)) {
5727 // Make sure we process all operands now that we are reducing their
5728 // use counts.
5729 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5730 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5731 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005732
Chris Lattner63d75af2004-05-01 23:27:23 +00005733 // Instructions may end up in the worklist more than once. Erase all
5734 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00005735 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00005736 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00005737 } else {
5738 WorkList.push_back(Result);
5739 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005740 }
Chris Lattner053c0932002-05-14 15:24:07 +00005741 }
Chris Lattner260ab202002-04-18 17:39:14 +00005742 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00005743 }
5744 }
5745
Chris Lattner260ab202002-04-18 17:39:14 +00005746 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00005747}
5748
Brian Gaeke38b79e82004-07-27 17:43:21 +00005749FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00005750 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00005751}
Brian Gaeke960707c2003-11-11 22:41:34 +00005752