blob: 1ef5d2a7a48dddcce10684e90d73833cd469fa7e [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.
Reid Spencer266e42b2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp 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 Lattner024f4ab2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000047#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000048#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000049#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000050#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000052#include "llvm/Support/Compiler.h"
Chris Lattnerf96f4a82007-01-31 04:40:53 +000053#include "llvm/ADT/SmallVector.h"
Chris Lattner7907e5f2007-02-15 19:41:52 +000054#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000055#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000056#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000057#include <algorithm>
Reid Spencer3f4e6e82007-02-04 00:40:42 +000058#include <set>
Chris Lattner8427bff2003-12-07 01:24:23 +000059using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000060using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000061
Chris Lattner79a42ac2006-12-19 21:40:18 +000062STATISTIC(NumCombined , "Number of insts combined");
63STATISTIC(NumConstProp, "Number of constant folds");
64STATISTIC(NumDeadInst , "Number of dead inst eliminated");
65STATISTIC(NumDeadStore, "Number of dead stores eliminated");
66STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000067
Chris Lattner79a42ac2006-12-19 21:40:18 +000068namespace {
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000069 class VISIBILITY_HIDDEN InstCombiner
70 : public FunctionPass,
71 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000072 // Worklist of all of the instructions that need to be simplified.
73 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000074 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000075
Chris Lattner51ea1272004-02-28 05:22:00 +000076 /// AddUsersToWorkList - When an instruction is simplified, add all users of
77 /// the instruction to the work lists because they might get more simplified
78 /// now.
79 ///
Chris Lattner2590e512006-02-07 06:56:34 +000080 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000081 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000082 UI != UE; ++UI)
83 WorkList.push_back(cast<Instruction>(*UI));
84 }
85
Chris Lattner51ea1272004-02-28 05:22:00 +000086 /// AddUsesToWorkList - When an instruction is simplified, add operands to
87 /// the work lists because they might get more simplified now.
88 ///
89 void AddUsesToWorkList(Instruction &I) {
90 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
91 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
92 WorkList.push_back(Op);
93 }
Chris Lattner2deeaea2006-10-05 06:55:50 +000094
95 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
96 /// dead. Add all of its operands to the worklist, turning them into
97 /// undef's to reduce the number of uses of those instructions.
98 ///
99 /// Return the specified operand before it is turned into an undef.
100 ///
101 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
102 Value *R = I.getOperand(op);
103
104 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
105 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
106 WorkList.push_back(Op);
107 // Set the operand to undef to drop the use.
108 I.setOperand(i, UndefValue::get(Op->getType()));
109 }
110
111 return R;
112 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000113
Chris Lattner99f48c62002-09-02 04:59:56 +0000114 // removeFromWorkList - remove all instances of I from the worklist.
115 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +0000116 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000117 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +0000118
Chris Lattnerf12cc842002-04-28 21:27:06 +0000119 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000120 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000121 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000122 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000123 }
124
Chris Lattner69193f92004-04-05 01:30:19 +0000125 TargetData &getTargetData() const { return *TD; }
126
Chris Lattner260ab202002-04-18 17:39:14 +0000127 // Visitation implementation - Implement instruction combining for different
128 // instruction types. The semantics are as follows:
129 // Return Value:
130 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000131 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000132 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000133 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000134 Instruction *visitAdd(BinaryOperator &I);
135 Instruction *visitSub(BinaryOperator &I);
136 Instruction *visitMul(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000137 Instruction *visitURem(BinaryOperator &I);
138 Instruction *visitSRem(BinaryOperator &I);
139 Instruction *visitFRem(BinaryOperator &I);
140 Instruction *commonRemTransforms(BinaryOperator &I);
141 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000142 Instruction *commonDivTransforms(BinaryOperator &I);
143 Instruction *commonIDivTransforms(BinaryOperator &I);
144 Instruction *visitUDiv(BinaryOperator &I);
145 Instruction *visitSDiv(BinaryOperator &I);
146 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000147 Instruction *visitAnd(BinaryOperator &I);
148 Instruction *visitOr (BinaryOperator &I);
149 Instruction *visitXor(BinaryOperator &I);
Reid Spencer2341c222007-02-02 02:16:23 +0000150 Instruction *visitShl(BinaryOperator &I);
151 Instruction *visitAShr(BinaryOperator &I);
152 Instruction *visitLShr(BinaryOperator &I);
153 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000154 Instruction *visitFCmpInst(FCmpInst &I);
155 Instruction *visitICmpInst(ICmpInst &I);
156 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000157
Reid Spencer266e42b2006-12-23 06:05:41 +0000158 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
159 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000160 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +0000161 BinaryOperator &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000162 Instruction *commonCastTransforms(CastInst &CI);
163 Instruction *commonIntCastTransforms(CastInst &CI);
164 Instruction *visitTrunc(CastInst &CI);
165 Instruction *visitZExt(CastInst &CI);
166 Instruction *visitSExt(CastInst &CI);
167 Instruction *visitFPTrunc(CastInst &CI);
168 Instruction *visitFPExt(CastInst &CI);
169 Instruction *visitFPToUI(CastInst &CI);
170 Instruction *visitFPToSI(CastInst &CI);
171 Instruction *visitUIToFP(CastInst &CI);
172 Instruction *visitSIToFP(CastInst &CI);
173 Instruction *visitPtrToInt(CastInst &CI);
174 Instruction *visitIntToPtr(CastInst &CI);
175 Instruction *visitBitCast(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000176 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
177 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000178 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000179 Instruction *visitCallInst(CallInst &CI);
180 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000181 Instruction *visitPHINode(PHINode &PN);
182 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000183 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000184 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000185 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000186 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000187 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000188 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000189 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000190 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000191 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000192
193 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000194 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000195
Chris Lattner970c33a2003-06-19 17:00:31 +0000196 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000197 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000198 bool transformConstExprCastCall(CallSite CS);
199
Chris Lattner69193f92004-04-05 01:30:19 +0000200 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000201 // InsertNewInstBefore - insert an instruction New before instruction Old
202 // in the program. Add the new instruction to the worklist.
203 //
Chris Lattner623826c2004-09-28 21:48:02 +0000204 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000205 assert(New && New->getParent() == 0 &&
206 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000207 BasicBlock *BB = Old.getParent();
208 BB->getInstList().insert(&Old, New); // Insert inst
209 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000210 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000211 }
212
Chris Lattner7e794272004-09-24 15:21:34 +0000213 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
214 /// This also adds the cast to the worklist. Finally, this returns the
215 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000216 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
217 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000218 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000219
Chris Lattnere79d2492006-04-06 19:19:17 +0000220 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000221 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000222
Reid Spencer13bc5d72006-12-12 09:18:51 +0000223 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattner7e794272004-09-24 15:21:34 +0000224 WorkList.push_back(C);
225 return C;
226 }
227
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000228 // ReplaceInstUsesWith - This method is to be used when an instruction is
229 // found to be dead, replacable with another preexisting expression. Here
230 // we add all uses of I to the worklist, replace all uses of I with the new
231 // value, then return I, so that the inst combiner will know that I was
232 // modified.
233 //
234 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000235 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000236 if (&I != V) {
237 I.replaceAllUsesWith(V);
238 return &I;
239 } else {
240 // If we are replacing the instruction with itself, this must be in a
241 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000242 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000243 return &I;
244 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000245 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000246
Chris Lattner2590e512006-02-07 06:56:34 +0000247 // UpdateValueUsesWith - This method is to be used when an value is
248 // found to be replacable with another preexisting expression or was
249 // updated. Here we add all uses of I to the worklist, replace all uses of
250 // I with the new value (unless the instruction was just updated), then
251 // return true, so that the inst combiner will know that I was modified.
252 //
253 bool UpdateValueUsesWith(Value *Old, Value *New) {
254 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
255 if (Old != New)
256 Old->replaceAllUsesWith(New);
257 if (Instruction *I = dyn_cast<Instruction>(Old))
258 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000259 if (Instruction *I = dyn_cast<Instruction>(New))
260 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000261 return true;
262 }
263
Chris Lattner51ea1272004-02-28 05:22:00 +0000264 // EraseInstFromFunction - When dealing with an instruction that has side
265 // effects or produces a void value, we can't rely on DCE to delete the
266 // instruction. Instead, visit methods should return the value returned by
267 // this function.
268 Instruction *EraseInstFromFunction(Instruction &I) {
269 assert(I.use_empty() && "Cannot erase instruction that is used!");
270 AddUsesToWorkList(I);
271 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000272 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000273 return 0; // Don't do anything with FI
274 }
275
Chris Lattner3ac7c262003-08-13 20:16:26 +0000276 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000277 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
278 /// InsertBefore instruction. This is specialized a bit to avoid inserting
279 /// casts that are known to not do anything...
280 ///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000281 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
282 Value *V, const Type *DestTy,
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000283 Instruction *InsertBefore);
284
Reid Spencer266e42b2006-12-23 06:05:41 +0000285 /// SimplifyCommutative - This performs a few simplifications for
286 /// commutative operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000287 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000288
Reid Spencer266e42b2006-12-23 06:05:41 +0000289 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
290 /// most-complex to least-complex order.
291 bool SimplifyCompare(CmpInst &I);
292
Chris Lattner0157e7f2006-02-11 09:31:47 +0000293 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
294 uint64_t &KnownZero, uint64_t &KnownOne,
295 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000296
Chris Lattner2deeaea2006-10-05 06:55:50 +0000297 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
298 uint64_t &UndefElts, unsigned Depth = 0);
299
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000300 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
301 // PHI node as operand #0, see if we can fold the instruction into the PHI
302 // (which is only possible if all operands to the PHI are constants).
303 Instruction *FoldOpIntoPhi(Instruction &I);
304
Chris Lattner7515cab2004-11-14 19:13:23 +0000305 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
306 // operator and they all are only used by the PHI, PHI together their
307 // inputs, and do the operation once, to the result of the PHI.
308 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000309 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
310
311
Zhou Sheng75b871f2007-01-11 12:24:14 +0000312 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
313 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000314
Zhou Sheng75b871f2007-01-11 12:24:14 +0000315 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000316 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000317 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000318 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000319 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000320 Instruction *MatchBSwap(BinaryOperator &I);
321
Reid Spencer74a528b2006-12-13 18:21:21 +0000322 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000323 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000324
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000325 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000326}
327
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000328// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000329// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000330static unsigned getComplexity(Value *V) {
331 if (isa<Instruction>(V)) {
332 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000333 return 3;
334 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000335 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000336 if (isa<Argument>(V)) return 3;
337 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000338}
Chris Lattner260ab202002-04-18 17:39:14 +0000339
Chris Lattner7fb29e12003-03-11 00:12:48 +0000340// isOnlyUse - Return true if this instruction will be deleted if we stop using
341// it.
342static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000343 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000344}
345
Chris Lattnere79e8542004-02-23 06:38:22 +0000346// getPromotedType - Return the specified type promoted as it would be to pass
347// though a va_arg area...
348static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000349 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
350 if (ITy->getBitWidth() < 32)
351 return Type::Int32Ty;
352 } else if (Ty == Type::FloatTy)
353 return Type::DoubleTy;
354 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000355}
356
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000357/// getBitCastOperand - If the specified operand is a CastInst or a constant
358/// expression bitcast, return the operand value, otherwise return null.
359static Value *getBitCastOperand(Value *V) {
360 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000361 return I->getOperand(0);
362 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000363 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000364 return CE->getOperand(0);
365 return 0;
366}
367
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000368/// This function is a wrapper around CastInst::isEliminableCastPair. It
369/// simply extracts arguments and returns what that function returns.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000370static Instruction::CastOps
371isEliminableCastPair(
372 const CastInst *CI, ///< The first cast instruction
373 unsigned opcode, ///< The opcode of the second cast instruction
374 const Type *DstTy, ///< The target type for the second cast instruction
375 TargetData *TD ///< The target data for pointer size
376) {
377
378 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
379 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000380
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000381 // Get the opcodes of the two Cast instructions
382 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
383 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000384
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000385 return Instruction::CastOps(
386 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
387 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000388}
389
390/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
391/// in any code being generated. It does not require codegen if V is simple
392/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000393static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
394 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000395 if (V->getType() == Ty || isa<Constant>(V)) return false;
396
Chris Lattner99155be2006-05-25 23:24:33 +0000397 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000398 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000399 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000400 return false;
401 return true;
402}
403
404/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
405/// InsertBefore instruction. This is specialized a bit to avoid inserting
406/// casts that are known to not do anything...
407///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000408Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
409 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000410 Instruction *InsertBefore) {
411 if (V->getType() == DestTy) return V;
412 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000413 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000414
Reid Spencer13bc5d72006-12-12 09:18:51 +0000415 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000416}
417
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000418// SimplifyCommutative - This performs a few simplifications for commutative
419// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000420//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000421// 1. Order operands such that they are listed from right (least complex) to
422// left (most complex). This puts constants before unary operators before
423// binary operators.
424//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000425// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
426// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000427//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000428bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000429 bool Changed = false;
430 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
431 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000432
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000433 if (!I.isAssociative()) return Changed;
434 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000435 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
436 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
437 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000438 Constant *Folded = ConstantExpr::get(I.getOpcode(),
439 cast<Constant>(I.getOperand(1)),
440 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000441 I.setOperand(0, Op->getOperand(0));
442 I.setOperand(1, Folded);
443 return true;
444 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
445 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
446 isOnlyUse(Op) && isOnlyUse(Op1)) {
447 Constant *C1 = cast<Constant>(Op->getOperand(1));
448 Constant *C2 = cast<Constant>(Op1->getOperand(1));
449
450 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000451 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000452 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
453 Op1->getOperand(0),
454 Op1->getName(), &I);
455 WorkList.push_back(New);
456 I.setOperand(0, New);
457 I.setOperand(1, Folded);
458 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000459 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000460 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000461 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000462}
Chris Lattnerca081252001-12-14 16:52:21 +0000463
Reid Spencer266e42b2006-12-23 06:05:41 +0000464/// SimplifyCompare - For a CmpInst this function just orders the operands
465/// so that theyare listed from right (least complex) to left (most complex).
466/// This puts constants before unary operators before binary operators.
467bool InstCombiner::SimplifyCompare(CmpInst &I) {
468 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
469 return false;
470 I.swapOperands();
471 // Compare instructions are not associative so there's nothing else we can do.
472 return true;
473}
474
Chris Lattnerbb74e222003-03-10 23:06:50 +0000475// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
476// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000477//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000478static inline Value *dyn_castNegVal(Value *V) {
479 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000480 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000481
Chris Lattner9ad0d552004-12-14 20:08:06 +0000482 // Constants can be considered to be negated values if they can be folded.
483 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
484 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000485 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000486}
487
Chris Lattnerbb74e222003-03-10 23:06:50 +0000488static inline Value *dyn_castNotVal(Value *V) {
489 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000490 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000491
492 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000493 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000494 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000495 return 0;
496}
497
Chris Lattner7fb29e12003-03-11 00:12:48 +0000498// dyn_castFoldableMul - If this value is a multiply that can be folded into
499// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000500// non-constant operand of the multiply, and set CST to point to the multiplier.
501// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000502//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000503static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000504 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000505 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000506 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000507 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000508 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000509 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000510 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000511 // The multiplier is really 1 << CST.
512 Constant *One = ConstantInt::get(V->getType(), 1);
513 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
514 return I->getOperand(0);
515 }
516 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000517 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000518}
Chris Lattner31ae8632002-08-14 17:51:49 +0000519
Chris Lattner0798af32005-01-13 20:14:25 +0000520/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
521/// expression, return it.
522static User *dyn_castGetElementPtr(Value *V) {
523 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
524 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
525 if (CE->getOpcode() == Instruction::GetElementPtr)
526 return cast<User>(V);
527 return false;
528}
529
Chris Lattner623826c2004-09-28 21:48:02 +0000530// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000531static ConstantInt *AddOne(ConstantInt *C) {
532 return cast<ConstantInt>(ConstantExpr::getAdd(C,
533 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000534}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000535static ConstantInt *SubOne(ConstantInt *C) {
536 return cast<ConstantInt>(ConstantExpr::getSub(C,
537 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000538}
539
Chris Lattner4534dd592006-02-09 07:38:58 +0000540/// ComputeMaskedBits - Determine which of the bits specified in Mask are
541/// known to be either zero or one and return them in the KnownZero/KnownOne
542/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
543/// processing.
544static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
545 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000546 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
547 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000548 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000549 // optimized based on the contradictory assumption that it is non-zero.
550 // Because instcombine aggressively folds operations with undef args anyway,
551 // this won't lose us code quality.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000552 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000553 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000554 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000555 KnownZero = ~KnownOne & Mask;
556 return;
557 }
558
559 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000560 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000561 return; // Limit search depth.
562
563 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000564 Instruction *I = dyn_cast<Instruction>(V);
565 if (!I) return;
566
Reid Spencera94d3942007-01-19 21:13:56 +0000567 Mask &= cast<IntegerType>(V->getType())->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +0000568
Chris Lattner0157e7f2006-02-11 09:31:47 +0000569 switch (I->getOpcode()) {
570 case Instruction::And:
571 // If either the LHS or the RHS are Zero, the result is zero.
572 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
573 Mask &= ~KnownZero;
574 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
575 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
576 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
577
578 // Output known-1 bits are only known if set in both the LHS & RHS.
579 KnownOne &= KnownOne2;
580 // Output known-0 are known to be clear if zero in either the LHS | RHS.
581 KnownZero |= KnownZero2;
582 return;
583 case Instruction::Or:
584 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
585 Mask &= ~KnownOne;
586 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
587 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
588 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
589
590 // Output known-0 bits are only known if clear in both the LHS & RHS.
591 KnownZero &= KnownZero2;
592 // Output known-1 are known to be set if set in either the LHS | RHS.
593 KnownOne |= KnownOne2;
594 return;
595 case Instruction::Xor: {
596 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
597 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
598 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
599 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
600
601 // Output known-0 bits are known if clear or set in both the LHS & RHS.
602 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
603 // Output known-1 are known to be set if set in only one of the LHS, RHS.
604 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
605 KnownZero = KnownZeroOut;
606 return;
607 }
608 case Instruction::Select:
609 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
610 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
611 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
612 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
613
614 // Only known if known in both the LHS and RHS.
615 KnownOne &= KnownOne2;
616 KnownZero &= KnownZero2;
617 return;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000618 case Instruction::FPTrunc:
619 case Instruction::FPExt:
620 case Instruction::FPToUI:
621 case Instruction::FPToSI:
622 case Instruction::SIToFP:
623 case Instruction::PtrToInt:
624 case Instruction::UIToFP:
625 case Instruction::IntToPtr:
626 return; // Can't work with floating point or pointers
627 case Instruction::Trunc:
628 // All these have integer operands
629 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
630 return;
631 case Instruction::BitCast: {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000632 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +0000633 if (SrcTy->isInteger()) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000634 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000635 return;
636 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000637 break;
638 }
639 case Instruction::ZExt: {
640 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +0000641 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
642 uint64_t NotIn = ~SrcTy->getBitMask();
643 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000644
Reid Spencera94d3942007-01-19 21:13:56 +0000645 Mask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000646 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
647 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
648 // The top bits are known to be zero.
649 KnownZero |= NewBits;
650 return;
651 }
652 case Instruction::SExt: {
653 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +0000654 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
655 uint64_t NotIn = ~SrcTy->getBitMask();
656 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000657
Reid Spencera94d3942007-01-19 21:13:56 +0000658 Mask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000659 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
660 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000661
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000662 // If the sign bit of the input is known set or clear, then we know the
663 // top bits of the result.
664 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
665 if (KnownZero & InSignBit) { // Input sign bit known zero
666 KnownZero |= NewBits;
667 KnownOne &= ~NewBits;
668 } else if (KnownOne & InSignBit) { // Input sign bit known set
669 KnownOne |= NewBits;
670 KnownZero &= ~NewBits;
671 } else { // Input sign bit unknown
672 KnownZero &= ~NewBits;
673 KnownOne &= ~NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000674 }
675 return;
676 }
677 case Instruction::Shl:
678 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000679 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
680 uint64_t ShiftAmt = SA->getZExtValue();
681 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000682 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
683 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000684 KnownZero <<= ShiftAmt;
685 KnownOne <<= ShiftAmt;
686 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000687 return;
688 }
689 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000690 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000691 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000692 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000693 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000694 uint64_t ShiftAmt = SA->getZExtValue();
695 uint64_t HighBits = (1ULL << ShiftAmt)-1;
696 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000697
Reid Spencerfdff9382006-11-08 06:47:33 +0000698 // Unsigned shift right.
699 Mask <<= ShiftAmt;
700 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
701 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
702 KnownZero >>= ShiftAmt;
703 KnownOne >>= ShiftAmt;
704 KnownZero |= HighBits; // high bits known zero.
705 return;
706 }
707 break;
708 case Instruction::AShr:
709 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
710 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
711 // Compute the new bits that are at the top now.
712 uint64_t ShiftAmt = SA->getZExtValue();
713 uint64_t HighBits = (1ULL << ShiftAmt)-1;
714 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
715
716 // Signed shift right.
717 Mask <<= ShiftAmt;
718 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
719 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
720 KnownZero >>= ShiftAmt;
721 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000722
Reid Spencerfdff9382006-11-08 06:47:33 +0000723 // Handle the sign bits.
724 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
725 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000726
Reid Spencerfdff9382006-11-08 06:47:33 +0000727 if (KnownZero & SignBit) { // New bits are known zero.
728 KnownZero |= HighBits;
729 } else if (KnownOne & SignBit) { // New bits are known one.
730 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000731 }
732 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000733 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000734 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000735 }
Chris Lattner92a68652006-02-07 08:05:22 +0000736}
737
738/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
739/// this predicate to simplify operations downstream. Mask is known to be zero
740/// for bits that V cannot have.
741static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000742 uint64_t KnownZero, KnownOne;
743 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
744 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
745 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000746}
747
Chris Lattner0157e7f2006-02-11 09:31:47 +0000748/// ShrinkDemandedConstant - Check to see if the specified operand of the
749/// specified instruction is a constant integer. If so, check to see if there
750/// are any bits set in the constant that are not demanded. If so, shrink the
751/// constant and return true.
752static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
753 uint64_t Demanded) {
754 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
755 if (!OpC) return false;
756
757 // If there are no bits set that aren't demanded, nothing to do.
758 if ((~Demanded & OpC->getZExtValue()) == 0)
759 return false;
760
761 // This is producing any bits that are not needed, shrink the RHS.
762 uint64_t Val = Demanded & OpC->getZExtValue();
Zhou Sheng75b871f2007-01-11 12:24:14 +0000763 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000764 return true;
765}
766
Chris Lattneree0f2802006-02-12 02:07:56 +0000767// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
768// set of known zero and one bits, compute the maximum and minimum values that
769// could have the specified known zero and known one bits, returning them in
770// min/max.
771static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
772 uint64_t KnownZero,
773 uint64_t KnownOne,
774 int64_t &Min, int64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +0000775 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +0000776 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
777
778 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
779
780 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
781 // bit if it is unknown.
782 Min = KnownOne;
783 Max = KnownOne|UnknownBits;
784
785 if (SignBit & UnknownBits) { // Sign bit is unknown
786 Min |= SignBit;
787 Max &= ~SignBit;
788 }
789
790 // Sign extend the min/max values.
791 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
792 Min = (Min << ShAmt) >> ShAmt;
793 Max = (Max << ShAmt) >> ShAmt;
794}
795
796// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
797// a set of known zero and one bits, compute the maximum and minimum values that
798// could have the specified known zero and known one bits, returning them in
799// min/max.
800static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
801 uint64_t KnownZero,
802 uint64_t KnownOne,
803 uint64_t &Min,
804 uint64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +0000805 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +0000806 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
807
808 // The minimum value is when the unknown bits are all zeros.
809 Min = KnownOne;
810 // The maximum value is when the unknown bits are all ones.
811 Max = KnownOne|UnknownBits;
812}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000813
814
815/// SimplifyDemandedBits - Look at V. At this point, we know that only the
816/// DemandedMask bits of the result of V are ever used downstream. If we can
817/// use this information to simplify V, do so and return true. Otherwise,
818/// analyze the expression and return a mask of KnownOne and KnownZero bits for
819/// the expression (used to simplify the caller). The KnownZero/One bits may
820/// only be accurate for those bits in the DemandedMask.
821bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
822 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000823 unsigned Depth) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000824 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000825 // We know all of the bits for a constant!
826 KnownOne = CI->getZExtValue() & DemandedMask;
827 KnownZero = ~KnownOne & DemandedMask;
828 return false;
829 }
830
831 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000832 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000833 if (Depth != 0) { // Not at the root.
834 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
835 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000836 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000837 }
Chris Lattner2590e512006-02-07 06:56:34 +0000838 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000839 // just set the DemandedMask to all bits.
Reid Spencera94d3942007-01-19 21:13:56 +0000840 DemandedMask = cast<IntegerType>(V->getType())->getBitMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000841 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000842 if (V != UndefValue::get(V->getType()))
843 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
844 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000845 } else if (Depth == 6) { // Limit search depth.
846 return false;
847 }
848
849 Instruction *I = dyn_cast<Instruction>(V);
850 if (!I) return false; // Only analyze instructions.
851
Reid Spencera94d3942007-01-19 21:13:56 +0000852 DemandedMask &= cast<IntegerType>(V->getType())->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +0000853
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000854 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000855 switch (I->getOpcode()) {
856 default: break;
857 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000858 // If either the LHS or the RHS are Zero, the result is zero.
859 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
860 KnownZero, KnownOne, Depth+1))
861 return true;
862 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
863
864 // If something is known zero on the RHS, the bits aren't demanded on the
865 // LHS.
866 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
867 KnownZero2, KnownOne2, Depth+1))
868 return true;
869 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
870
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000871 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000872 // These bits cannot contribute to the result of the 'and'.
873 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
874 return UpdateValueUsesWith(I, I->getOperand(0));
875 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
876 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000877
878 // If all of the demanded bits in the inputs are known zeros, return zero.
879 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
880 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
881
Chris Lattner0157e7f2006-02-11 09:31:47 +0000882 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000883 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000884 return UpdateValueUsesWith(I, I);
885
886 // Output known-1 bits are only known if set in both the LHS & RHS.
887 KnownOne &= KnownOne2;
888 // Output known-0 are known to be clear if zero in either the LHS | RHS.
889 KnownZero |= KnownZero2;
890 break;
891 case Instruction::Or:
892 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
893 KnownZero, KnownOne, Depth+1))
894 return true;
895 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
896 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
897 KnownZero2, KnownOne2, Depth+1))
898 return true;
899 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
900
901 // If all of the demanded bits are known zero on one side, return the other.
902 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000903 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000904 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000905 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000906 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000907
908 // If all of the potentially set bits on one side are known to be set on
909 // the other side, just use the 'other' side.
910 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
911 (DemandedMask & (~KnownZero)))
912 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000913 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
914 (DemandedMask & (~KnownZero2)))
915 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000916
917 // If the RHS is a constant, see if we can simplify it.
918 if (ShrinkDemandedConstant(I, 1, DemandedMask))
919 return UpdateValueUsesWith(I, I);
920
921 // Output known-0 bits are only known if clear in both the LHS & RHS.
922 KnownZero &= KnownZero2;
923 // Output known-1 are known to be set if set in either the LHS | RHS.
924 KnownOne |= KnownOne2;
925 break;
926 case Instruction::Xor: {
927 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
928 KnownZero, KnownOne, Depth+1))
929 return true;
930 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
931 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
932 KnownZero2, KnownOne2, Depth+1))
933 return true;
934 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
935
936 // If all of the demanded bits are known zero on one side, return the other.
937 // These bits cannot contribute to the result of the 'xor'.
938 if ((DemandedMask & KnownZero) == DemandedMask)
939 return UpdateValueUsesWith(I, I->getOperand(0));
940 if ((DemandedMask & KnownZero2) == DemandedMask)
941 return UpdateValueUsesWith(I, I->getOperand(1));
942
943 // Output known-0 bits are known if clear or set in both the LHS & RHS.
944 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
945 // Output known-1 are known to be set if set in only one of the LHS, RHS.
946 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
947
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000948 // If all of the demanded bits are known to be zero on one side or the
949 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000950 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000951 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
952 Instruction *Or =
953 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
954 I->getName());
955 InsertNewInstBefore(Or, *I);
956 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000957 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000958
Chris Lattner5b2edb12006-02-12 08:02:11 +0000959 // If all of the demanded bits on one side are known, and all of the set
960 // bits on that side are also known to be set on the other side, turn this
961 // into an AND, as we know the bits will be cleared.
962 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
963 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
964 if ((KnownOne & KnownOne2) == KnownOne) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000965 Constant *AndC = ConstantInt::get(I->getType(),
966 ~KnownOne & DemandedMask);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000967 Instruction *And =
968 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
969 InsertNewInstBefore(And, *I);
970 return UpdateValueUsesWith(I, And);
971 }
972 }
973
Chris Lattner0157e7f2006-02-11 09:31:47 +0000974 // If the RHS is a constant, see if we can simplify it.
975 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
976 if (ShrinkDemandedConstant(I, 1, DemandedMask))
977 return UpdateValueUsesWith(I, I);
978
979 KnownZero = KnownZeroOut;
980 KnownOne = KnownOneOut;
981 break;
982 }
983 case Instruction::Select:
984 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
985 KnownZero, KnownOne, Depth+1))
986 return true;
987 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
988 KnownZero2, KnownOne2, Depth+1))
989 return true;
990 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
991 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
992
993 // If the operands are constants, see if we can simplify them.
994 if (ShrinkDemandedConstant(I, 1, DemandedMask))
995 return UpdateValueUsesWith(I, I);
996 if (ShrinkDemandedConstant(I, 2, DemandedMask))
997 return UpdateValueUsesWith(I, I);
998
999 // Only known if known in both the LHS and RHS.
1000 KnownOne &= KnownOne2;
1001 KnownZero &= KnownZero2;
1002 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001003 case Instruction::Trunc:
1004 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1005 KnownZero, KnownOne, Depth+1))
1006 return true;
1007 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1008 break;
1009 case Instruction::BitCast:
Chris Lattner03c49532007-01-15 02:27:26 +00001010 if (!I->getOperand(0)->getType()->isInteger())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001011 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001012
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001013 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1014 KnownZero, KnownOne, Depth+1))
1015 return true;
1016 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1017 break;
1018 case Instruction::ZExt: {
1019 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001020 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1021 uint64_t NotIn = ~SrcTy->getBitMask();
1022 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001023
Reid Spencera94d3942007-01-19 21:13:56 +00001024 DemandedMask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001025 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1026 KnownZero, KnownOne, Depth+1))
1027 return true;
1028 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1029 // The top bits are known to be zero.
1030 KnownZero |= NewBits;
1031 break;
1032 }
1033 case Instruction::SExt: {
1034 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001035 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1036 uint64_t NotIn = ~SrcTy->getBitMask();
1037 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001038
1039 // Get the sign bit for the source type
1040 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
Reid Spencera94d3942007-01-19 21:13:56 +00001041 int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
Chris Lattner7d852282006-02-13 22:41:07 +00001042
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001043 // If any of the sign extended bits are demanded, we know that the sign
1044 // bit is demanded.
1045 if (NewBits & DemandedMask)
1046 InputDemandedBits |= InSignBit;
Chris Lattner7d852282006-02-13 22:41:07 +00001047
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001048 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1049 KnownZero, KnownOne, Depth+1))
1050 return true;
1051 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0157e7f2006-02-11 09:31:47 +00001052
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001053 // If the sign bit of the input is known set or clear, then we know the
1054 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001055
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001056 // If the input sign bit is known zero, or if the NewBits are not demanded
1057 // convert this into a zero extension.
1058 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1059 // Convert to ZExt cast
1060 CastInst *NewCast = CastInst::create(
1061 Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1062 return UpdateValueUsesWith(I, NewCast);
1063 } else if (KnownOne & InSignBit) { // Input sign bit known set
1064 KnownOne |= NewBits;
1065 KnownZero &= ~NewBits;
1066 } else { // Input sign bit unknown
1067 KnownZero &= ~NewBits;
1068 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001069 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001070 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001071 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001072 case Instruction::Add:
1073 // If there is a constant on the RHS, there are a variety of xformations
1074 // we can do.
1075 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1076 // If null, this should be simplified elsewhere. Some of the xforms here
1077 // won't work if the RHS is zero.
1078 if (RHS->isNullValue())
1079 break;
1080
1081 // Figure out what the input bits are. If the top bits of the and result
1082 // are not demanded, then the add doesn't demand them from its input
1083 // either.
1084
1085 // Shift the demanded mask up so that it's at the top of the uint64_t.
1086 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1087 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1088
1089 // If the top bit of the output is demanded, demand everything from the
1090 // input. Otherwise, we demand all the input bits except NLZ top bits.
Jeff Cohen223004c2007-01-08 20:17:17 +00001091 uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001092
1093 // Find information about known zero/one bits in the input.
1094 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1095 KnownZero2, KnownOne2, Depth+1))
1096 return true;
1097
1098 // If the RHS of the add has bits set that can't affect the input, reduce
1099 // the constant.
1100 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1101 return UpdateValueUsesWith(I, I);
1102
1103 // Avoid excess work.
1104 if (KnownZero2 == 0 && KnownOne2 == 0)
1105 break;
1106
1107 // Turn it into OR if input bits are zero.
1108 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1109 Instruction *Or =
1110 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1111 I->getName());
1112 InsertNewInstBefore(Or, *I);
1113 return UpdateValueUsesWith(I, Or);
1114 }
1115
1116 // We can say something about the output known-zero and known-one bits,
1117 // depending on potential carries from the input constant and the
1118 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1119 // bits set and the RHS constant is 0x01001, then we know we have a known
1120 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1121
1122 // To compute this, we first compute the potential carry bits. These are
1123 // the bits which may be modified. I'm not aware of a better way to do
1124 // this scan.
1125 uint64_t RHSVal = RHS->getZExtValue();
1126
1127 bool CarryIn = false;
1128 uint64_t CarryBits = 0;
1129 uint64_t CurBit = 1;
1130 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1131 // Record the current carry in.
1132 if (CarryIn) CarryBits |= CurBit;
1133
1134 bool CarryOut;
1135
1136 // This bit has a carry out unless it is "zero + zero" or
1137 // "zero + anything" with no carry in.
1138 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1139 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1140 } else if (!CarryIn &&
1141 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1142 CarryOut = false; // 0 + anything has no carry out if no carry in.
1143 } else {
1144 // Otherwise, we have to assume we have a carry out.
1145 CarryOut = true;
1146 }
1147
1148 // This stage's carry out becomes the next stage's carry-in.
1149 CarryIn = CarryOut;
1150 }
1151
1152 // Now that we know which bits have carries, compute the known-1/0 sets.
1153
1154 // Bits are known one if they are known zero in one operand and one in the
1155 // other, and there is no input carry.
1156 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1157
1158 // Bits are known zero if they are known zero in both operands and there
1159 // is no input carry.
1160 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1161 }
1162 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001163 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001164 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1165 uint64_t ShiftAmt = SA->getZExtValue();
1166 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001167 KnownZero, KnownOne, Depth+1))
1168 return true;
1169 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001170 KnownZero <<= ShiftAmt;
1171 KnownOne <<= ShiftAmt;
1172 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001173 }
Chris Lattner2590e512006-02-07 06:56:34 +00001174 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001175 case Instruction::LShr:
1176 // For a logical shift right
1177 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1178 unsigned ShiftAmt = SA->getZExtValue();
1179
1180 // Compute the new bits that are at the top now.
1181 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1182 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Reid Spencera94d3942007-01-19 21:13:56 +00001183 uint64_t TypeMask = cast<IntegerType>(I->getType())->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001184 // Unsigned shift right.
1185 if (SimplifyDemandedBits(I->getOperand(0),
1186 (DemandedMask << ShiftAmt) & TypeMask,
1187 KnownZero, KnownOne, Depth+1))
1188 return true;
1189 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1190 KnownZero &= TypeMask;
1191 KnownOne &= TypeMask;
1192 KnownZero >>= ShiftAmt;
1193 KnownOne >>= ShiftAmt;
1194 KnownZero |= HighBits; // high bits known zero.
1195 }
1196 break;
1197 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001198 // If this is an arithmetic shift right and only the low-bit is set, we can
1199 // always convert this into a logical shr, even if the shift amount is
1200 // variable. The low bit of the shift cannot be an input sign bit unless
1201 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001202 if (DemandedMask == 1) {
1203 // Perform the logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00001204 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00001205 I->getOperand(0), I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001206 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001207 return UpdateValueUsesWith(I, NewVal);
1208 }
1209
Reid Spencere0fc4df2006-10-20 07:07:24 +00001210 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1211 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001212
1213 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001214 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1215 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Reid Spencera94d3942007-01-19 21:13:56 +00001216 uint64_t TypeMask = cast<IntegerType>(I->getType())->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001217 // Signed shift right.
1218 if (SimplifyDemandedBits(I->getOperand(0),
1219 (DemandedMask << ShiftAmt) & TypeMask,
1220 KnownZero, KnownOne, Depth+1))
1221 return true;
1222 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1223 KnownZero &= TypeMask;
1224 KnownOne &= TypeMask;
1225 KnownZero >>= ShiftAmt;
1226 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001227
Reid Spencerfdff9382006-11-08 06:47:33 +00001228 // Handle the sign bits.
1229 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1230 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001231
Reid Spencerfdff9382006-11-08 06:47:33 +00001232 // If the input sign bit is known to be zero, or if none of the top bits
1233 // are demanded, turn this into an unsigned shift right.
1234 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1235 // Perform the logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00001236 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00001237 I->getOperand(0), SA, I->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00001238 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1239 return UpdateValueUsesWith(I, NewVal);
1240 } else if (KnownOne & SignBit) { // New bits are known one.
1241 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001242 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001243 }
Chris Lattner2590e512006-02-07 06:56:34 +00001244 break;
1245 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001246
1247 // If the client is only demanding bits that we know, return the known
1248 // constant.
1249 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001250 return UpdateValueUsesWith(I, ConstantInt::get(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001251 return false;
1252}
1253
Chris Lattner2deeaea2006-10-05 06:55:50 +00001254
1255/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1256/// 64 or fewer elements. DemandedElts contains the set of elements that are
1257/// actually used by the caller. This method analyzes which elements of the
1258/// operand are undef and returns that information in UndefElts.
1259///
1260/// If the information about demanded elements can be used to simplify the
1261/// operation, the operation is simplified, then the resultant value is
1262/// returned. This returns null if no change was made.
1263Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1264 uint64_t &UndefElts,
1265 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001266 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001267 assert(VWidth <= 64 && "Vector too wide to analyze!");
1268 uint64_t EltMask = ~0ULL >> (64-VWidth);
1269 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1270 "Invalid DemandedElts!");
1271
1272 if (isa<UndefValue>(V)) {
1273 // If the entire vector is undefined, just return this info.
1274 UndefElts = EltMask;
1275 return 0;
1276 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1277 UndefElts = EltMask;
1278 return UndefValue::get(V->getType());
1279 }
1280
1281 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001282 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1283 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001284 Constant *Undef = UndefValue::get(EltTy);
1285
1286 std::vector<Constant*> Elts;
1287 for (unsigned i = 0; i != VWidth; ++i)
1288 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1289 Elts.push_back(Undef);
1290 UndefElts |= (1ULL << i);
1291 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1292 Elts.push_back(Undef);
1293 UndefElts |= (1ULL << i);
1294 } else { // Otherwise, defined.
1295 Elts.push_back(CP->getOperand(i));
1296 }
1297
1298 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001299 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001300 return NewCP != CP ? NewCP : 0;
1301 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001302 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001303 // set to undef.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001304 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001305 Constant *Zero = Constant::getNullValue(EltTy);
1306 Constant *Undef = UndefValue::get(EltTy);
1307 std::vector<Constant*> Elts;
1308 for (unsigned i = 0; i != VWidth; ++i)
1309 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1310 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001311 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001312 }
1313
1314 if (!V->hasOneUse()) { // Other users may use these bits.
1315 if (Depth != 0) { // Not at the root.
1316 // TODO: Just compute the UndefElts information recursively.
1317 return false;
1318 }
1319 return false;
1320 } else if (Depth == 10) { // Limit search depth.
1321 return false;
1322 }
1323
1324 Instruction *I = dyn_cast<Instruction>(V);
1325 if (!I) return false; // Only analyze instructions.
1326
1327 bool MadeChange = false;
1328 uint64_t UndefElts2;
1329 Value *TmpV;
1330 switch (I->getOpcode()) {
1331 default: break;
1332
1333 case Instruction::InsertElement: {
1334 // If this is a variable index, we don't know which element it overwrites.
1335 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001336 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001337 if (Idx == 0) {
1338 // Note that we can't propagate undef elt info, because we don't know
1339 // which elt is getting updated.
1340 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1341 UndefElts2, Depth+1);
1342 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1343 break;
1344 }
1345
1346 // If this is inserting an element that isn't demanded, remove this
1347 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001348 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001349 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1350 return AddSoonDeadInstToWorklist(*I, 0);
1351
1352 // Otherwise, the element inserted overwrites whatever was there, so the
1353 // input demanded set is simpler than the output set.
1354 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1355 DemandedElts & ~(1ULL << IdxNo),
1356 UndefElts, Depth+1);
1357 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1358
1359 // The inserted element is defined.
1360 UndefElts |= 1ULL << IdxNo;
1361 break;
1362 }
1363
1364 case Instruction::And:
1365 case Instruction::Or:
1366 case Instruction::Xor:
1367 case Instruction::Add:
1368 case Instruction::Sub:
1369 case Instruction::Mul:
1370 // div/rem demand all inputs, because they don't want divide by zero.
1371 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1372 UndefElts, Depth+1);
1373 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1374 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1375 UndefElts2, Depth+1);
1376 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1377
1378 // Output elements are undefined if both are undefined. Consider things
1379 // like undef&0. The result is known zero, not undef.
1380 UndefElts &= UndefElts2;
1381 break;
1382
1383 case Instruction::Call: {
1384 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1385 if (!II) break;
1386 switch (II->getIntrinsicID()) {
1387 default: break;
1388
1389 // Binary vector operations that work column-wise. A dest element is a
1390 // function of the corresponding input elements from the two inputs.
1391 case Intrinsic::x86_sse_sub_ss:
1392 case Intrinsic::x86_sse_mul_ss:
1393 case Intrinsic::x86_sse_min_ss:
1394 case Intrinsic::x86_sse_max_ss:
1395 case Intrinsic::x86_sse2_sub_sd:
1396 case Intrinsic::x86_sse2_mul_sd:
1397 case Intrinsic::x86_sse2_min_sd:
1398 case Intrinsic::x86_sse2_max_sd:
1399 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1400 UndefElts, Depth+1);
1401 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1402 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1403 UndefElts2, Depth+1);
1404 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1405
1406 // If only the low elt is demanded and this is a scalarizable intrinsic,
1407 // scalarize it now.
1408 if (DemandedElts == 1) {
1409 switch (II->getIntrinsicID()) {
1410 default: break;
1411 case Intrinsic::x86_sse_sub_ss:
1412 case Intrinsic::x86_sse_mul_ss:
1413 case Intrinsic::x86_sse2_sub_sd:
1414 case Intrinsic::x86_sse2_mul_sd:
1415 // TODO: Lower MIN/MAX/ABS/etc
1416 Value *LHS = II->getOperand(1);
1417 Value *RHS = II->getOperand(2);
1418 // Extract the element as scalars.
1419 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1420 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1421
1422 switch (II->getIntrinsicID()) {
1423 default: assert(0 && "Case stmts out of sync!");
1424 case Intrinsic::x86_sse_sub_ss:
1425 case Intrinsic::x86_sse2_sub_sd:
1426 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1427 II->getName()), *II);
1428 break;
1429 case Intrinsic::x86_sse_mul_ss:
1430 case Intrinsic::x86_sse2_mul_sd:
1431 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1432 II->getName()), *II);
1433 break;
1434 }
1435
1436 Instruction *New =
1437 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1438 II->getName());
1439 InsertNewInstBefore(New, *II);
1440 AddSoonDeadInstToWorklist(*II, 0);
1441 return New;
1442 }
1443 }
1444
1445 // Output elements are undefined if both are undefined. Consider things
1446 // like undef&0. The result is known zero, not undef.
1447 UndefElts &= UndefElts2;
1448 break;
1449 }
1450 break;
1451 }
1452 }
1453 return MadeChange ? I : 0;
1454}
1455
Reid Spencer266e42b2006-12-23 06:05:41 +00001456/// @returns true if the specified compare instruction is
1457/// true when both operands are equal...
1458/// @brief Determine if the ICmpInst returns true if both operands are equal
1459static bool isTrueWhenEqual(ICmpInst &ICI) {
1460 ICmpInst::Predicate pred = ICI.getPredicate();
1461 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1462 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1463 pred == ICmpInst::ICMP_SLE;
1464}
1465
Chris Lattnerb8b97502003-08-13 19:01:45 +00001466/// AssociativeOpt - Perform an optimization on an associative operator. This
1467/// function is designed to check a chain of associative operators for a
1468/// potential to apply a certain optimization. Since the optimization may be
1469/// applicable if the expression was reassociated, this checks the chain, then
1470/// reassociates the expression as necessary to expose the optimization
1471/// opportunity. This makes use of a special Functor, which must define
1472/// 'shouldApply' and 'apply' methods.
1473///
1474template<typename Functor>
1475Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1476 unsigned Opcode = Root.getOpcode();
1477 Value *LHS = Root.getOperand(0);
1478
1479 // Quick check, see if the immediate LHS matches...
1480 if (F.shouldApply(LHS))
1481 return F.apply(Root);
1482
1483 // Otherwise, if the LHS is not of the same opcode as the root, return.
1484 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001485 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001486 // Should we apply this transform to the RHS?
1487 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1488
1489 // If not to the RHS, check to see if we should apply to the LHS...
1490 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1491 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1492 ShouldApply = true;
1493 }
1494
1495 // If the functor wants to apply the optimization to the RHS of LHSI,
1496 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1497 if (ShouldApply) {
1498 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001499
Chris Lattnerb8b97502003-08-13 19:01:45 +00001500 // Now all of the instructions are in the current basic block, go ahead
1501 // and perform the reassociation.
1502 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1503
1504 // First move the selected RHS to the LHS of the root...
1505 Root.setOperand(0, LHSI->getOperand(1));
1506
1507 // Make what used to be the LHS of the root be the user of the root...
1508 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001509 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001510 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1511 return 0;
1512 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001513 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001514 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001515 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1516 BasicBlock::iterator ARI = &Root; ++ARI;
1517 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1518 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001519
1520 // Now propagate the ExtraOperand down the chain of instructions until we
1521 // get to LHSI.
1522 while (TmpLHSI != LHSI) {
1523 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001524 // Move the instruction to immediately before the chain we are
1525 // constructing to avoid breaking dominance properties.
1526 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1527 BB->getInstList().insert(ARI, NextLHSI);
1528 ARI = NextLHSI;
1529
Chris Lattnerb8b97502003-08-13 19:01:45 +00001530 Value *NextOp = NextLHSI->getOperand(1);
1531 NextLHSI->setOperand(1, ExtraOperand);
1532 TmpLHSI = NextLHSI;
1533 ExtraOperand = NextOp;
1534 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001535
Chris Lattnerb8b97502003-08-13 19:01:45 +00001536 // Now that the instructions are reassociated, have the functor perform
1537 // the transformation...
1538 return F.apply(Root);
1539 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001540
Chris Lattnerb8b97502003-08-13 19:01:45 +00001541 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1542 }
1543 return 0;
1544}
1545
1546
1547// AddRHS - Implements: X + X --> X << 1
1548struct AddRHS {
1549 Value *RHS;
1550 AddRHS(Value *rhs) : RHS(rhs) {}
1551 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1552 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer0d5f9232007-02-02 14:08:20 +00001553 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer2341c222007-02-02 02:16:23 +00001554 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001555 }
1556};
1557
1558// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1559// iff C1&C2 == 0
1560struct AddMaskingAnd {
1561 Constant *C2;
1562 AddMaskingAnd(Constant *c) : C2(c) {}
1563 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001564 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001565 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001566 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001567 }
1568 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001569 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001570 }
1571};
1572
Chris Lattner86102b82005-01-01 16:22:27 +00001573static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001574 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001575 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001576 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001577 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001578
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001579 return IC->InsertNewInstBefore(CastInst::create(
1580 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001581 }
1582
Chris Lattner183b3362004-04-09 19:05:30 +00001583 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001584 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1585 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001586
Chris Lattner183b3362004-04-09 19:05:30 +00001587 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1588 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001589 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1590 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001591 }
1592
1593 Value *Op0 = SO, *Op1 = ConstOperand;
1594 if (!ConstIsRHS)
1595 std::swap(Op0, Op1);
1596 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001597 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1598 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001599 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1600 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1601 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001602 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001603 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001604 abort();
1605 }
Chris Lattner86102b82005-01-01 16:22:27 +00001606 return IC->InsertNewInstBefore(New, I);
1607}
1608
1609// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1610// constant as the other operand, try to fold the binary operator into the
1611// select arguments. This also works for Cast instructions, which obviously do
1612// not have a second operand.
1613static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1614 InstCombiner *IC) {
1615 // Don't modify shared select instructions
1616 if (!SI->hasOneUse()) return 0;
1617 Value *TV = SI->getOperand(1);
1618 Value *FV = SI->getOperand(2);
1619
1620 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001621 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001622 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001623
Chris Lattner86102b82005-01-01 16:22:27 +00001624 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1625 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1626
1627 return new SelectInst(SI->getCondition(), SelectTrueVal,
1628 SelectFalseVal);
1629 }
1630 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001631}
1632
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001633
1634/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1635/// node as operand #0, see if we can fold the instruction into the PHI (which
1636/// is only possible if all operands to the PHI are constants).
1637Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1638 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001639 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001640 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001641
Chris Lattner04689872006-09-09 22:02:56 +00001642 // Check to see if all of the operands of the PHI are constants. If there is
1643 // one non-constant value, remember the BB it is. If there is more than one
1644 // bail out.
1645 BasicBlock *NonConstBB = 0;
1646 for (unsigned i = 0; i != NumPHIValues; ++i)
1647 if (!isa<Constant>(PN->getIncomingValue(i))) {
1648 if (NonConstBB) return 0; // More than one non-const value.
1649 NonConstBB = PN->getIncomingBlock(i);
1650
1651 // If the incoming non-constant value is in I's block, we have an infinite
1652 // loop.
1653 if (NonConstBB == I.getParent())
1654 return 0;
1655 }
1656
1657 // If there is exactly one non-constant value, we can insert a copy of the
1658 // operation in that block. However, if this is a critical edge, we would be
1659 // inserting the computation one some other paths (e.g. inside a loop). Only
1660 // do this if the pred block is unconditionally branching into the phi block.
1661 if (NonConstBB) {
1662 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1663 if (!BI || !BI->isUnconditional()) return 0;
1664 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001665
1666 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6e0123b2007-02-11 01:23:03 +00001667 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001668 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001669 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00001670 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001671
1672 // Next, add all of the operands to the PHI.
1673 if (I.getNumOperands() == 2) {
1674 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001675 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001676 Value *InV;
1677 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001678 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1679 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1680 else
1681 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001682 } else {
1683 assert(PN->getIncomingBlock(i) == NonConstBB);
1684 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1685 InV = BinaryOperator::create(BO->getOpcode(),
1686 PN->getIncomingValue(i), C, "phitmp",
1687 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001688 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1689 InV = CmpInst::create(CI->getOpcode(),
1690 CI->getPredicate(),
1691 PN->getIncomingValue(i), C, "phitmp",
1692 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001693 else
1694 assert(0 && "Unknown binop!");
1695
1696 WorkList.push_back(cast<Instruction>(InV));
1697 }
1698 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001699 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001700 } else {
1701 CastInst *CI = cast<CastInst>(&I);
1702 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001703 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001704 Value *InV;
1705 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001706 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001707 } else {
1708 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001709 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1710 I.getType(), "phitmp",
1711 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001712 WorkList.push_back(cast<Instruction>(InV));
1713 }
1714 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001715 }
1716 }
1717 return ReplaceInstUsesWith(I, NewPN);
1718}
1719
Chris Lattner113f4f42002-06-25 16:13:24 +00001720Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001721 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001722 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001723
Chris Lattnercf4a9962004-04-10 22:01:55 +00001724 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001725 // X + undef -> undef
1726 if (isa<UndefValue>(RHS))
1727 return ReplaceInstUsesWith(I, RHS);
1728
Chris Lattnercf4a9962004-04-10 22:01:55 +00001729 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001730 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001731 if (RHSC->isNullValue())
1732 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001733 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1734 if (CFP->isExactlyValue(-0.0))
1735 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001736 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001737
Chris Lattnercf4a9962004-04-10 22:01:55 +00001738 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001739 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00001740 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001741 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001742 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001743
1744 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1745 // (X & 254)+1 -> (X&254)|1
1746 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001747 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00001748 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001749 KnownZero, KnownOne))
1750 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00001751 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001752
1753 if (isa<PHINode>(LHS))
1754 if (Instruction *NV = FoldOpIntoPhi(I))
1755 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001756
Chris Lattner330628a2006-01-06 17:59:59 +00001757 ConstantInt *XorRHS = 0;
1758 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00001759 if (isa<ConstantInt>(RHSC) &&
1760 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001761 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1762 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1763 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1764
1765 uint64_t C0080Val = 1ULL << 31;
1766 int64_t CFF80Val = -C0080Val;
1767 unsigned Size = 32;
1768 do {
1769 if (TySizeBits > Size) {
1770 bool Found = false;
1771 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1772 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1773 if (RHSSExt == CFF80Val) {
1774 if (XorRHS->getZExtValue() == C0080Val)
1775 Found = true;
1776 } else if (RHSZExt == C0080Val) {
1777 if (XorRHS->getSExtValue() == CFF80Val)
1778 Found = true;
1779 }
1780 if (Found) {
1781 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001782 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001783 Mask <<= 64-(TySizeBits-Size);
Reid Spencera94d3942007-01-19 21:13:56 +00001784 Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001785 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001786 Size = 0; // Not a sign ext, but can't be any others either.
1787 goto FoundSExt;
1788 }
1789 }
1790 Size >>= 1;
1791 C0080Val >>= Size;
1792 CFF80Val >>= Size;
1793 } while (Size >= 8);
1794
1795FoundSExt:
1796 const Type *MiddleType = 0;
1797 switch (Size) {
1798 default: break;
Reid Spencerc635f472006-12-31 05:48:39 +00001799 case 32: MiddleType = Type::Int32Ty; break;
1800 case 16: MiddleType = Type::Int16Ty; break;
1801 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001802 }
1803 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001804 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001805 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001806 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001807 }
1808 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001809 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001810
Chris Lattnerb8b97502003-08-13 19:01:45 +00001811 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00001812 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001813 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001814
1815 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1816 if (RHSI->getOpcode() == Instruction::Sub)
1817 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1818 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1819 }
1820 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1821 if (LHSI->getOpcode() == Instruction::Sub)
1822 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1823 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1824 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001825 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001826
Chris Lattner147e9752002-05-08 22:46:53 +00001827 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001828 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001829 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001830
1831 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001832 if (!isa<Constant>(RHS))
1833 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001834 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001835
Misha Brukmanb1c93172005-04-21 23:48:37 +00001836
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001837 ConstantInt *C2;
1838 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1839 if (X == RHS) // X*C + X --> X * (C+1)
1840 return BinaryOperator::createMul(RHS, AddOne(C2));
1841
1842 // X*C1 + X*C2 --> X * (C1+C2)
1843 ConstantInt *C1;
1844 if (X == dyn_castFoldableMul(RHS, C1))
1845 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001846 }
1847
1848 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001849 if (dyn_castFoldableMul(RHS, C2) == LHS)
1850 return BinaryOperator::createMul(LHS, AddOne(C2));
1851
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001852 // X + ~X --> -1 since ~X = -X-1
1853 if (dyn_castNotVal(LHS) == RHS ||
1854 dyn_castNotVal(RHS) == LHS)
1855 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1856
Chris Lattner57c8d992003-02-18 19:57:07 +00001857
Chris Lattnerb8b97502003-08-13 19:01:45 +00001858 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001859 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001860 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1861 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001862
Chris Lattnerb9cde762003-10-02 15:11:26 +00001863 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001864 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001865 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1866 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1867 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001868 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001869
Chris Lattnerbff91d92004-10-08 05:07:56 +00001870 // (X & FF00) + xx00 -> (X+xx00) & FF00
1871 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1872 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1873 if (Anded == CRHS) {
1874 // See if all bits from the first bit set in the Add RHS up are included
1875 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001876 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001877
1878 // Form a mask of all bits from the lowest bit added through the top.
1879 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Reid Spencera94d3942007-01-19 21:13:56 +00001880 AddRHSHighBits &= C2->getType()->getBitMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001881
1882 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001883 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001884
Chris Lattnerbff91d92004-10-08 05:07:56 +00001885 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1886 // Okay, the xform is safe. Insert the new add pronto.
1887 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1888 LHS->getName()), I);
1889 return BinaryOperator::createAnd(NewAdd, C2);
1890 }
1891 }
1892 }
1893
Chris Lattnerd4252a72004-07-30 07:50:03 +00001894 // Try to fold constant add into select arguments.
1895 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001896 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001897 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001898 }
1899
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001900 // add (cast *A to intptrtype) B ->
1901 // cast (GEP (cast *A to sbyte*) B) ->
1902 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001903 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001904 CastInst *CI = dyn_cast<CastInst>(LHS);
1905 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001906 if (!CI) {
1907 CI = dyn_cast<CastInst>(RHS);
1908 Other = LHS;
1909 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001910 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00001911 (CI->getType()->getPrimitiveSizeInBits() ==
1912 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001913 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00001914 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001915 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001916 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001917 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001918 }
1919 }
1920
Chris Lattner113f4f42002-06-25 16:13:24 +00001921 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001922}
1923
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001924// isSignBit - Return true if the value represented by the constant only has the
1925// highest order bit set.
1926static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001927 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001928 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001929}
1930
Chris Lattner113f4f42002-06-25 16:13:24 +00001931Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001932 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001933
Chris Lattnere6794492002-08-12 21:17:25 +00001934 if (Op0 == Op1) // sub X, X -> 0
1935 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001936
Chris Lattnere6794492002-08-12 21:17:25 +00001937 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001938 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001939 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001940
Chris Lattner81a7a232004-10-16 18:11:37 +00001941 if (isa<UndefValue>(Op0))
1942 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1943 if (isa<UndefValue>(Op1))
1944 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1945
Chris Lattner8f2f5982003-11-05 01:06:05 +00001946 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1947 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001948 if (C->isAllOnesValue())
1949 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001950
Chris Lattner8f2f5982003-11-05 01:06:05 +00001951 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001952 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001953 if (match(Op1, m_Not(m_Value(X))))
1954 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001955 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner27df1db2007-01-15 07:02:54 +00001956 // -(X >>u 31) -> (X >>s 31)
1957 // -(X >>s 31) -> (X >>u 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001958 if (C->isNullValue()) {
Reid Spencer2341c222007-02-02 02:16:23 +00001959 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00001960 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001961 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001962 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001963 if (CU->getZExtValue() ==
1964 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001965 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00001966 return BinaryOperator::create(Instruction::AShr,
1967 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00001968 }
1969 }
Reid Spencerfdff9382006-11-08 06:47:33 +00001970 }
1971 else if (SI->getOpcode() == Instruction::AShr) {
1972 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1973 // Check to see if we are shifting out everything but the sign bit.
1974 if (CU->getZExtValue() ==
1975 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00001976 // Ok, the transformation is safe. Insert LShr.
Reid Spencer0d5f9232007-02-02 14:08:20 +00001977 return BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00001978 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00001979 }
1980 }
1981 }
Chris Lattner022167f2004-03-13 00:11:49 +00001982 }
Chris Lattner183b3362004-04-09 19:05:30 +00001983
1984 // Try to fold constant sub into select arguments.
1985 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001986 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001987 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001988
1989 if (isa<PHINode>(Op0))
1990 if (Instruction *NV = FoldOpIntoPhi(I))
1991 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001992 }
1993
Chris Lattnera9be4492005-04-07 16:15:25 +00001994 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1995 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00001996 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001997 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001998 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001999 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002000 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002001 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2002 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2003 // C1-(X+C2) --> (C1-C2)-X
2004 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2005 Op1I->getOperand(0));
2006 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002007 }
2008
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002009 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002010 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2011 // is not used by anyone else...
2012 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002013 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002014 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002015 // Swap the two operands of the subexpr...
2016 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2017 Op1I->setOperand(0, IIOp1);
2018 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002019
Chris Lattner3082c5a2003-02-18 19:28:33 +00002020 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002021 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002022 }
2023
2024 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2025 //
2026 if (Op1I->getOpcode() == Instruction::And &&
2027 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2028 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2029
Chris Lattner396dbfe2004-06-09 05:08:07 +00002030 Value *NewNot =
2031 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002032 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002033 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002034
Reid Spencer3c514952006-10-16 23:08:08 +00002035 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002036 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002037 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002038 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002039 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002040 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002041 ConstantExpr::getNeg(DivRHS));
2042
Chris Lattner57c8d992003-02-18 19:57:07 +00002043 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002044 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002045 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002046 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002047 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002048 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002049 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002050 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002051 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002052
Chris Lattner7a002fe2006-12-02 00:13:08 +00002053 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002054 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2055 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002056 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2057 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2058 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2059 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002060 } else if (Op0I->getOpcode() == Instruction::Sub) {
2061 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2062 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002063 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002064
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002065 ConstantInt *C1;
2066 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2067 if (X == Op1) { // X*C - X --> X * (C-1)
2068 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2069 return BinaryOperator::createMul(Op1, CP1);
2070 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002071
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002072 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2073 if (X == dyn_castFoldableMul(Op1, C2))
2074 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2075 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002076 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002077}
2078
Reid Spencer266e42b2006-12-23 06:05:41 +00002079/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002080/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002081static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2082 switch (pred) {
2083 case ICmpInst::ICMP_SLT:
2084 // True if LHS s< RHS and RHS == 0
2085 return RHS->isNullValue();
2086 case ICmpInst::ICMP_SLE:
2087 // True if LHS s<= RHS and RHS == -1
2088 return RHS->isAllOnesValue();
2089 case ICmpInst::ICMP_UGE:
2090 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2091 return RHS->getZExtValue() == (1ULL <<
2092 (RHS->getType()->getPrimitiveSizeInBits()-1));
2093 case ICmpInst::ICMP_UGT:
2094 // True if LHS u> RHS and RHS == high-bit-mask - 1
2095 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002096 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002097 default:
2098 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002099 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002100}
2101
Chris Lattner113f4f42002-06-25 16:13:24 +00002102Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002103 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002104 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002105
Chris Lattner81a7a232004-10-16 18:11:37 +00002106 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2107 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2108
Chris Lattnere6794492002-08-12 21:17:25 +00002109 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002110 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2111 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002112
2113 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002114 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002115 if (SI->getOpcode() == Instruction::Shl)
2116 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002117 return BinaryOperator::createMul(SI->getOperand(0),
2118 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002119
Chris Lattnercce81be2003-09-11 22:24:54 +00002120 if (CI->isNullValue())
2121 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2122 if (CI->equalsInt(1)) // X * 1 == X
2123 return ReplaceInstUsesWith(I, Op0);
2124 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002125 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002126
Reid Spencere0fc4df2006-10-20 07:07:24 +00002127 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002128 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2129 uint64_t C = Log2_64(Val);
Reid Spencer0d5f9232007-02-02 14:08:20 +00002130 return BinaryOperator::createShl(Op0,
Reid Spencer2341c222007-02-02 02:16:23 +00002131 ConstantInt::get(Op0->getType(), C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002132 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002133 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002134 if (Op1F->isNullValue())
2135 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002136
Chris Lattner3082c5a2003-02-18 19:28:33 +00002137 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2138 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2139 if (Op1F->getValue() == 1.0)
2140 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2141 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002142
2143 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2144 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2145 isa<ConstantInt>(Op0I->getOperand(1))) {
2146 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2147 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2148 Op1, "tmp");
2149 InsertNewInstBefore(Add, I);
2150 Value *C1C2 = ConstantExpr::getMul(Op1,
2151 cast<Constant>(Op0I->getOperand(1)));
2152 return BinaryOperator::createAdd(Add, C1C2);
2153
2154 }
Chris Lattner183b3362004-04-09 19:05:30 +00002155
2156 // Try to fold constant mul into select arguments.
2157 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002158 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002159 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002160
2161 if (isa<PHINode>(Op0))
2162 if (Instruction *NV = FoldOpIntoPhi(I))
2163 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002164 }
2165
Chris Lattner934a64cf2003-03-10 23:23:04 +00002166 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2167 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002168 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002169
Chris Lattner2635b522004-02-23 05:39:21 +00002170 // If one of the operands of the multiply is a cast from a boolean value, then
2171 // we know the bool is either zero or one, so this is a 'masking' multiply.
2172 // See if we can simplify things based on how the boolean was originally
2173 // formed.
2174 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002175 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002176 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002177 BoolCast = CI;
2178 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002179 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002180 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002181 BoolCast = CI;
2182 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002183 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002184 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2185 const Type *SCOpTy = SCIOp0->getType();
2186
Reid Spencer266e42b2006-12-23 06:05:41 +00002187 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002188 // multiply into a shift/and combination.
2189 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002190 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002191 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00002192 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002193 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002194 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002195 InsertNewInstBefore(
2196 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002197 BoolCast->getOperand(0)->getName()+
2198 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002199
2200 // If the multiply type is not the same as the source type, sign extend
2201 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002202 if (I.getType() != V->getType()) {
2203 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2204 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2205 Instruction::CastOps opcode =
2206 (SrcBits == DstBits ? Instruction::BitCast :
2207 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2208 V = InsertCastBefore(opcode, V, I.getType(), I);
2209 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002210
Chris Lattner2635b522004-02-23 05:39:21 +00002211 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002212 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002213 }
2214 }
2215 }
2216
Chris Lattner113f4f42002-06-25 16:13:24 +00002217 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002218}
2219
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002220/// This function implements the transforms on div instructions that work
2221/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2222/// used by the visitors to those instructions.
2223/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002224Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002225 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002226
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002227 // undef / X -> 0
2228 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002229 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002230
2231 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002232 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002233 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002234
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002235 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002236 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2237 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002238 // same basic block, then we replace the select with Y, and the condition
2239 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002240 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002241 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002242 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2243 if (ST->isNullValue()) {
2244 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2245 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002246 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002247 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2248 I.setOperand(1, SI->getOperand(2));
2249 else
2250 UpdateValueUsesWith(SI, SI->getOperand(2));
2251 return &I;
2252 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002253
Chris Lattnerd79dc792006-09-09 20:26:32 +00002254 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2255 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2256 if (ST->isNullValue()) {
2257 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2258 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002259 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002260 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2261 I.setOperand(1, SI->getOperand(1));
2262 else
2263 UpdateValueUsesWith(SI, SI->getOperand(1));
2264 return &I;
2265 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002266 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002267
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002268 return 0;
2269}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002270
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002271/// This function implements the transforms common to both integer division
2272/// instructions (udiv and sdiv). It is called by the visitors to those integer
2273/// division instructions.
2274/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002275Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002276 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2277
2278 if (Instruction *Common = commonDivTransforms(I))
2279 return Common;
2280
2281 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2282 // div X, 1 == X
2283 if (RHS->equalsInt(1))
2284 return ReplaceInstUsesWith(I, Op0);
2285
2286 // (X / C1) / C2 -> X / (C1*C2)
2287 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2288 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2289 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2290 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2291 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002292 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002293
2294 if (!RHS->isNullValue()) { // avoid X udiv 0
2295 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2296 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2297 return R;
2298 if (isa<PHINode>(Op0))
2299 if (Instruction *NV = FoldOpIntoPhi(I))
2300 return NV;
2301 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002302 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002303
Chris Lattner3082c5a2003-02-18 19:28:33 +00002304 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002305 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002306 if (LHS->equalsInt(0))
2307 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2308
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002309 return 0;
2310}
2311
2312Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2313 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2314
2315 // Handle the integer div common cases
2316 if (Instruction *Common = commonIDivTransforms(I))
2317 return Common;
2318
2319 // X udiv C^2 -> X >> C
2320 // Check to see if this is an unsigned division with an exact power of 2,
2321 // if so, convert to a right shift.
2322 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2323 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2324 if (isPowerOf2_64(Val)) {
2325 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencer0d5f9232007-02-02 14:08:20 +00002326 return BinaryOperator::createLShr(Op0,
Reid Spencer2341c222007-02-02 02:16:23 +00002327 ConstantInt::get(Op0->getType(), ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002328 }
2329 }
2330
2331 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00002332 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002333 if (RHSI->getOpcode() == Instruction::Shl &&
2334 isa<ConstantInt>(RHSI->getOperand(0))) {
2335 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2336 if (isPowerOf2_64(C1)) {
2337 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002338 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002339 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002340 Constant *C2V = ConstantInt::get(NTy, C2);
2341 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002342 }
Reid Spencer0d5f9232007-02-02 14:08:20 +00002343 return BinaryOperator::createLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002344 }
2345 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002346 }
2347
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002348 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2349 // where C1&C2 are powers of two.
2350 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2351 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2352 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2353 if (!STO->isNullValue() && !STO->isNullValue()) {
2354 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2355 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2356 // Compute the shift amounts
2357 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002358 // Construct the "on true" case of the select
Reid Spencer2341c222007-02-02 02:16:23 +00002359 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Reid Spencer0d5f9232007-02-02 14:08:20 +00002360 Instruction *TSI = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002361 Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002362 TSI = InsertNewInstBefore(TSI, I);
2363
2364 // Construct the "on false" case of the select
Reid Spencer2341c222007-02-02 02:16:23 +00002365 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Reid Spencer0d5f9232007-02-02 14:08:20 +00002366 Instruction *FSI = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002367 Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002368 FSI = InsertNewInstBefore(FSI, I);
2369
2370 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002371 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002372 }
2373 }
2374 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002375 return 0;
2376}
2377
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002378Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2379 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2380
2381 // Handle the integer div common cases
2382 if (Instruction *Common = commonIDivTransforms(I))
2383 return Common;
2384
2385 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2386 // sdiv X, -1 == -X
2387 if (RHS->isAllOnesValue())
2388 return BinaryOperator::createNeg(Op0);
2389
2390 // -X/C -> X/-C
2391 if (Value *LHSNeg = dyn_castNegVal(Op0))
2392 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2393 }
2394
2395 // If the sign bits of both operands are zero (i.e. we can prove they are
2396 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002397 if (I.getType()->isInteger()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002398 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2399 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2400 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2401 }
2402 }
2403
2404 return 0;
2405}
2406
2407Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2408 return commonDivTransforms(I);
2409}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002410
Chris Lattner85dda9a2006-03-02 06:50:58 +00002411/// GetFactor - If we can prove that the specified value is at least a multiple
2412/// of some factor, return that factor.
2413static Constant *GetFactor(Value *V) {
2414 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2415 return CI;
2416
2417 // Unless we can be tricky, we know this is a multiple of 1.
2418 Constant *Result = ConstantInt::get(V->getType(), 1);
2419
2420 Instruction *I = dyn_cast<Instruction>(V);
2421 if (!I) return Result;
2422
2423 if (I->getOpcode() == Instruction::Mul) {
2424 // Handle multiplies by a constant, etc.
2425 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2426 GetFactor(I->getOperand(1)));
2427 } else if (I->getOpcode() == Instruction::Shl) {
2428 // (X<<C) -> X * (1 << C)
2429 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2430 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2431 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2432 }
2433 } else if (I->getOpcode() == Instruction::And) {
2434 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2435 // X & 0xFFF0 is known to be a multiple of 16.
2436 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2437 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2438 return ConstantExpr::getShl(Result,
Reid Spencer2341c222007-02-02 02:16:23 +00002439 ConstantInt::get(Result->getType(), Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002440 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002441 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002442 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002443 if (!CI->isIntegerCast())
2444 return Result;
2445 Value *Op = CI->getOperand(0);
2446 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002447 }
2448 return Result;
2449}
2450
Reid Spencer7eb55b32006-11-02 01:53:59 +00002451/// This function implements the transforms on rem instructions that work
2452/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2453/// is used by the visitors to those instructions.
2454/// @brief Transforms common to all three rem instructions
2455Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002456 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002457
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002458 // 0 % X == 0, we don't need to preserve faults!
2459 if (Constant *LHS = dyn_cast<Constant>(Op0))
2460 if (LHS->isNullValue())
2461 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2462
2463 if (isa<UndefValue>(Op0)) // undef % X -> 0
2464 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2465 if (isa<UndefValue>(Op1))
2466 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002467
2468 // Handle cases involving: rem X, (select Cond, Y, Z)
2469 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2470 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2471 // the same basic block, then we replace the select with Y, and the
2472 // condition of the select with false (if the cond value is in the same
2473 // BB). If the select has uses other than the div, this allows them to be
2474 // simplified also.
2475 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2476 if (ST->isNullValue()) {
2477 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2478 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002479 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002480 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2481 I.setOperand(1, SI->getOperand(2));
2482 else
2483 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002484 return &I;
2485 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002486 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2487 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2488 if (ST->isNullValue()) {
2489 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2490 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002491 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002492 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2493 I.setOperand(1, SI->getOperand(1));
2494 else
2495 UpdateValueUsesWith(SI, SI->getOperand(1));
2496 return &I;
2497 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002498 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002499
Reid Spencer7eb55b32006-11-02 01:53:59 +00002500 return 0;
2501}
2502
2503/// This function implements the transforms common to both integer remainder
2504/// instructions (urem and srem). It is called by the visitors to those integer
2505/// remainder instructions.
2506/// @brief Common integer remainder transforms
2507Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2508 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2509
2510 if (Instruction *common = commonRemTransforms(I))
2511 return common;
2512
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002513 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002514 // X % 0 == undef, we don't need to preserve faults!
2515 if (RHS->equalsInt(0))
2516 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2517
Chris Lattner3082c5a2003-02-18 19:28:33 +00002518 if (RHS->equalsInt(1)) // X % 1 == 0
2519 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2520
Chris Lattnerb70f1412006-02-28 05:49:21 +00002521 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2522 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2523 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2524 return R;
2525 } else if (isa<PHINode>(Op0I)) {
2526 if (Instruction *NV = FoldOpIntoPhi(I))
2527 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002528 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002529 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2530 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002531 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002532 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002533 }
2534
Reid Spencer7eb55b32006-11-02 01:53:59 +00002535 return 0;
2536}
2537
2538Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2539 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2540
2541 if (Instruction *common = commonIRemTransforms(I))
2542 return common;
2543
2544 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2545 // X urem C^2 -> X and C
2546 // Check to see if this is an unsigned remainder with an exact power of 2,
2547 // if so, convert to a bitwise and.
2548 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2549 if (isPowerOf2_64(C->getZExtValue()))
2550 return BinaryOperator::createAnd(Op0, SubOne(C));
2551 }
2552
Chris Lattner2e90b732006-02-05 07:54:04 +00002553 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002554 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2555 if (RHSI->getOpcode() == Instruction::Shl &&
2556 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002557 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002558 if (isPowerOf2_64(C1)) {
2559 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2560 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2561 "tmp"), I);
2562 return BinaryOperator::createAnd(Op0, Add);
2563 }
2564 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002565 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002566
Reid Spencer7eb55b32006-11-02 01:53:59 +00002567 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2568 // where C1&C2 are powers of two.
2569 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2570 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2571 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2572 // STO == 0 and SFO == 0 handled above.
2573 if (isPowerOf2_64(STO->getZExtValue()) &&
2574 isPowerOf2_64(SFO->getZExtValue())) {
2575 Value *TrueAnd = InsertNewInstBefore(
2576 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2577 Value *FalseAnd = InsertNewInstBefore(
2578 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2579 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2580 }
2581 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002582 }
2583
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002584 return 0;
2585}
2586
Reid Spencer7eb55b32006-11-02 01:53:59 +00002587Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2588 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2589
2590 if (Instruction *common = commonIRemTransforms(I))
2591 return common;
2592
2593 if (Value *RHSNeg = dyn_castNegVal(Op1))
2594 if (!isa<ConstantInt>(RHSNeg) ||
2595 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2596 // X % -Y -> X % Y
2597 AddUsesToWorkList(I);
2598 I.setOperand(1, RHSNeg);
2599 return &I;
2600 }
2601
2602 // If the top bits of both operands are zero (i.e. we can prove they are
2603 // unsigned inputs), turn this into a urem.
2604 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2605 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2606 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2607 return BinaryOperator::createURem(Op0, Op1, I.getName());
2608 }
2609
2610 return 0;
2611}
2612
2613Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002614 return commonRemTransforms(I);
2615}
2616
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002617// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002618static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2619 if (isSigned) {
2620 // Calculate 0111111111..11111
2621 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2622 int64_t Val = INT64_MAX; // All ones
2623 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2624 return C->getSExtValue() == Val-1;
2625 }
Reid Spencera94d3942007-01-19 21:13:56 +00002626 return C->getZExtValue() == C->getType()->getBitMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002627}
2628
2629// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002630static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2631 if (isSigned) {
2632 // Calculate 1111111111000000000000
2633 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2634 int64_t Val = -1; // All ones
2635 Val <<= TypeBits-1; // Shift over to the right spot
2636 return C->getSExtValue() == Val+1;
2637 }
2638 return C->getZExtValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002639}
2640
Chris Lattner35167c32004-06-09 07:59:58 +00002641// isOneBitSet - Return true if there is exactly one bit set in the specified
2642// constant.
2643static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002644 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002645 return V && (V & (V-1)) == 0;
2646}
2647
Chris Lattner8fc5af42004-09-23 21:46:38 +00002648#if 0 // Currently unused
2649// isLowOnes - Return true if the constant is of the form 0+1+.
2650static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002651 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002652
2653 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002654 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002655
2656 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2657 return U && V && (U & V) == 0;
2658}
2659#endif
2660
2661// isHighOnes - Return true if the constant is of the form 1+0+.
2662// This is the same as lowones(~X).
2663static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002664 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002665 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002666
2667 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002668 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002669
2670 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2671 return U && V && (U & V) == 0;
2672}
2673
Reid Spencer266e42b2006-12-23 06:05:41 +00002674/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002675/// are carefully arranged to allow folding of expressions such as:
2676///
2677/// (A < B) | (A > B) --> (A != B)
2678///
Reid Spencer266e42b2006-12-23 06:05:41 +00002679/// Note that this is only valid if the first and second predicates have the
2680/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002681///
Reid Spencer266e42b2006-12-23 06:05:41 +00002682/// Three bits are used to represent the condition, as follows:
2683/// 0 A > B
2684/// 1 A == B
2685/// 2 A < B
2686///
2687/// <=> Value Definition
2688/// 000 0 Always false
2689/// 001 1 A > B
2690/// 010 2 A == B
2691/// 011 3 A >= B
2692/// 100 4 A < B
2693/// 101 5 A != B
2694/// 110 6 A <= B
2695/// 111 7 Always true
2696///
2697static unsigned getICmpCode(const ICmpInst *ICI) {
2698 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002699 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002700 case ICmpInst::ICMP_UGT: return 1; // 001
2701 case ICmpInst::ICMP_SGT: return 1; // 001
2702 case ICmpInst::ICMP_EQ: return 2; // 010
2703 case ICmpInst::ICMP_UGE: return 3; // 011
2704 case ICmpInst::ICMP_SGE: return 3; // 011
2705 case ICmpInst::ICMP_ULT: return 4; // 100
2706 case ICmpInst::ICMP_SLT: return 4; // 100
2707 case ICmpInst::ICMP_NE: return 5; // 101
2708 case ICmpInst::ICMP_ULE: return 6; // 110
2709 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002710 // True -> 7
2711 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002712 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002713 return 0;
2714 }
2715}
2716
Reid Spencer266e42b2006-12-23 06:05:41 +00002717/// getICmpValue - This is the complement of getICmpCode, which turns an
2718/// opcode and two operands into either a constant true or false, or a brand
2719/// new /// ICmp instruction. The sign is passed in to determine which kind
2720/// of predicate to use in new icmp instructions.
2721static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2722 switch (code) {
2723 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002724 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002725 case 1:
2726 if (sign)
2727 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2728 else
2729 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2730 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2731 case 3:
2732 if (sign)
2733 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2734 else
2735 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2736 case 4:
2737 if (sign)
2738 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2739 else
2740 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2741 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2742 case 6:
2743 if (sign)
2744 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2745 else
2746 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002747 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002748 }
2749}
2750
Reid Spencer266e42b2006-12-23 06:05:41 +00002751static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2752 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2753 (ICmpInst::isSignedPredicate(p1) &&
2754 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2755 (ICmpInst::isSignedPredicate(p2) &&
2756 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2757}
2758
2759namespace {
2760// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2761struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002762 InstCombiner &IC;
2763 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002764 ICmpInst::Predicate pred;
2765 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2766 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2767 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002768 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002769 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2770 if (PredicatesFoldable(pred, ICI->getPredicate()))
2771 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2772 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002773 return false;
2774 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002775 Instruction *apply(Instruction &Log) const {
2776 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2777 if (ICI->getOperand(0) != LHS) {
2778 assert(ICI->getOperand(1) == LHS);
2779 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002780 }
2781
Reid Spencer266e42b2006-12-23 06:05:41 +00002782 unsigned LHSCode = getICmpCode(ICI);
2783 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattner3ac7c262003-08-13 20:16:26 +00002784 unsigned Code;
2785 switch (Log.getOpcode()) {
2786 case Instruction::And: Code = LHSCode & RHSCode; break;
2787 case Instruction::Or: Code = LHSCode | RHSCode; break;
2788 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002789 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002790 }
2791
Reid Spencer266e42b2006-12-23 06:05:41 +00002792 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002793 if (Instruction *I = dyn_cast<Instruction>(RV))
2794 return I;
2795 // Otherwise, it's a constant boolean value...
2796 return IC.ReplaceInstUsesWith(Log, RV);
2797 }
2798};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002799} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002800
Chris Lattnerba1cb382003-09-19 17:17:26 +00002801// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2802// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00002803// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00002804Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00002805 ConstantInt *OpRHS,
2806 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00002807 BinaryOperator &TheAnd) {
2808 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002809 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00002810 if (!Op->isShift())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002811 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002812
Chris Lattnerba1cb382003-09-19 17:17:26 +00002813 switch (Op->getOpcode()) {
2814 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002815 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002816 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6e0123b2007-02-11 01:23:03 +00002817 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002818 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002819 And->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002820 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002821 }
2822 break;
2823 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002824 if (Together == AndRHS) // (X | C) & C --> C
2825 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002826
Chris Lattner86102b82005-01-01 16:22:27 +00002827 if (Op->hasOneUse() && Together != OpRHS) {
2828 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6e0123b2007-02-11 01:23:03 +00002829 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00002830 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002831 Or->takeName(Op);
Chris Lattner86102b82005-01-01 16:22:27 +00002832 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002833 }
2834 break;
2835 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002836 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002837 // Adding a one to a single bit bit-field should be turned into an XOR
2838 // of the bit. First thing to check is to see if this AND is with a
2839 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002840 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002841
2842 // Clear bits that are not part of the constant.
Reid Spencera94d3942007-01-19 21:13:56 +00002843 AndRHSV &= AndRHS->getType()->getBitMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002844
2845 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002846 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002847 // Ok, at this point, we know that we are masking the result of the
2848 // ADD down to exactly one bit. If the constant we are adding has
2849 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002850 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002851
Chris Lattnerba1cb382003-09-19 17:17:26 +00002852 // Check to see if any bits below the one bit set in AndRHSV are set.
2853 if ((AddRHS & (AndRHSV-1)) == 0) {
2854 // If not, the only thing that can effect the output of the AND is
2855 // the bit specified by AndRHSV. If that bit is set, the effect of
2856 // the XOR is to toggle the bit. If it is clear, then the ADD has
2857 // no effect.
2858 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2859 TheAnd.setOperand(0, X);
2860 return &TheAnd;
2861 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002862 // Pull the XOR out of the AND.
Chris Lattner6e0123b2007-02-11 01:23:03 +00002863 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002864 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002865 NewAnd->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002866 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002867 }
2868 }
2869 }
2870 }
2871 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002872
2873 case Instruction::Shl: {
2874 // We know that the AND will not produce any of the bits shifted in, so if
2875 // the anded constant includes them, clear them now!
2876 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002877 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002878 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2879 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002880
Chris Lattner7e794272004-09-24 15:21:34 +00002881 if (CI == ShlMask) { // Masking out bits that the shift already masks
2882 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2883 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002884 TheAnd.setOperand(1, CI);
2885 return &TheAnd;
2886 }
2887 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002888 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002889 case Instruction::LShr:
2890 {
Chris Lattner2da29172003-09-19 19:05:02 +00002891 // We know that the AND will not produce any of the bits shifted in, so if
2892 // the anded constant includes them, clear them now! This only applies to
2893 // unsigned shifts, because a signed shr may bring in set bits!
2894 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002895 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00002896 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2897 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002898
Reid Spencerfdff9382006-11-08 06:47:33 +00002899 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2900 return ReplaceInstUsesWith(TheAnd, Op);
2901 } else if (CI != AndRHS) {
2902 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2903 return &TheAnd;
2904 }
2905 break;
2906 }
2907 case Instruction::AShr:
2908 // Signed shr.
2909 // See if this is shifting in some sign extension, then masking it out
2910 // with an and.
2911 if (Op->hasOneUse()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002912 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00002913 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00002914 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2915 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002916 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00002917 // Make the argument unsigned.
2918 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00002919 ShVal = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00002920 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00002921 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00002922 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002923 }
Chris Lattner2da29172003-09-19 19:05:02 +00002924 }
2925 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002926 }
2927 return 0;
2928}
2929
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002930
Chris Lattner6862fbd2004-09-29 17:40:11 +00002931/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2932/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00002933/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2934/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00002935/// insert new instructions.
2936Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00002937 bool isSigned, bool Inside,
2938 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002939 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00002940 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00002941 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002942
Chris Lattner6862fbd2004-09-29 17:40:11 +00002943 if (Inside) {
2944 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00002945 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002946
Reid Spencer266e42b2006-12-23 06:05:41 +00002947 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00002948 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002949 ICmpInst::Predicate pred = (isSigned ?
2950 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2951 return new ICmpInst(pred, V, Hi);
2952 }
2953
2954 // Emit V-Lo <u Hi-Lo
2955 Constant *NegLo = ConstantExpr::getNeg(Lo);
2956 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00002957 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00002958 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2959 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002960 }
2961
2962 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00002963 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002964
Reid Spencer266e42b2006-12-23 06:05:41 +00002965 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattner6862fbd2004-09-29 17:40:11 +00002966 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00002967 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002968 ICmpInst::Predicate pred = (isSigned ?
2969 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
2970 return new ICmpInst(pred, V, Hi);
2971 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00002972
Reid Spencer266e42b2006-12-23 06:05:41 +00002973 // Emit V-Lo > Hi-1-Lo
2974 Constant *NegLo = ConstantExpr::getNeg(Lo);
2975 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00002976 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00002977 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
2978 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002979}
2980
Chris Lattnerb4b25302005-09-18 07:22:02 +00002981// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2982// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2983// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2984// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00002985static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002986 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00002987 if (!isShiftedMask_64(V)) return false;
2988
2989 // look for the first zero bit after the run of ones
2990 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2991 // look for the first non-zero bit
2992 ME = 64-CountLeadingZeros_64(V);
2993 return true;
2994}
2995
2996
2997
2998/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2999/// where isSub determines whether the operator is a sub. If we can fold one of
3000/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003001///
3002/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3003/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3004/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3005///
3006/// return (A +/- B).
3007///
3008Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003009 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003010 Instruction &I) {
3011 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3012 if (!LHSI || LHSI->getNumOperands() != 2 ||
3013 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3014
3015 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3016
3017 switch (LHSI->getOpcode()) {
3018 default: return 0;
3019 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003020 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3021 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003022 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003023 break;
3024
3025 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3026 // part, we don't need any explicit masks to take them out of A. If that
3027 // is all N is, ignore it.
3028 unsigned MB, ME;
3029 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencera94d3942007-01-19 21:13:56 +00003030 uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003031 Mask >>= 64-MB+1;
3032 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003033 break;
3034 }
3035 }
Chris Lattneraf517572005-09-18 04:24:45 +00003036 return 0;
3037 case Instruction::Or:
3038 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003039 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003040 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003041 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003042 break;
3043 return 0;
3044 }
3045
3046 Instruction *New;
3047 if (isSub)
3048 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3049 else
3050 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3051 return InsertNewInstBefore(New, I);
3052}
3053
Chris Lattner113f4f42002-06-25 16:13:24 +00003054Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003055 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003056 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003057
Chris Lattner81a7a232004-10-16 18:11:37 +00003058 if (isa<UndefValue>(Op1)) // X & undef -> 0
3059 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3060
Chris Lattner86102b82005-01-01 16:22:27 +00003061 // and X, X = X
3062 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003063 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003064
Chris Lattner5b2edb12006-02-12 08:02:11 +00003065 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003066 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003067 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00003068 if (!isa<VectorType>(I.getType())) {
Reid Spencera94d3942007-01-19 21:13:56 +00003069 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner120ab032007-01-18 22:16:33 +00003070 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003071 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003072 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003073 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner120ab032007-01-18 22:16:33 +00003074 if (CP->isAllOnesValue())
3075 return ReplaceInstUsesWith(I, I.getOperand(0));
3076 }
3077 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003078
Zhou Sheng75b871f2007-01-11 12:24:14 +00003079 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003080 uint64_t AndRHSMask = AndRHS->getZExtValue();
Reid Spencera94d3942007-01-19 21:13:56 +00003081 uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003082 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003083
Chris Lattnerba1cb382003-09-19 17:17:26 +00003084 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003085 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003086 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003087 Value *Op0LHS = Op0I->getOperand(0);
3088 Value *Op0RHS = Op0I->getOperand(1);
3089 switch (Op0I->getOpcode()) {
3090 case Instruction::Xor:
3091 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003092 // If the mask is only needed on one incoming arm, push it up.
3093 if (Op0I->hasOneUse()) {
3094 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3095 // Not masking anything out for the LHS, move to RHS.
3096 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3097 Op0RHS->getName()+".masked");
3098 InsertNewInstBefore(NewRHS, I);
3099 return BinaryOperator::create(
3100 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003101 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003102 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003103 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3104 // Not masking anything out for the RHS, move to LHS.
3105 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3106 Op0LHS->getName()+".masked");
3107 InsertNewInstBefore(NewLHS, I);
3108 return BinaryOperator::create(
3109 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3110 }
3111 }
3112
Chris Lattner86102b82005-01-01 16:22:27 +00003113 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003114 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003115 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3116 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3117 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3118 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3119 return BinaryOperator::createAnd(V, AndRHS);
3120 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3121 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003122 break;
3123
3124 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003125 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3126 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3127 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3128 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3129 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003130 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003131 }
3132
Chris Lattner16464b32003-07-23 19:25:52 +00003133 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003134 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003135 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003136 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003137 // If this is an integer truncation or change from signed-to-unsigned, and
3138 // if the source is an and/or with immediate, transform it. This
3139 // frequently occurs for bitfield accesses.
3140 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003141 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003142 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003143 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003144 if (CastOp->getOpcode() == Instruction::And) {
3145 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003146 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3147 // This will fold the two constants together, which may allow
3148 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003149 Instruction *NewCast = CastInst::createTruncOrBitCast(
3150 CastOp->getOperand(0), I.getType(),
3151 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003152 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003153 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003154 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003155 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003156 return BinaryOperator::createAnd(NewCast, C3);
3157 } else if (CastOp->getOpcode() == Instruction::Or) {
3158 // Change: and (cast (or X, C1) to T), C2
3159 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003160 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003161 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3162 return ReplaceInstUsesWith(I, AndRHS);
3163 }
3164 }
Chris Lattner33217db2003-07-23 19:36:21 +00003165 }
Chris Lattner183b3362004-04-09 19:05:30 +00003166
3167 // Try to fold constant and into select arguments.
3168 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003169 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003170 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003171 if (isa<PHINode>(Op0))
3172 if (Instruction *NV = FoldOpIntoPhi(I))
3173 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003174 }
3175
Chris Lattnerbb74e222003-03-10 23:06:50 +00003176 Value *Op0NotVal = dyn_castNotVal(Op0);
3177 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003178
Chris Lattner023a4832004-06-18 06:07:51 +00003179 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3180 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3181
Misha Brukman9c003d82004-07-30 12:50:08 +00003182 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003183 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003184 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3185 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003186 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003187 return BinaryOperator::createNot(Or);
3188 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003189
3190 {
3191 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003192 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3193 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3194 return ReplaceInstUsesWith(I, Op1);
3195 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3196 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3197 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003198
3199 if (Op0->hasOneUse() &&
3200 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3201 if (A == Op1) { // (A^B)&A -> A&(A^B)
3202 I.swapOperands(); // Simplify below
3203 std::swap(Op0, Op1);
3204 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3205 cast<BinaryOperator>(Op0)->swapOperands();
3206 I.swapOperands(); // Simplify below
3207 std::swap(Op0, Op1);
3208 }
3209 }
3210 if (Op1->hasOneUse() &&
3211 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3212 if (B == Op0) { // B&(A^B) -> B&(B^A)
3213 cast<BinaryOperator>(Op1)->swapOperands();
3214 std::swap(A, B);
3215 }
3216 if (A == Op0) { // A&(A^B) -> A & ~B
3217 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3218 InsertNewInstBefore(NotB, I);
3219 return BinaryOperator::createAnd(A, NotB);
3220 }
3221 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003222 }
3223
Reid Spencer266e42b2006-12-23 06:05:41 +00003224 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3225 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3226 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003227 return R;
3228
Chris Lattner623826c2004-09-28 21:48:02 +00003229 Value *LHSVal, *RHSVal;
3230 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003231 ICmpInst::Predicate LHSCC, RHSCC;
3232 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3233 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3234 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3235 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3236 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3237 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3238 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3239 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003240 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003241 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3242 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3243 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3244 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003245 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003246 std::swap(LHS, RHS);
3247 std::swap(LHSCst, RHSCst);
3248 std::swap(LHSCC, RHSCC);
3249 }
3250
Reid Spencer266e42b2006-12-23 06:05:41 +00003251 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003252 // comparing a value against two constants and and'ing the result
3253 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003254 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3255 // (from the FoldICmpLogical check above), that the two constants
3256 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003257 assert(LHSCst != RHSCst && "Compares not folded above?");
3258
3259 switch (LHSCC) {
3260 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003261 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003262 switch (RHSCC) {
3263 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003264 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3265 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3266 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003267 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003268 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3269 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3270 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003271 return ReplaceInstUsesWith(I, LHS);
3272 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003273 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003274 switch (RHSCC) {
3275 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003276 case ICmpInst::ICMP_ULT:
3277 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3278 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3279 break; // (X != 13 & X u< 15) -> no change
3280 case ICmpInst::ICMP_SLT:
3281 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3282 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3283 break; // (X != 13 & X s< 15) -> no change
3284 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3285 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3286 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003287 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003288 case ICmpInst::ICMP_NE:
3289 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003290 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3291 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3292 LHSVal->getName()+".off");
3293 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00003294 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3295 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00003296 }
3297 break; // (X != 13 & X != 15) -> no change
3298 }
3299 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003300 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003301 switch (RHSCC) {
3302 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003303 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3304 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003305 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003306 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3307 break;
3308 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3309 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003310 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003311 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3312 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003313 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003314 break;
3315 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003316 switch (RHSCC) {
3317 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003318 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3319 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003320 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003321 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3322 break;
3323 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3324 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003325 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003326 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3327 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003328 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003329 break;
3330 case ICmpInst::ICMP_UGT:
3331 switch (RHSCC) {
3332 default: assert(0 && "Unknown integer condition code!");
3333 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3334 return ReplaceInstUsesWith(I, LHS);
3335 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3336 return ReplaceInstUsesWith(I, RHS);
3337 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3338 break;
3339 case ICmpInst::ICMP_NE:
3340 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3341 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3342 break; // (X u> 13 & X != 15) -> no change
3343 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3344 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3345 true, I);
3346 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3347 break;
3348 }
3349 break;
3350 case ICmpInst::ICMP_SGT:
3351 switch (RHSCC) {
3352 default: assert(0 && "Unknown integer condition code!");
3353 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3354 return ReplaceInstUsesWith(I, LHS);
3355 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3356 return ReplaceInstUsesWith(I, RHS);
3357 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3358 break;
3359 case ICmpInst::ICMP_NE:
3360 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3361 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3362 break; // (X s> 13 & X != 15) -> no change
3363 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3364 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3365 true, I);
3366 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3367 break;
3368 }
3369 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003370 }
3371 }
3372 }
3373
Chris Lattner3af10532006-05-05 06:39:07 +00003374 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003375 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3376 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3377 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3378 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003379 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003380 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003381 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3382 I.getType(), TD) &&
3383 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3384 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003385 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3386 Op1C->getOperand(0),
3387 I.getName());
3388 InsertNewInstBefore(NewOp, I);
3389 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3390 }
Chris Lattner3af10532006-05-05 06:39:07 +00003391 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003392
3393 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003394 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3395 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3396 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003397 SI0->getOperand(1) == SI1->getOperand(1) &&
3398 (SI0->hasOneUse() || SI1->hasOneUse())) {
3399 Instruction *NewOp =
3400 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3401 SI1->getOperand(0),
3402 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003403 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3404 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003405 }
Chris Lattner3af10532006-05-05 06:39:07 +00003406 }
3407
Chris Lattner113f4f42002-06-25 16:13:24 +00003408 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003409}
3410
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003411/// CollectBSwapParts - Look to see if the specified value defines a single byte
3412/// in the result. If it does, and if the specified byte hasn't been filled in
3413/// yet, fill it in and return false.
3414static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3415 Instruction *I = dyn_cast<Instruction>(V);
3416 if (I == 0) return true;
3417
3418 // If this is an or instruction, it is an inner node of the bswap.
3419 if (I->getOpcode() == Instruction::Or)
3420 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3421 CollectBSwapParts(I->getOperand(1), ByteValues);
3422
3423 // If this is a shift by a constant int, and it is "24", then its operand
3424 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00003425 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003426 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003427 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003428 8*(ByteValues.size()-1))
3429 return true;
3430
3431 unsigned DestNo;
3432 if (I->getOpcode() == Instruction::Shl) {
3433 // X << 24 defines the top byte with the lowest of the input bytes.
3434 DestNo = ByteValues.size()-1;
3435 } else {
3436 // X >>u 24 defines the low byte with the highest of the input bytes.
3437 DestNo = 0;
3438 }
3439
3440 // If the destination byte value is already defined, the values are or'd
3441 // together, which isn't a bswap (unless it's an or of the same bits).
3442 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3443 return true;
3444 ByteValues[DestNo] = I->getOperand(0);
3445 return false;
3446 }
3447
3448 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3449 // don't have this.
3450 Value *Shift = 0, *ShiftLHS = 0;
3451 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3452 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3453 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3454 return true;
3455 Instruction *SI = cast<Instruction>(Shift);
3456
3457 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003458 if (ShiftAmt->getZExtValue() & 7 ||
3459 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003460 return true;
3461
3462 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3463 unsigned DestByte;
3464 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003465 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003466 break;
3467 // Unknown mask for bswap.
3468 if (DestByte == ByteValues.size()) return true;
3469
Reid Spencere0fc4df2006-10-20 07:07:24 +00003470 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003471 unsigned SrcByte;
3472 if (SI->getOpcode() == Instruction::Shl)
3473 SrcByte = DestByte - ShiftBytes;
3474 else
3475 SrcByte = DestByte + ShiftBytes;
3476
3477 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3478 if (SrcByte != ByteValues.size()-DestByte-1)
3479 return true;
3480
3481 // If the destination byte value is already defined, the values are or'd
3482 // together, which isn't a bswap (unless it's an or of the same bits).
3483 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3484 return true;
3485 ByteValues[DestByte] = SI->getOperand(0);
3486 return false;
3487}
3488
3489/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3490/// If so, insert the new bswap intrinsic and return it.
3491Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Reid Spencer2341c222007-02-02 02:16:23 +00003492 // We cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00003493 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003494 return 0;
3495
3496 /// ByteValues - For each byte of the result, we keep track of which value
3497 /// defines each byte.
3498 std::vector<Value*> ByteValues;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00003499 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003500
3501 // Try to find all the pieces corresponding to the bswap.
3502 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3503 CollectBSwapParts(I.getOperand(1), ByteValues))
3504 return 0;
3505
3506 // Check to see if all of the bytes come from the same value.
3507 Value *V = ByteValues[0];
3508 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3509
3510 // Check to make sure that all of the bytes come from the same value.
3511 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3512 if (ByteValues[i] != V)
3513 return 0;
3514
3515 // If they do then *success* we can turn this into a bswap. Figure out what
3516 // bswap to make it into.
3517 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003518 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00003519 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003520 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00003521 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003522 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00003523 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003524 FnName = "llvm.bswap.i64";
3525 else
3526 assert(0 && "Unknown integer type!");
Chris Lattnerfbc524f2007-01-07 06:58:05 +00003527 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003528 return new CallInst(F, V);
3529}
3530
3531
Chris Lattner113f4f42002-06-25 16:13:24 +00003532Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003533 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003534 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003535
Chris Lattner81a7a232004-10-16 18:11:37 +00003536 if (isa<UndefValue>(Op1))
3537 return ReplaceInstUsesWith(I, // X | undef -> -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003538 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003539
Chris Lattner5b2edb12006-02-12 08:02:11 +00003540 // or X, X = X
3541 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003542 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003543
Chris Lattner5b2edb12006-02-12 08:02:11 +00003544 // See if we can simplify any instructions used by the instruction whose sole
3545 // purpose is to compute bits we don't care about.
3546 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00003547 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00003548 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003549 KnownZero, KnownOne))
3550 return &I;
3551
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003552 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003553 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003554 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003555 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3556 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003557 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003558 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003559 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003560 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3561 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003562
Chris Lattnerd4252a72004-07-30 07:50:03 +00003563 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3564 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003565 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003566 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003567 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003568 return BinaryOperator::createXor(Or,
3569 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003570 }
Chris Lattner183b3362004-04-09 19:05:30 +00003571
3572 // Try to fold constant and into select arguments.
3573 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003574 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003575 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003576 if (isa<PHINode>(Op0))
3577 if (Instruction *NV = FoldOpIntoPhi(I))
3578 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003579 }
3580
Chris Lattner330628a2006-01-06 17:59:59 +00003581 Value *A = 0, *B = 0;
3582 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003583
3584 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3585 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3586 return ReplaceInstUsesWith(I, Op1);
3587 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3588 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3589 return ReplaceInstUsesWith(I, Op0);
3590
Chris Lattnerb7845d62006-07-10 20:25:24 +00003591 // (A | B) | C and A | (B | C) -> bswap if possible.
3592 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003593 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003594 match(Op1, m_Or(m_Value(), m_Value())) ||
3595 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3596 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003597 if (Instruction *BSwap = MatchBSwap(I))
3598 return BSwap;
3599 }
3600
Chris Lattnerb62f5082005-05-09 04:58:36 +00003601 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3602 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003603 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003604 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3605 InsertNewInstBefore(NOr, I);
3606 NOr->takeName(Op0);
3607 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003608 }
3609
3610 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3611 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003612 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003613 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3614 InsertNewInstBefore(NOr, I);
3615 NOr->takeName(Op0);
3616 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003617 }
3618
Chris Lattner15212982005-09-18 03:42:07 +00003619 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003620 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003621 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3622
3623 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3624 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3625
3626
Chris Lattner01f56c62005-09-18 06:02:59 +00003627 // If we have: ((V + N) & C1) | (V & C2)
3628 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3629 // replace with V+N.
3630 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003631 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003632 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003633 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3634 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003635 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003636 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003637 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003638 return ReplaceInstUsesWith(I, A);
3639 }
3640 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003641 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003642 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3643 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003644 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003645 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003646 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003647 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003648 }
3649 }
3650 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003651
3652 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003653 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3654 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3655 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003656 SI0->getOperand(1) == SI1->getOperand(1) &&
3657 (SI0->hasOneUse() || SI1->hasOneUse())) {
3658 Instruction *NewOp =
3659 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3660 SI1->getOperand(0),
3661 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003662 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3663 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003664 }
3665 }
Chris Lattner812aab72003-08-12 19:11:07 +00003666
Chris Lattnerd4252a72004-07-30 07:50:03 +00003667 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3668 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003669 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003670 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003671 } else {
3672 A = 0;
3673 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003674 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003675 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3676 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003677 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003678 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003679
Misha Brukman9c003d82004-07-30 12:50:08 +00003680 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003681 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3682 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3683 I.getName()+".demorgan"), I);
3684 return BinaryOperator::createNot(And);
3685 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003686 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003687
Reid Spencer266e42b2006-12-23 06:05:41 +00003688 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3689 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3690 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003691 return R;
3692
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003693 Value *LHSVal, *RHSVal;
3694 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003695 ICmpInst::Predicate LHSCC, RHSCC;
3696 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3697 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3698 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3699 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3700 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3701 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3702 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3703 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003704 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003705 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3706 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3707 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3708 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003709 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003710 std::swap(LHS, RHS);
3711 std::swap(LHSCst, RHSCst);
3712 std::swap(LHSCC, RHSCC);
3713 }
3714
Reid Spencer266e42b2006-12-23 06:05:41 +00003715 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003716 // comparing a value against two constants and or'ing the result
3717 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003718 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3719 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003720 // equal.
3721 assert(LHSCst != RHSCst && "Compares not folded above?");
3722
3723 switch (LHSCC) {
3724 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003725 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003726 switch (RHSCC) {
3727 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003728 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003729 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3730 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3731 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3732 LHSVal->getName()+".off");
3733 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003734 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003735 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003736 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003737 break; // (X == 13 | X == 15) -> no change
3738 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3739 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003740 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003741 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3742 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3743 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003744 return ReplaceInstUsesWith(I, RHS);
3745 }
3746 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003747 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003748 switch (RHSCC) {
3749 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003750 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3751 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3752 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003753 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003754 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3755 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3756 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003757 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003758 }
3759 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003760 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003761 switch (RHSCC) {
3762 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003763 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003764 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003765 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3766 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3767 false, I);
3768 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3769 break;
3770 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3771 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003772 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003773 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3774 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003775 }
3776 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003777 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003778 switch (RHSCC) {
3779 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003780 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3781 break;
3782 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3783 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3784 false, I);
3785 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3786 break;
3787 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3788 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3789 return ReplaceInstUsesWith(I, RHS);
3790 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3791 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003792 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003793 break;
3794 case ICmpInst::ICMP_UGT:
3795 switch (RHSCC) {
3796 default: assert(0 && "Unknown integer condition code!");
3797 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3798 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3799 return ReplaceInstUsesWith(I, LHS);
3800 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3801 break;
3802 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3803 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003804 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003805 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3806 break;
3807 }
3808 break;
3809 case ICmpInst::ICMP_SGT:
3810 switch (RHSCC) {
3811 default: assert(0 && "Unknown integer condition code!");
3812 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3813 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3814 return ReplaceInstUsesWith(I, LHS);
3815 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3816 break;
3817 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3818 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003819 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003820 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3821 break;
3822 }
3823 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003824 }
3825 }
3826 }
Chris Lattner3af10532006-05-05 06:39:07 +00003827
3828 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003829 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003830 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003831 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3832 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003833 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003834 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003835 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3836 I.getType(), TD) &&
3837 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3838 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003839 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3840 Op1C->getOperand(0),
3841 I.getName());
3842 InsertNewInstBefore(NewOp, I);
3843 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3844 }
Chris Lattner3af10532006-05-05 06:39:07 +00003845 }
Chris Lattner3af10532006-05-05 06:39:07 +00003846
Chris Lattner15212982005-09-18 03:42:07 +00003847
Chris Lattner113f4f42002-06-25 16:13:24 +00003848 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003849}
3850
Chris Lattnerc2076352004-02-16 01:20:27 +00003851// XorSelf - Implements: X ^ X --> 0
3852struct XorSelf {
3853 Value *RHS;
3854 XorSelf(Value *rhs) : RHS(rhs) {}
3855 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3856 Instruction *apply(BinaryOperator &Xor) const {
3857 return &Xor;
3858 }
3859};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003860
3861
Chris Lattner113f4f42002-06-25 16:13:24 +00003862Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003863 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003864 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003865
Chris Lattner81a7a232004-10-16 18:11:37 +00003866 if (isa<UndefValue>(Op1))
3867 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3868
Chris Lattnerc2076352004-02-16 01:20:27 +00003869 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3870 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3871 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003872 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003873 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003874
3875 // See if we can simplify any instructions used by the instruction whose sole
3876 // purpose is to compute bits we don't care about.
3877 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00003878 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00003879 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003880 KnownZero, KnownOne))
3881 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003882
Zhou Sheng75b871f2007-01-11 12:24:14 +00003883 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003884 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3885 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00003886 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00003887 return new ICmpInst(ICI->getInversePredicate(),
3888 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003889
Reid Spencer266e42b2006-12-23 06:05:41 +00003890 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00003891 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003892 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3893 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003894 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3895 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003896 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003897 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003898 }
Chris Lattner023a4832004-06-18 06:07:51 +00003899
3900 // ~(~X & Y) --> (X | ~Y)
3901 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3902 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3903 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3904 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003905 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003906 Op0I->getOperand(1)->getName()+".not");
3907 InsertNewInstBefore(NotY, I);
3908 return BinaryOperator::createOr(Op0NotVal, NotY);
3909 }
3910 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003911
Chris Lattner97638592003-07-23 21:37:07 +00003912 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003913 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003914 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003915 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003916 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3917 return BinaryOperator::createSub(
3918 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003919 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003920 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003921 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003922 } else if (Op0I->getOpcode() == Instruction::Or) {
3923 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3924 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3925 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3926 // Anything in both C1 and C2 is known to be zero, remove it from
3927 // NewRHS.
3928 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3929 NewRHS = ConstantExpr::getAnd(NewRHS,
3930 ConstantExpr::getNot(CommonBits));
3931 WorkList.push_back(Op0I);
3932 I.setOperand(0, Op0I->getOperand(0));
3933 I.setOperand(1, NewRHS);
3934 return &I;
3935 }
Chris Lattner97638592003-07-23 21:37:07 +00003936 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003937 }
Chris Lattner183b3362004-04-09 19:05:30 +00003938
3939 // Try to fold constant and into select arguments.
3940 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003941 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003942 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003943 if (isa<PHINode>(Op0))
3944 if (Instruction *NV = FoldOpIntoPhi(I))
3945 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003946 }
3947
Chris Lattnerbb74e222003-03-10 23:06:50 +00003948 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003949 if (X == Op1)
3950 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003951 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003952
Chris Lattnerbb74e222003-03-10 23:06:50 +00003953 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003954 if (X == Op0)
3955 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003956 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003957
Chris Lattnerdcd07922006-04-01 08:03:55 +00003958 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003959 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003960 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003961 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003962 I.swapOperands();
3963 std::swap(Op0, Op1);
3964 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003965 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003966 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003967 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003968 } else if (Op1I->getOpcode() == Instruction::Xor) {
3969 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3970 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3971 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3972 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003973 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3974 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3975 Op1I->swapOperands();
3976 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3977 I.swapOperands(); // Simplified below.
3978 std::swap(Op0, Op1);
3979 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003980 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003981
Chris Lattnerdcd07922006-04-01 08:03:55 +00003982 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003983 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003984 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003985 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003986 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003987 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3988 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003989 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003990 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003991 } else if (Op0I->getOpcode() == Instruction::Xor) {
3992 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3993 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3994 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3995 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003996 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3997 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3998 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003999 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
4000 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00004001 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4002 InsertNewInstBefore(N, I);
4003 return BinaryOperator::createAnd(N, Op1);
4004 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004005 }
4006
Reid Spencer266e42b2006-12-23 06:05:41 +00004007 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4008 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4009 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004010 return R;
4011
Chris Lattner3af10532006-05-05 06:39:07 +00004012 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004013 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004014 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004015 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4016 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004017 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004018 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004019 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4020 I.getType(), TD) &&
4021 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4022 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004023 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4024 Op1C->getOperand(0),
4025 I.getName());
4026 InsertNewInstBefore(NewOp, I);
4027 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4028 }
Chris Lattner3af10532006-05-05 06:39:07 +00004029 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004030
4031 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004032 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4033 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4034 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004035 SI0->getOperand(1) == SI1->getOperand(1) &&
4036 (SI0->hasOneUse() || SI1->hasOneUse())) {
4037 Instruction *NewOp =
4038 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4039 SI1->getOperand(0),
4040 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00004041 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4042 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004043 }
4044 }
Chris Lattner3af10532006-05-05 06:39:07 +00004045
Chris Lattner113f4f42002-06-25 16:13:24 +00004046 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004047}
4048
Chris Lattner6862fbd2004-09-29 17:40:11 +00004049static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004050 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004051}
4052
4053/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4054/// overflowed for this type.
4055static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4056 ConstantInt *In2) {
4057 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4058
Reid Spencerc635f472006-12-31 05:48:39 +00004059 return cast<ConstantInt>(Result)->getZExtValue() <
4060 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004061}
4062
Chris Lattner0798af32005-01-13 20:14:25 +00004063/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4064/// code necessary to compute the offset from the base pointer (without adding
4065/// in the base pointer). Return the result as a signed integer of intptr size.
4066static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4067 TargetData &TD = IC.getTargetData();
4068 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004069 const Type *IntPtrTy = TD.getIntPtrType();
4070 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004071
4072 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004073 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004074
Chris Lattner0798af32005-01-13 20:14:25 +00004075 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4076 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004077 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004078 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004079 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4080 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004081 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004082 Scale = ConstantExpr::getMul(OpC, Scale);
4083 if (Constant *RC = dyn_cast<Constant>(Result))
4084 Result = ConstantExpr::getAdd(RC, Scale);
4085 else {
4086 // Emit an add instruction.
4087 Result = IC.InsertNewInstBefore(
4088 BinaryOperator::createAdd(Result, Scale,
4089 GEP->getName()+".offs"), I);
4090 }
4091 }
4092 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004093 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004094 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004095 Op->getName()+".c"), I);
4096 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004097 // We'll let instcombine(mul) convert this to a shl if possible.
4098 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4099 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004100
4101 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004102 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004103 GEP->getName()+".offs"), I);
4104 }
4105 }
4106 return Result;
4107}
4108
Reid Spencer266e42b2006-12-23 06:05:41 +00004109/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004110/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004111Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4112 ICmpInst::Predicate Cond,
4113 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004114 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004115
4116 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4117 if (isa<PointerType>(CI->getOperand(0)->getType()))
4118 RHS = CI->getOperand(0);
4119
Chris Lattner0798af32005-01-13 20:14:25 +00004120 Value *PtrBase = GEPLHS->getOperand(0);
4121 if (PtrBase == RHS) {
4122 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004123 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4124 // each index is zero or not.
4125 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004126 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004127 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4128 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004129 bool EmitIt = true;
4130 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4131 if (isa<UndefValue>(C)) // undef index -> undef.
4132 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4133 if (C->isNullValue())
4134 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004135 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4136 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004137 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004138 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004139 ConstantInt::get(Type::Int1Ty,
4140 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004141 }
4142
4143 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004144 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004145 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004146 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4147 if (InVal == 0)
4148 InVal = Comp;
4149 else {
4150 InVal = InsertNewInstBefore(InVal, I);
4151 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004152 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004153 InVal = BinaryOperator::createOr(InVal, Comp);
4154 else // True if all are equal
4155 InVal = BinaryOperator::createAnd(InVal, Comp);
4156 }
4157 }
4158 }
4159
4160 if (InVal)
4161 return InVal;
4162 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004163 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004164 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4165 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004166 }
Chris Lattner0798af32005-01-13 20:14:25 +00004167
Reid Spencer266e42b2006-12-23 06:05:41 +00004168 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004169 // the result to fold to a constant!
4170 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4171 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4172 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004173 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4174 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004175 }
4176 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004177 // If the base pointers are different, but the indices are the same, just
4178 // compare the base pointer.
4179 if (PtrBase != GEPRHS->getOperand(0)) {
4180 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004181 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004182 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004183 if (IndicesTheSame)
4184 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4185 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4186 IndicesTheSame = false;
4187 break;
4188 }
4189
4190 // If all indices are the same, just compare the base pointers.
4191 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004192 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4193 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004194
4195 // Otherwise, the base pointers are different and the indices are
4196 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004197 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004198 }
Chris Lattner0798af32005-01-13 20:14:25 +00004199
Chris Lattner81e84172005-01-13 22:25:21 +00004200 // If one of the GEPs has all zero indices, recurse.
4201 bool AllZeros = true;
4202 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4203 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4204 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4205 AllZeros = false;
4206 break;
4207 }
4208 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004209 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4210 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004211
4212 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004213 AllZeros = true;
4214 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4215 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4216 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4217 AllZeros = false;
4218 break;
4219 }
4220 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004221 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004222
Chris Lattner4fa89822005-01-14 00:20:05 +00004223 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4224 // If the GEPs only differ by one index, compare it.
4225 unsigned NumDifferences = 0; // Keep track of # differences.
4226 unsigned DiffOperand = 0; // The operand that differs.
4227 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4228 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004229 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4230 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004231 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004232 NumDifferences = 2;
4233 break;
4234 } else {
4235 if (NumDifferences++) break;
4236 DiffOperand = i;
4237 }
4238 }
4239
4240 if (NumDifferences == 0) // SAME GEP?
4241 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004242 ConstantInt::get(Type::Int1Ty,
4243 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004244 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004245 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4246 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004247 // Make sure we do a signed comparison here.
4248 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004249 }
4250 }
4251
Reid Spencer266e42b2006-12-23 06:05:41 +00004252 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004253 // the result to fold to a constant!
4254 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4255 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4256 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4257 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4258 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004259 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004260 }
4261 }
4262 return 0;
4263}
4264
Reid Spencer266e42b2006-12-23 06:05:41 +00004265Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4266 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004267 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004268
Chris Lattner6ee923f2007-01-14 19:42:17 +00004269 // Fold trivial predicates.
4270 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4271 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4272 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4273 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4274
4275 // Simplify 'fcmp pred X, X'
4276 if (Op0 == Op1) {
4277 switch (I.getPredicate()) {
4278 default: assert(0 && "Unknown predicate!");
4279 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4280 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4281 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4282 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4283 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4284 case FCmpInst::FCMP_OLT: // True if ordered and less than
4285 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4286 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4287
4288 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4289 case FCmpInst::FCMP_ULT: // True if unordered or less than
4290 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4291 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4292 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4293 I.setPredicate(FCmpInst::FCMP_UNO);
4294 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4295 return &I;
4296
4297 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4298 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4299 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4300 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4301 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4302 I.setPredicate(FCmpInst::FCMP_ORD);
4303 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4304 return &I;
4305 }
4306 }
4307
Reid Spencer266e42b2006-12-23 06:05:41 +00004308 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004309 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004310
Reid Spencer266e42b2006-12-23 06:05:41 +00004311 // Handle fcmp with constant RHS
4312 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4313 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4314 switch (LHSI->getOpcode()) {
4315 case Instruction::PHI:
4316 if (Instruction *NV = FoldOpIntoPhi(I))
4317 return NV;
4318 break;
4319 case Instruction::Select:
4320 // If either operand of the select is a constant, we can fold the
4321 // comparison into the select arms, which will cause one to be
4322 // constant folded and the select turned into a bitwise or.
4323 Value *Op1 = 0, *Op2 = 0;
4324 if (LHSI->hasOneUse()) {
4325 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4326 // Fold the known value into the constant operand.
4327 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4328 // Insert a new FCmp of the other select operand.
4329 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4330 LHSI->getOperand(2), RHSC,
4331 I.getName()), I);
4332 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4333 // Fold the known value into the constant operand.
4334 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4335 // Insert a new FCmp of the other select operand.
4336 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4337 LHSI->getOperand(1), RHSC,
4338 I.getName()), I);
4339 }
4340 }
4341
4342 if (Op1)
4343 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4344 break;
4345 }
4346 }
4347
4348 return Changed ? &I : 0;
4349}
4350
4351Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4352 bool Changed = SimplifyCompare(I);
4353 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4354 const Type *Ty = Op0->getType();
4355
4356 // icmp X, X
4357 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004358 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4359 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004360
4361 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004362 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004363
4364 // icmp of GlobalValues can never equal each other as long as they aren't
4365 // external weak linkage type.
4366 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4367 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4368 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004369 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4370 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004371
4372 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004373 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004374 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4375 isa<ConstantPointerNull>(Op0)) &&
4376 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004377 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004378 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4379 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004380
Reid Spencer266e42b2006-12-23 06:05:41 +00004381 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004382 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004383 switch (I.getPredicate()) {
4384 default: assert(0 && "Invalid icmp instruction!");
4385 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004386 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004387 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004388 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004389 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004390 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004391 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004392
Reid Spencer266e42b2006-12-23 06:05:41 +00004393 case ICmpInst::ICMP_UGT:
4394 case ICmpInst::ICMP_SGT:
4395 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004396 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004397 case ICmpInst::ICMP_ULT:
4398 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004399 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4400 InsertNewInstBefore(Not, I);
4401 return BinaryOperator::createAnd(Not, Op1);
4402 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004403 case ICmpInst::ICMP_UGE:
4404 case ICmpInst::ICMP_SGE:
4405 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004406 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004407 case ICmpInst::ICMP_ULE:
4408 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004409 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4410 InsertNewInstBefore(Not, I);
4411 return BinaryOperator::createOr(Not, Op1);
4412 }
4413 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004414 }
4415
Chris Lattner2dd01742004-06-09 04:24:29 +00004416 // See if we are doing a comparison between a constant and an instruction that
4417 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004418 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004419 switch (I.getPredicate()) {
4420 default: break;
4421 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4422 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004423 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004424 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4425 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4426 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4427 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4428 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004429
Reid Spencer266e42b2006-12-23 06:05:41 +00004430 case ICmpInst::ICMP_SLT:
4431 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004432 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004433 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4434 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4435 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4436 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4437 break;
4438
4439 case ICmpInst::ICMP_UGT:
4440 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004441 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004442 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4443 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4444 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4445 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4446 break;
4447
4448 case ICmpInst::ICMP_SGT:
4449 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004450 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004451 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4452 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4453 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4454 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4455 break;
4456
4457 case ICmpInst::ICMP_ULE:
4458 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004459 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004460 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4461 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4462 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4463 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4464 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004465
Reid Spencer266e42b2006-12-23 06:05:41 +00004466 case ICmpInst::ICMP_SLE:
4467 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004468 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004469 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4470 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4471 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4472 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4473 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004474
Reid Spencer266e42b2006-12-23 06:05:41 +00004475 case ICmpInst::ICMP_UGE:
4476 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004477 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004478 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4479 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4480 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4481 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4482 break;
4483
4484 case ICmpInst::ICMP_SGE:
4485 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004486 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004487 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4488 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4489 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4490 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4491 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004492 }
4493
Reid Spencer266e42b2006-12-23 06:05:41 +00004494 // If we still have a icmp le or icmp ge instruction, turn it into the
4495 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004496 // already been handled above, this requires little checking.
4497 //
Reid Spencer266e42b2006-12-23 06:05:41 +00004498 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4499 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4500 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4501 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4502 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4503 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4504 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4505 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00004506
4507 // See if we can fold the comparison based on bits known to be zero or one
4508 // in the input.
4509 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00004510 if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
Chris Lattneree0f2802006-02-12 02:07:56 +00004511 KnownZero, KnownOne, 0))
4512 return &I;
4513
4514 // Given the known and unknown bits, compute a range that the LHS could be
4515 // in.
4516 if (KnownOne | KnownZero) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004517 // Compute the Min, Max and RHS values based on the known bits. For the
4518 // EQ and NE we use unsigned values.
Reid Spencer910f23f2006-12-23 19:17:57 +00004519 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4520 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00004521 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4522 SRHSVal = CI->getSExtValue();
4523 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4524 SMax);
4525 } else {
4526 URHSVal = CI->getZExtValue();
4527 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4528 UMax);
4529 }
4530 switch (I.getPredicate()) { // LE/GE have been folded already.
4531 default: assert(0 && "Unknown icmp opcode!");
4532 case ICmpInst::ICMP_EQ:
4533 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004534 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004535 break;
4536 case ICmpInst::ICMP_NE:
4537 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004538 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004539 break;
4540 case ICmpInst::ICMP_ULT:
4541 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004542 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004543 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004544 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004545 break;
4546 case ICmpInst::ICMP_UGT:
4547 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004548 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004549 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004550 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004551 break;
4552 case ICmpInst::ICMP_SLT:
4553 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004554 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004555 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004556 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004557 break;
4558 case ICmpInst::ICMP_SGT:
4559 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004560 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004561 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004562 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004563 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004564 }
4565 }
4566
Reid Spencer266e42b2006-12-23 06:05:41 +00004567 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004568 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004569 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004570 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004571 switch (LHSI->getOpcode()) {
4572 case Instruction::And:
4573 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4574 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004575 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4576
Reid Spencer266e42b2006-12-23 06:05:41 +00004577 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004578 // and/compare to be the input width without changing the value
4579 // produced, eliminating a cast.
4580 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4581 // We can do this transformation if either the AND constant does not
4582 // have its sign bit set or if it is an equality comparison.
4583 // Extending a relational comparison when we're checking the sign
4584 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004585 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004586 (I.isEquality() ||
4587 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4588 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4589 ConstantInt *NewCST;
4590 ConstantInt *NewCI;
Reid Spencerc635f472006-12-31 05:48:39 +00004591 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4592 AndCST->getZExtValue());
4593 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4594 CI->getZExtValue());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004595 Instruction *NewAnd =
4596 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4597 LHSI->getName());
4598 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004599 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004600 }
4601 }
4602
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004603 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4604 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4605 // happens a LOT in code produced by the C front-end, for bitfield
4606 // access.
Reid Spencer2341c222007-02-02 02:16:23 +00004607 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4608 if (Shift && !Shift->isShift())
4609 Shift = 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004610
Reid Spencere0fc4df2006-10-20 07:07:24 +00004611 ConstantInt *ShAmt;
4612 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004613 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4614 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004615
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004616 // We can fold this as long as we can't shift unknown bits
4617 // into the mask. This can only happen with signed shift
4618 // rights, as they sign-extend.
4619 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004620 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004621 if (!CanFold) {
4622 // To test for the bad case of the signed shr, see if any
4623 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004624 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004625 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4626
Reid Spencer2341c222007-02-02 02:16:23 +00004627 Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004628 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004629 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4630 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004631 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4632 CanFold = true;
4633 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004634
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004635 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004636 Constant *NewCst;
4637 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004638 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004639 else
4640 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004641
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004642 // Check to see if we are shifting out any of the bits being
4643 // compared.
4644 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4645 // If we shifted bits out, the fold is not going to work out.
4646 // As a special case, check to see if this means that the
4647 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004648 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004649 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004650 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004651 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004652 } else {
4653 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004654 Constant *NewAndCST;
4655 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004656 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004657 else
4658 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4659 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00004660 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004661 WorkList.push_back(Shift); // Shift is dead.
4662 AddUsesToWorkList(I);
4663 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004664 }
4665 }
Chris Lattner35167c32004-06-09 07:59:58 +00004666 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004667
4668 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4669 // preferable because it allows the C<<Y expression to be hoisted out
4670 // of a loop if Y is invariant and X is not.
4671 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004672 I.isEquality() && !Shift->isArithmeticShift() &&
4673 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004674 // Compute C << Y.
4675 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004676 if (Shift->getOpcode() == Instruction::LShr) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00004677 NS = BinaryOperator::createShl(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004678 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004679 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004680 // Insert a logical shift.
Reid Spencer0d5f9232007-02-02 14:08:20 +00004681 NS = BinaryOperator::createLShr(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004682 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004683 }
4684 InsertNewInstBefore(cast<Instruction>(NS), I);
4685
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004686 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00004687 Instruction *NewAnd = BinaryOperator::createAnd(
4688 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004689 InsertNewInstBefore(NewAnd, I);
4690
4691 I.setOperand(0, NewAnd);
4692 return &I;
4693 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004694 }
4695 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004696
Reid Spencer266e42b2006-12-23 06:05:41 +00004697 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004698 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004699 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004700 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4701
4702 // Check that the shift amount is in range. If not, don't perform
4703 // undefined shifts. When the shift is visited it will be
4704 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004705 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004706 break;
4707
Chris Lattner272d5ca2004-09-28 18:22:15 +00004708 // If we are comparing against bits always shifted out, the
4709 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004710 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004711 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004712 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004713 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004714 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004715 return ReplaceInstUsesWith(I, Cst);
4716 }
4717
4718 if (LHSI->hasOneUse()) {
4719 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004720 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004721 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc635f472006-12-31 05:48:39 +00004722 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004723
Chris Lattner272d5ca2004-09-28 18:22:15 +00004724 Instruction *AndI =
4725 BinaryOperator::createAnd(LHSI->getOperand(0),
4726 Mask, LHSI->getName()+".mask");
4727 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004728 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004729 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004730 }
4731 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004732 }
4733 break;
4734
Reid Spencer266e42b2006-12-23 06:05:41 +00004735 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004736 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004737 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004738 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004739 // Check that the shift amount is in range. If not, don't perform
4740 // undefined shifts. When the shift is visited it will be
4741 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004742 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004743 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004744 break;
4745
Chris Lattner1023b872004-09-27 16:18:50 +00004746 // If we are comparing against bits always shifted out, the
4747 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004748 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00004749 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00004750 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4751 ShAmt);
4752 else
4753 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4754 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004755
Chris Lattner1023b872004-09-27 16:18:50 +00004756 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004757 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004758 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004759 return ReplaceInstUsesWith(I, Cst);
4760 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004761
Chris Lattner1023b872004-09-27 16:18:50 +00004762 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004763 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004764
Chris Lattner1023b872004-09-27 16:18:50 +00004765 // Otherwise strength reduce the shift into an and.
4766 uint64_t Val = ~0ULL; // All ones.
4767 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc635f472006-12-31 05:48:39 +00004768 Val &= ~0ULL >> (64-TypeBits);
4769 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004770
Chris Lattner1023b872004-09-27 16:18:50 +00004771 Instruction *AndI =
4772 BinaryOperator::createAnd(LHSI->getOperand(0),
4773 Mask, LHSI->getName()+".mask");
4774 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004775 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004776 ConstantExpr::getShl(CI, ShAmt));
4777 }
Chris Lattner1023b872004-09-27 16:18:50 +00004778 }
4779 }
4780 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004781
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004782 case Instruction::SDiv:
4783 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004784 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004785 // Fold this div into the comparison, producing a range check.
4786 // Determine, based on the divide type, what the range is being
4787 // checked. If there is an overflow on the low or high side, remember
4788 // it, otherwise compute the range [low, hi) bounding the new value.
4789 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004790 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004791 // FIXME: If the operand types don't match the type of the divide
4792 // then don't attempt this transform. The code below doesn't have the
4793 // logic to deal with a signed divide and an unsigned compare (and
4794 // vice versa). This is because (x /s C1) <s C2 produces different
4795 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4796 // (x /u C1) <u C2. Simply casting the operands and result won't
4797 // work. :( The if statement below tests that condition and bails
4798 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004799 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4800 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004801 break;
4802
4803 // Initialize the variables that will indicate the nature of the
4804 // range check.
4805 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004806 ConstantInt *LoBound = 0, *HiBound = 0;
4807
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004808 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4809 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4810 // C2 (CI). By solving for X we can turn this into a range check
4811 // instead of computing a divide.
4812 ConstantInt *Prod =
4813 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004814
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004815 // Determine if the product overflows by seeing if the product is
4816 // not equal to the divide. Make sure we do the same kind of divide
4817 // as in the LHS instruction that we're folding.
4818 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00004819 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004820 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4821
Reid Spencer266e42b2006-12-23 06:05:41 +00004822 // Get the ICmp opcode
4823 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004824
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004825 if (DivRHS->isNullValue()) {
4826 // Don't hack on divide by zeros!
Reid Spencer266e42b2006-12-23 06:05:41 +00004827 } else if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004828 LoBound = Prod;
4829 LoOverflow = ProdOV;
4830 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004831 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004832 if (CI->isNullValue()) { // (X / pos) op 0
4833 // Can't overflow.
4834 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4835 HiBound = DivRHS;
4836 } else if (isPositive(CI)) { // (X / pos) op pos
4837 LoBound = Prod;
4838 LoOverflow = ProdOV;
4839 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4840 } else { // (X / pos) op neg
4841 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4842 LoOverflow = AddWithOverflow(LoBound, Prod,
4843 cast<ConstantInt>(DivRHSH));
4844 HiBound = Prod;
4845 HiOverflow = ProdOV;
4846 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004847 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004848 if (CI->isNullValue()) { // (X / neg) op 0
4849 LoBound = AddOne(DivRHS);
4850 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004851 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004852 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004853 } else if (isPositive(CI)) { // (X / neg) op pos
4854 HiOverflow = LoOverflow = ProdOV;
4855 if (!LoOverflow)
4856 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4857 HiBound = AddOne(Prod);
4858 } else { // (X / neg) op neg
4859 LoBound = Prod;
4860 LoOverflow = HiOverflow = ProdOV;
4861 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4862 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004863
Chris Lattnera92af962004-10-11 19:40:04 +00004864 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00004865 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004866 }
4867
4868 if (LoBound) {
4869 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004870 switch (predicate) {
4871 default: assert(0 && "Unhandled icmp opcode!");
4872 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004873 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004874 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004875 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004876 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4877 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004878 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004879 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4880 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004881 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004882 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4883 true, I);
4884 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004885 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004886 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004887 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004888 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4889 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004890 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004891 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4892 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004893 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004894 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4895 false, I);
4896 case ICmpInst::ICMP_ULT:
4897 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004898 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004899 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004900 return new ICmpInst(predicate, X, LoBound);
4901 case ICmpInst::ICMP_UGT:
4902 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004903 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004904 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004905 if (predicate == ICmpInst::ICMP_UGT)
4906 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4907 else
4908 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004909 }
4910 }
4911 }
4912 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004913 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004914
Reid Spencer266e42b2006-12-23 06:05:41 +00004915 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004916 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004917 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004918
Reid Spencere0fc4df2006-10-20 07:07:24 +00004919 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4920 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004921 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4922 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004923 case Instruction::SRem:
4924 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4925 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4926 BO->hasOneUse()) {
4927 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4928 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004929 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4930 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004931 return new ICmpInst(I.getPredicate(), NewRem,
4932 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004933 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004934 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004935 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004936 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004937 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4938 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004939 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004940 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4941 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004942 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004943 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4944 // efficiently invertible, or if the add has just this one use.
4945 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004946
Chris Lattnerc992add2003-08-13 05:33:12 +00004947 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004948 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00004949 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004950 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004951 else if (BO->hasOneUse()) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00004952 Instruction *Neg = BinaryOperator::createNeg(BOp1);
Chris Lattnerc992add2003-08-13 05:33:12 +00004953 InsertNewInstBefore(Neg, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004954 Neg->takeName(BO);
Reid Spencer266e42b2006-12-23 06:05:41 +00004955 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00004956 }
4957 }
4958 break;
4959 case Instruction::Xor:
4960 // For the xor case, we can xor two constants together, eliminating
4961 // the explicit xor.
4962 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00004963 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4964 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004965
4966 // FALLTHROUGH
4967 case Instruction::Sub:
4968 // Replace (([sub|xor] A, B) != 0) with (A != B)
4969 if (CI->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00004970 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4971 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00004972 break;
4973
4974 case Instruction::Or:
4975 // If bits are being or'd in that are not present in the constant we
4976 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004977 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004978 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004979 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00004980 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4981 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004982 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004983 break;
4984
4985 case Instruction::And:
4986 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004987 // If bits are being compared against that are and'd out, then the
4988 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004989 if (!ConstantExpr::getAnd(CI,
4990 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00004991 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4992 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004993
Chris Lattner35167c32004-06-09 07:59:58 +00004994 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004995 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00004996 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
4997 ICmpInst::ICMP_NE, Op0,
4998 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004999
Reid Spencer266e42b2006-12-23 06:05:41 +00005000 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00005001 if (isSignBit(BOC)) {
5002 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005003 Constant *Zero = Constant::getNullValue(X->getType());
5004 ICmpInst::Predicate pred = isICMP_NE ?
5005 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5006 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005007 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005008
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005009 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005010 if (CI->isNullValue() && isHighOnes(BOC)) {
5011 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005012 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005013 ICmpInst::Predicate pred = isICMP_NE ?
5014 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5015 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005016 }
5017
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005018 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005019 default: break;
5020 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005021 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5022 // Handle set{eq|ne} <intrinsic>, intcst.
5023 switch (II->getIntrinsicID()) {
5024 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005025 case Intrinsic::bswap_i16:
5026 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005027 WorkList.push_back(II); // Dead?
5028 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005029 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005030 ByteSwap_16(CI->getZExtValue())));
5031 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005032 case Intrinsic::bswap_i32:
5033 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005034 WorkList.push_back(II); // Dead?
5035 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005036 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005037 ByteSwap_32(CI->getZExtValue())));
5038 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005039 case Intrinsic::bswap_i64:
5040 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005041 WorkList.push_back(II); // Dead?
5042 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005043 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005044 ByteSwap_64(CI->getZExtValue())));
5045 return &I;
5046 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005047 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005048 } else { // Not a ICMP_EQ/ICMP_NE
5049 // If the LHS is a cast from an integral value of the same size, then
5050 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005051 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5052 Value *CastOp = Cast->getOperand(0);
5053 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005054 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner03c49532007-01-15 02:27:26 +00005055 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005056 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005057 // If this is an unsigned comparison, try to make the comparison use
5058 // smaller constant values.
5059 switch (I.getPredicate()) {
5060 default: break;
5061 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5062 ConstantInt *CUI = cast<ConstantInt>(CI);
5063 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5064 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5065 ConstantInt::get(SrcTy, -1));
5066 break;
5067 }
5068 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5069 ConstantInt *CUI = cast<ConstantInt>(CI);
5070 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5071 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5072 Constant::getNullValue(SrcTy));
5073 break;
5074 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005075 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005076
Chris Lattner2b55ea32004-02-23 07:16:20 +00005077 }
5078 }
Chris Lattnere967b342003-06-04 05:10:11 +00005079 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005080 }
5081
Reid Spencer266e42b2006-12-23 06:05:41 +00005082 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005083 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5084 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5085 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005086 case Instruction::GetElementPtr:
5087 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005088 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005089 bool isAllZeros = true;
5090 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5091 if (!isa<Constant>(LHSI->getOperand(i)) ||
5092 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5093 isAllZeros = false;
5094 break;
5095 }
5096 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005097 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005098 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5099 }
5100 break;
5101
Chris Lattner77c32c32005-04-23 15:31:55 +00005102 case Instruction::PHI:
5103 if (Instruction *NV = FoldOpIntoPhi(I))
5104 return NV;
5105 break;
5106 case Instruction::Select:
5107 // If either operand of the select is a constant, we can fold the
5108 // comparison into the select arms, which will cause one to be
5109 // constant folded and the select turned into a bitwise or.
5110 Value *Op1 = 0, *Op2 = 0;
5111 if (LHSI->hasOneUse()) {
5112 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5113 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005114 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5115 // Insert a new ICmp of the other select operand.
5116 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5117 LHSI->getOperand(2), RHSC,
5118 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005119 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5120 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005121 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5122 // Insert a new ICmp of the other select operand.
5123 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5124 LHSI->getOperand(1), RHSC,
5125 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005126 }
5127 }
Jeff Cohen82639852005-04-23 21:38:35 +00005128
Chris Lattner77c32c32005-04-23 15:31:55 +00005129 if (Op1)
5130 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5131 break;
5132 }
5133 }
5134
Reid Spencer266e42b2006-12-23 06:05:41 +00005135 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005136 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005137 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005138 return NI;
5139 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005140 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5141 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005142 return NI;
5143
Reid Spencer266e42b2006-12-23 06:05:41 +00005144 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005145 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5146 // now.
5147 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5148 if (isa<PointerType>(Op0->getType()) &&
5149 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005150 // We keep moving the cast from the left operand over to the right
5151 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005152 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005153
Chris Lattner64d87b02007-01-06 01:45:59 +00005154 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5155 // so eliminate it as well.
5156 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5157 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005158
Chris Lattner16930792003-11-03 04:25:02 +00005159 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005160 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005161 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005162 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005163 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005164 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005165 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005166 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005167 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005168 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005169 }
5170
5171 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005172 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005173 // This comes up when you have code like
5174 // int X = A < B;
5175 // if (X) ...
5176 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005177 // with a constant or another cast from the same type.
5178 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005179 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005180 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005181 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005182
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005183 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005184 Value *A, *B, *C, *D;
5185 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5186 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5187 Value *OtherVal = A == Op1 ? B : A;
5188 return new ICmpInst(I.getPredicate(), OtherVal,
5189 Constant::getNullValue(A->getType()));
5190 }
5191
5192 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5193 // A^c1 == C^c2 --> A == C^(c1^c2)
5194 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5195 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5196 if (Op1->hasOneUse()) {
5197 Constant *NC = ConstantExpr::getXor(C1, C2);
5198 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5199 return new ICmpInst(I.getPredicate(), A,
5200 InsertNewInstBefore(Xor, I));
5201 }
5202
5203 // A^B == A^D -> B == D
5204 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5205 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5206 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5207 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5208 }
5209 }
5210
5211 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5212 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005213 // A == (A^B) -> B == 0
5214 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005215 return new ICmpInst(I.getPredicate(), OtherVal,
5216 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005217 }
5218 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005219 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005220 return new ICmpInst(I.getPredicate(), B,
5221 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005222 }
5223 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005224 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005225 return new ICmpInst(I.getPredicate(), B,
5226 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005227 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005228
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005229 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5230 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5231 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5232 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5233 Value *X = 0, *Y = 0, *Z = 0;
5234
5235 if (A == C) {
5236 X = B; Y = D; Z = A;
5237 } else if (A == D) {
5238 X = B; Y = C; Z = A;
5239 } else if (B == C) {
5240 X = A; Y = D; Z = B;
5241 } else if (B == D) {
5242 X = A; Y = C; Z = B;
5243 }
5244
5245 if (X) { // Build (X^Y) & Z
5246 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5247 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5248 I.setOperand(0, Op1);
5249 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5250 return &I;
5251 }
5252 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005253 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005254 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005255}
5256
Reid Spencer266e42b2006-12-23 06:05:41 +00005257// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005258// We only handle extending casts so far.
5259//
Reid Spencer266e42b2006-12-23 06:05:41 +00005260Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5261 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005262 Value *LHSCIOp = LHSCI->getOperand(0);
5263 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005264 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005265 Value *RHSCIOp;
5266
Reid Spencer266e42b2006-12-23 06:05:41 +00005267 // We only handle extension cast instructions, so far. Enforce this.
5268 if (LHSCI->getOpcode() != Instruction::ZExt &&
5269 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005270 return 0;
5271
Reid Spencer266e42b2006-12-23 06:05:41 +00005272 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5273 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005274
Reid Spencer266e42b2006-12-23 06:05:41 +00005275 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005276 // Not an extension from the same type?
5277 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005278 if (RHSCIOp->getType() != LHSCIOp->getType())
5279 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005280
5281 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5282 // and the other is a zext), then we can't handle this.
5283 if (CI->getOpcode() != LHSCI->getOpcode())
5284 return 0;
5285
5286 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5287 // then we can't handle this.
5288 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5289 return 0;
5290
5291 // Okay, just insert a compare of the reduced operands now!
5292 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005293 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005294
Reid Spencer266e42b2006-12-23 06:05:41 +00005295 // If we aren't dealing with a constant on the RHS, exit early
5296 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5297 if (!CI)
5298 return 0;
5299
5300 // Compute the constant that would happen if we truncated to SrcTy then
5301 // reextended to DestTy.
5302 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5303 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5304
5305 // If the re-extended constant didn't change...
5306 if (Res2 == CI) {
5307 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5308 // For example, we might have:
5309 // %A = sext short %X to uint
5310 // %B = icmp ugt uint %A, 1330
5311 // It is incorrect to transform this into
5312 // %B = icmp ugt short %X, 1330
5313 // because %A may have negative value.
5314 //
5315 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5316 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005317 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005318 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5319 else
5320 return 0;
5321 }
5322
5323 // The re-extended constant changed so the constant cannot be represented
5324 // in the shorter type. Consequently, we cannot emit a simple comparison.
5325
5326 // First, handle some easy cases. We know the result cannot be equal at this
5327 // point so handle the ICI.isEquality() cases
5328 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005329 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005330 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005331 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005332
5333 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5334 // should have been folded away previously and not enter in here.
5335 Value *Result;
5336 if (isSignedCmp) {
5337 // We're performing a signed comparison.
5338 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005339 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005340 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005341 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005342 } else {
5343 // We're performing an unsigned comparison.
5344 if (isSignedExt) {
5345 // We're performing an unsigned comp with a sign extended value.
5346 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005347 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005348 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5349 NegOne, ICI.getName()), ICI);
5350 } else {
5351 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005352 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005353 }
5354 }
5355
5356 // Finally, return the value computed.
5357 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5358 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5359 return ReplaceInstUsesWith(ICI, Result);
5360 } else {
5361 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5362 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5363 "ICmp should be folded!");
5364 if (Constant *CI = dyn_cast<Constant>(Result))
5365 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5366 else
5367 return BinaryOperator::createNot(Result);
5368 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005369}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005370
Reid Spencer2341c222007-02-02 02:16:23 +00005371Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5372 return commonShiftTransforms(I);
5373}
5374
5375Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5376 return commonShiftTransforms(I);
5377}
5378
5379Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5380 return commonShiftTransforms(I);
5381}
5382
5383Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5384 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00005385 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005386
5387 // shl X, 0 == X and shr X, 0 == X
5388 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00005389 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005390 Op0 == Constant::getNullValue(Op0->getType()))
5391 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005392
Reid Spencer266e42b2006-12-23 06:05:41 +00005393 if (isa<UndefValue>(Op0)) {
5394 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005395 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005396 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005397 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5398 }
5399 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005400 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5401 return ReplaceInstUsesWith(I, Op0);
5402 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005403 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005404 }
5405
Chris Lattnerd4dee402006-11-10 23:38:52 +00005406 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5407 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005408 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005409 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005410 return ReplaceInstUsesWith(I, CSI);
5411
Chris Lattner183b3362004-04-09 19:05:30 +00005412 // Try to fold constant and into select arguments.
5413 if (isa<Constant>(Op0))
5414 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005415 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005416 return R;
5417
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005418 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005419 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005420 if (MaskedValueIsZero(Op0,
5421 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005422 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005423 }
5424 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005425
Reid Spencere0fc4df2006-10-20 07:07:24 +00005426 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005427 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5428 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005429 return 0;
5430}
5431
Reid Spencere0fc4df2006-10-20 07:07:24 +00005432Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00005433 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005434 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00005435
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005436 // See if we can simplify any instructions used by the instruction whose sole
5437 // purpose is to compute bits we don't care about.
5438 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00005439 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005440 KnownZero, KnownOne))
5441 return &I;
5442
Chris Lattner14553932006-01-06 07:12:35 +00005443 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5444 // of a signed value.
5445 //
5446 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005447 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005448 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00005449 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5450 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005451 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005452 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005453 }
Chris Lattner14553932006-01-06 07:12:35 +00005454 }
5455
5456 // ((X*C1) << C2) == (X * (C1 << C2))
5457 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5458 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5459 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5460 return BinaryOperator::createMul(BO->getOperand(0),
5461 ConstantExpr::getShl(BOOp, Op1));
5462
5463 // Try to fold constant and into select arguments.
5464 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5465 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5466 return R;
5467 if (isa<PHINode>(Op0))
5468 if (Instruction *NV = FoldOpIntoPhi(I))
5469 return NV;
5470
5471 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005472 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5473 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5474 Value *V1, *V2;
5475 ConstantInt *CC;
5476 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005477 default: break;
5478 case Instruction::Add:
5479 case Instruction::And:
5480 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00005481 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005482 // These operators commute.
5483 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005484 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5485 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005486 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005487 Instruction *YS = BinaryOperator::createShl(
Chris Lattner14553932006-01-06 07:12:35 +00005488 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005489 Op0BO->getName());
5490 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005491 Instruction *X =
5492 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5493 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005494 InsertNewInstBefore(X, I); // (X + (Y << C))
5495 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005496 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005497 return BinaryOperator::createAnd(X, C2);
5498 }
Chris Lattner14553932006-01-06 07:12:35 +00005499
Chris Lattner797dee72005-09-18 06:30:59 +00005500 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00005501 Value *Op0BOOp1 = Op0BO->getOperand(1);
5502 if (isLeftShift && Op0BOOp1->hasOneUse() && V2 == Op1 &&
5503 match(Op0BOOp1,
5504 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
5505 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)-> hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005506 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005507 Op0BO->getOperand(0), Op1,
5508 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005509 InsertNewInstBefore(YS, I); // (Y << C)
5510 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005511 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005512 V1->getName()+".mask");
5513 InsertNewInstBefore(XM, I); // X & (CC << C)
5514
5515 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5516 }
Reid Spencer2f34b982007-02-02 14:41:37 +00005517 }
Chris Lattner14553932006-01-06 07:12:35 +00005518
Reid Spencer2f34b982007-02-02 14:41:37 +00005519 // FALL THROUGH.
5520 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005521 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005522 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5523 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005524 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005525 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005526 Op0BO->getOperand(1), Op1,
5527 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005528 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005529 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005530 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005531 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005532 InsertNewInstBefore(X, I); // (X + (Y << C))
5533 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005534 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005535 return BinaryOperator::createAnd(X, C2);
5536 }
Chris Lattner14553932006-01-06 07:12:35 +00005537
Chris Lattner1df0e982006-05-31 21:14:00 +00005538 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005539 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5540 match(Op0BO->getOperand(0),
5541 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005542 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005543 cast<BinaryOperator>(Op0BO->getOperand(0))
5544 ->getOperand(0)->hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005545 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005546 Op0BO->getOperand(1), Op1,
5547 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005548 InsertNewInstBefore(YS, I); // (Y << C)
5549 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005550 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005551 V1->getName()+".mask");
5552 InsertNewInstBefore(XM, I); // X & (CC << C)
5553
Chris Lattner1df0e982006-05-31 21:14:00 +00005554 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005555 }
Chris Lattner14553932006-01-06 07:12:35 +00005556
Chris Lattner27cb9db2005-09-18 05:12:10 +00005557 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00005558 }
Chris Lattner14553932006-01-06 07:12:35 +00005559 }
5560
5561
5562 // If the operand is an bitwise operator with a constant RHS, and the
5563 // shift is the only use, we can pull it out of the shift.
5564 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5565 bool isValid = true; // Valid only for And, Or, Xor
5566 bool highBitSet = false; // Transform if high bit of constant set?
5567
5568 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005569 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005570 case Instruction::Add:
5571 isValid = isLeftShift;
5572 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005573 case Instruction::Or:
5574 case Instruction::Xor:
5575 highBitSet = false;
5576 break;
5577 case Instruction::And:
5578 highBitSet = true;
5579 break;
Chris Lattner14553932006-01-06 07:12:35 +00005580 }
5581
5582 // If this is a signed shift right, and the high bit is modified
5583 // by the logical operation, do not perform the transformation.
5584 // The highBitSet boolean indicates the value of the high bit of
5585 // the constant which would cause it to be modified for this
5586 // operation.
5587 //
Chris Lattner3e009e82007-02-05 00:57:54 +00005588 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005589 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005590 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5591 }
5592
5593 if (isValid) {
5594 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5595
5596 Instruction *NewShift =
Chris Lattner6e0123b2007-02-11 01:23:03 +00005597 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00005598 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005599 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00005600
5601 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5602 NewRHS);
5603 }
5604 }
5605 }
5606 }
5607
Chris Lattnereb372a02006-01-06 07:52:12 +00005608 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00005609 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5610 if (ShiftOp && !ShiftOp->isShift())
5611 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00005612
Reid Spencere0fc4df2006-10-20 07:07:24 +00005613 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005614 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Reid Spencere0fc4df2006-10-20 07:07:24 +00005615 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5616 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattner3e009e82007-02-05 00:57:54 +00005617 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5618 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
5619 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005620
Chris Lattner3e009e82007-02-05 00:57:54 +00005621 unsigned AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5622 if (AmtSum > I.getType()->getPrimitiveSizeInBits())
5623 AmtSum = I.getType()->getPrimitiveSizeInBits();
5624
5625 const IntegerType *Ty = cast<IntegerType>(I.getType());
5626
5627 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00005628 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner3e009e82007-02-05 00:57:54 +00005629 return BinaryOperator::create(I.getOpcode(), X,
5630 ConstantInt::get(Ty, AmtSum));
5631 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5632 I.getOpcode() == Instruction::AShr) {
5633 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
5634 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5635 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5636 I.getOpcode() == Instruction::LShr) {
5637 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5638 Instruction *Shift =
5639 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5640 InsertNewInstBefore(Shift, I);
5641
5642 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5643 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005644 }
5645
Chris Lattner3e009e82007-02-05 00:57:54 +00005646 // Okay, if we get here, one shift must be left, and the other shift must be
5647 // right. See if the amounts are equal.
5648 if (ShiftAmt1 == ShiftAmt2) {
5649 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5650 if (I.getOpcode() == Instruction::Shl) {
Chris Lattner0a28e902007-02-05 04:09:35 +00005651 uint64_t Mask = Ty->getBitMask() << ShiftAmt1;
Chris Lattner3e009e82007-02-05 00:57:54 +00005652 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5653 }
5654 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5655 if (I.getOpcode() == Instruction::LShr) {
Chris Lattner0a28e902007-02-05 04:09:35 +00005656 uint64_t Mask = Ty->getBitMask() >> ShiftAmt1;
Chris Lattner3e009e82007-02-05 00:57:54 +00005657 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5658 }
5659 // We can simplify ((X << C) >>s C) into a trunc + sext.
5660 // NOTE: we could do this for any C, but that would make 'unusual' integer
5661 // types. For now, just stick to ones well-supported by the code
5662 // generators.
5663 const Type *SExtType = 0;
5664 switch (Ty->getBitWidth() - ShiftAmt1) {
5665 case 8 : SExtType = Type::Int8Ty; break;
5666 case 16: SExtType = Type::Int16Ty; break;
5667 case 32: SExtType = Type::Int32Ty; break;
5668 default: break;
5669 }
5670 if (SExtType) {
5671 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5672 InsertNewInstBefore(NewTrunc, I);
5673 return new SExtInst(NewTrunc, Ty);
5674 }
5675 // Otherwise, we can't handle it yet.
5676 } else if (ShiftAmt1 < ShiftAmt2) {
5677 unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00005678
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005679 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005680 if (I.getOpcode() == Instruction::Shl) {
5681 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5682 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005683 Instruction *Shift =
Chris Lattner3e009e82007-02-05 00:57:54 +00005684 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005685 InsertNewInstBefore(Shift, I);
5686
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005687 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00005688 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005689 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005690
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005691 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005692 if (I.getOpcode() == Instruction::LShr) {
5693 assert(ShiftOp->getOpcode() == Instruction::Shl);
5694 Instruction *Shift =
5695 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5696 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005697
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005698 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00005699 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00005700 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005701
5702 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
5703 } else {
5704 assert(ShiftAmt2 < ShiftAmt1);
5705 unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
5706
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005707 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005708 if (I.getOpcode() == Instruction::Shl) {
5709 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5710 ShiftOp->getOpcode() == Instruction::AShr);
5711 Instruction *Shift =
5712 BinaryOperator::create(ShiftOp->getOpcode(), X,
5713 ConstantInt::get(Ty, ShiftDiff));
5714 InsertNewInstBefore(Shift, I);
5715
5716 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
5717 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5718 }
5719
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005720 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005721 if (I.getOpcode() == Instruction::LShr) {
5722 assert(ShiftOp->getOpcode() == Instruction::Shl);
5723 Instruction *Shift =
5724 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5725 InsertNewInstBefore(Shift, I);
5726
5727 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5728 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5729 }
5730
5731 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00005732 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005733 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005734 return 0;
5735}
5736
Chris Lattner48a44f72002-05-02 17:06:02 +00005737
Chris Lattner8f663e82005-10-29 04:36:15 +00005738/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5739/// expression. If so, decompose it, returning some value X, such that Val is
5740/// X*Scale+Offset.
5741///
5742static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5743 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00005744 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005745 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00005746 Offset = CI->getZExtValue();
5747 Scale = 1;
5748 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00005749 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5750 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005751 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00005752 if (I->getOpcode() == Instruction::Shl) {
5753 // This is a value scaled by '1 << the shift amt'.
5754 Scale = 1U << CUI->getZExtValue();
5755 Offset = 0;
5756 return I->getOperand(0);
5757 } else if (I->getOpcode() == Instruction::Mul) {
5758 // This value is scaled by 'CUI'.
5759 Scale = CUI->getZExtValue();
5760 Offset = 0;
5761 return I->getOperand(0);
5762 } else if (I->getOpcode() == Instruction::Add) {
5763 // We have X+C. Check to see if we really have (X*C2)+C1,
5764 // where C1 is divisible by C2.
5765 unsigned SubScale;
5766 Value *SubVal =
5767 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5768 Offset += CUI->getZExtValue();
5769 if (SubScale > 1 && (Offset % SubScale == 0)) {
5770 Scale = SubScale;
5771 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00005772 }
5773 }
5774 }
5775 }
5776 }
5777
5778 // Otherwise, we can't look past this.
5779 Scale = 1;
5780 Offset = 0;
5781 return Val;
5782}
5783
5784
Chris Lattner216be912005-10-24 06:03:58 +00005785/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5786/// try to eliminate the cast by moving the type information into the alloc.
5787Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5788 AllocationInst &AI) {
5789 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005790 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005791
Chris Lattnerac87beb2005-10-24 06:22:12 +00005792 // Remove any uses of AI that are dead.
5793 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5794 std::vector<Instruction*> DeadUsers;
5795 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5796 Instruction *User = cast<Instruction>(*UI++);
5797 if (isInstructionTriviallyDead(User)) {
5798 while (UI != E && *UI == User)
5799 ++UI; // If this instruction uses AI more than once, don't break UI.
5800
5801 // Add operands to the worklist.
5802 AddUsesToWorkList(*User);
5803 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005804 DOUT << "IC: DCE: " << *User;
Chris Lattnerac87beb2005-10-24 06:22:12 +00005805
5806 User->eraseFromParent();
5807 removeFromWorkList(User);
5808 }
5809 }
5810
Chris Lattner216be912005-10-24 06:03:58 +00005811 // Get the type really allocated and the type casted to.
5812 const Type *AllocElTy = AI.getAllocatedType();
5813 const Type *CastElTy = PTy->getElementType();
5814 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005815
Chris Lattner945e4372007-02-14 05:52:17 +00005816 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
5817 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005818 if (CastElTyAlign < AllocElTyAlign) return 0;
5819
Chris Lattner46705b22005-10-24 06:35:18 +00005820 // If the allocation has multiple uses, only promote it if we are strictly
5821 // increasing the alignment of the resultant allocation. If we keep it the
5822 // same, we open the door to infinite loops of various kinds.
5823 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5824
Chris Lattner216be912005-10-24 06:03:58 +00005825 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5826 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005827 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005828
Chris Lattner8270c332005-10-29 03:19:53 +00005829 // See if we can satisfy the modulus by pulling a scale out of the array
5830 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005831 unsigned ArraySizeScale, ArrayOffset;
5832 Value *NumElements = // See if the array size is a decomposable linear expr.
5833 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5834
Chris Lattner8270c332005-10-29 03:19:53 +00005835 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5836 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005837 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5838 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005839
Chris Lattner8270c332005-10-29 03:19:53 +00005840 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5841 Value *Amt = 0;
5842 if (Scale == 1) {
5843 Amt = NumElements;
5844 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005845 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00005846 Amt = ConstantInt::get(Type::Int32Ty, Scale);
5847 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00005848 Amt = ConstantExpr::getMul(
5849 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5850 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005851 else if (Scale != 1) {
5852 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5853 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005854 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005855 }
5856
Chris Lattner8f663e82005-10-29 04:36:15 +00005857 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00005858 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005859 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5860 Amt = InsertNewInstBefore(Tmp, AI);
5861 }
5862
Chris Lattner216be912005-10-24 06:03:58 +00005863 AllocationInst *New;
5864 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00005865 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00005866 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00005867 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00005868 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005869 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005870
5871 // If the allocation has multiple uses, insert a cast and change all things
5872 // that used it to use the new cast. This will also hack on CI, but it will
5873 // die soon.
5874 if (!AI.hasOneUse()) {
5875 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005876 // New is the allocation instruction, pointer typed. AI is the original
5877 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5878 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00005879 InsertNewInstBefore(NewCast, AI);
5880 AI.replaceAllUsesWith(NewCast);
5881 }
Chris Lattner216be912005-10-24 06:03:58 +00005882 return ReplaceInstUsesWith(CI, New);
5883}
5884
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005885/// CanEvaluateInDifferentType - Return true if we can take the specified value
5886/// and return it without inserting any new casts. This is used by code that
5887/// tries to decide whether promoting or shrinking integer operations to wider
5888/// or smaller types will allow us to eliminate a truncate or extend.
5889static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5890 int &NumCastsRemoved) {
5891 if (isa<Constant>(V)) return true;
5892
5893 Instruction *I = dyn_cast<Instruction>(V);
5894 if (!I || !I->hasOneUse()) return false;
5895
5896 switch (I->getOpcode()) {
5897 case Instruction::And:
5898 case Instruction::Or:
5899 case Instruction::Xor:
5900 // These operators can all arbitrarily be extended or truncated.
5901 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5902 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattner960acb02006-11-29 07:18:39 +00005903 case Instruction::AShr:
5904 case Instruction::LShr:
5905 case Instruction::Shl:
5906 // If this is just a bitcast changing the sign of the operation, we can
5907 // convert if the operand can be converted.
5908 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5909 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5910 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005911 case Instruction::Trunc:
5912 case Instruction::ZExt:
5913 case Instruction::SExt:
5914 case Instruction::BitCast:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005915 // If this is a cast from the destination type, we can trivially eliminate
5916 // it, and this will remove a cast overall.
5917 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005918 // If the first operand is itself a cast, and is eliminable, do not count
5919 // this as an eliminable cast. We would prefer to eliminate those two
5920 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005921 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005922 return true;
5923
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005924 ++NumCastsRemoved;
5925 return true;
5926 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005927 break;
5928 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005929 // TODO: Can handle more cases here.
5930 break;
5931 }
5932
5933 return false;
5934}
5935
5936/// EvaluateInDifferentType - Given an expression that
5937/// CanEvaluateInDifferentType returns true for, actually insert the code to
5938/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00005939Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
5940 bool isSigned ) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005941 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00005942 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005943
5944 // Otherwise, it must be an instruction.
5945 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005946 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005947 switch (I->getOpcode()) {
5948 case Instruction::And:
5949 case Instruction::Or:
5950 case Instruction::Xor: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005951 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5952 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005953 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5954 LHS, RHS, I->getName());
5955 break;
5956 }
Chris Lattner960acb02006-11-29 07:18:39 +00005957 case Instruction::AShr:
5958 case Instruction::LShr:
5959 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005960 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Reid Spencer2341c222007-02-02 02:16:23 +00005961 Res = BinaryOperator::create(Instruction::BinaryOps(I->getOpcode()), LHS,
5962 I->getOperand(1), I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00005963 break;
5964 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005965 case Instruction::Trunc:
5966 case Instruction::ZExt:
5967 case Instruction::SExt:
5968 case Instruction::BitCast:
5969 // If the source type of the cast is the type we're trying for then we can
5970 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005971 if (I->getOperand(0)->getType() == Ty)
5972 return I->getOperand(0);
5973
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005974 // Some other kind of cast, which shouldn't happen, so just ..
5975 // FALL THROUGH
5976 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005977 // TODO: Can handle more cases here.
5978 assert(0 && "Unreachable!");
5979 break;
5980 }
5981
5982 return InsertNewInstBefore(Res, *I);
5983}
5984
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005985/// @brief Implement the transforms common to all CastInst visitors.
5986Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005987 Value *Src = CI.getOperand(0);
5988
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005989 // Casting undef to anything results in undef so might as just replace it and
5990 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00005991 if (isa<UndefValue>(Src)) // cast undef -> undef
5992 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5993
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005994 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5995 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00005996 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005997 if (Instruction::CastOps opc =
5998 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5999 // The first cast (CSrc) is eliminable so we need to fix up or replace
6000 // the second cast (CI). CSrc will then have a good chance of being dead.
6001 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00006002 }
6003 }
Chris Lattner03841652004-05-25 04:29:21 +00006004
Chris Lattnerd0d51602003-06-21 23:12:02 +00006005 // If casting the result of a getelementptr instruction with no offset, turn
6006 // this into a cast of the original pointer!
6007 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006008 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006009 bool AllZeroOperands = true;
6010 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6011 if (!isa<Constant>(GEP->getOperand(i)) ||
6012 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6013 AllZeroOperands = false;
6014 break;
6015 }
6016 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006017 // Changing the cast operand is usually not a good idea but it is safe
6018 // here because the pointer operand is being replaced with another
6019 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006020 CI.setOperand(0, GEP->getOperand(0));
6021 return &CI;
6022 }
6023 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006024
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006025 // If we are casting a malloc or alloca to a pointer to a type of the same
6026 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006027 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006028 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6029 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006030
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006031 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006032 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6033 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6034 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006035
6036 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006037 if (isa<PHINode>(Src))
6038 if (Instruction *NV = FoldOpIntoPhi(CI))
6039 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006040
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006041 return 0;
6042}
6043
6044/// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
6045/// integers. This function implements the common transforms for all those
6046/// cases.
6047/// @brief Implement the transforms common to CastInst with integer operands
6048Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6049 if (Instruction *Result = commonCastTransforms(CI))
6050 return Result;
6051
6052 Value *Src = CI.getOperand(0);
6053 const Type *SrcTy = Src->getType();
6054 const Type *DestTy = CI.getType();
6055 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6056 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6057
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006058 // See if we can simplify any instructions used by the LHS whose sole
6059 // purpose is to compute bits we don't care about.
6060 uint64_t KnownZero = 0, KnownOne = 0;
Reid Spencera94d3942007-01-19 21:13:56 +00006061 if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006062 KnownZero, KnownOne))
6063 return &CI;
6064
6065 // If the source isn't an instruction or has more than one use then we
6066 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006067 Instruction *SrcI = dyn_cast<Instruction>(Src);
6068 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006069 return 0;
6070
6071 // Attempt to propagate the cast into the instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006072 int NumCastsRemoved = 0;
6073 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6074 // If this cast is a truncate, evaluting in a different type always
6075 // eliminates the cast, so it is always a win. If this is a noop-cast
6076 // this just removes a noop cast which isn't pointful, but simplifies
6077 // the code. If this is a zero-extension, we need to do an AND to
6078 // maintain the clear top-part of the computation, so we require that
6079 // the input have eliminated at least one cast. If this is a sign
6080 // extension, we insert two new casts (to do the extension) so we
6081 // require that two casts have been eliminated.
6082 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6083 if (!DoXForm) {
6084 switch (CI.getOpcode()) {
6085 case Instruction::Trunc:
6086 DoXForm = true;
6087 break;
6088 case Instruction::ZExt:
6089 DoXForm = NumCastsRemoved >= 1;
6090 break;
6091 case Instruction::SExt:
6092 DoXForm = NumCastsRemoved >= 2;
6093 break;
6094 case Instruction::BitCast:
6095 DoXForm = false;
6096 break;
6097 default:
6098 // All the others use floating point so we shouldn't actually
6099 // get here because of the check above.
6100 assert(!"Unknown cast type .. unreachable");
6101 break;
6102 }
6103 }
6104
6105 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006106 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6107 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006108 assert(Res->getType() == DestTy);
6109 switch (CI.getOpcode()) {
6110 default: assert(0 && "Unknown cast type!");
6111 case Instruction::Trunc:
6112 case Instruction::BitCast:
6113 // Just replace this cast with the result.
6114 return ReplaceInstUsesWith(CI, Res);
6115 case Instruction::ZExt: {
6116 // We need to emit an AND to clear the high bits.
6117 assert(SrcBitSize < DestBitSize && "Not a zext?");
6118 Constant *C =
Reid Spencerc635f472006-12-31 05:48:39 +00006119 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006120 if (DestBitSize < 64)
6121 C = ConstantExpr::getTrunc(C, DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006122 return BinaryOperator::createAnd(Res, C);
6123 }
6124 case Instruction::SExt:
6125 // We need to emit a cast to truncate, then a cast to sext.
6126 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006127 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6128 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006129 }
6130 }
6131 }
6132
6133 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6134 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6135
6136 switch (SrcI->getOpcode()) {
6137 case Instruction::Add:
6138 case Instruction::Mul:
6139 case Instruction::And:
6140 case Instruction::Or:
6141 case Instruction::Xor:
6142 // If we are discarding information, or just changing the sign,
6143 // rewrite.
6144 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6145 // Don't insert two casts if they cannot be eliminated. We allow
6146 // two casts to be inserted if the sizes are the same. This could
6147 // only be converting signedness, which is a noop.
6148 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006149 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6150 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006151 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006152 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6153 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6154 return BinaryOperator::create(
6155 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006156 }
6157 }
6158
6159 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6160 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6161 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006162 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006163 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006164 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006165 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6166 }
6167 break;
6168 case Instruction::SDiv:
6169 case Instruction::UDiv:
6170 case Instruction::SRem:
6171 case Instruction::URem:
6172 // If we are just changing the sign, rewrite.
6173 if (DestBitSize == SrcBitSize) {
6174 // Don't insert two casts if they cannot be eliminated. We allow
6175 // two casts to be inserted if the sizes are the same. This could
6176 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006177 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6178 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006179 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6180 Op0, DestTy, SrcI);
6181 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6182 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006183 return BinaryOperator::create(
6184 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6185 }
6186 }
6187 break;
6188
6189 case Instruction::Shl:
6190 // Allow changing the sign of the source operand. Do not allow
6191 // changing the size of the shift, UNLESS the shift amount is a
6192 // constant. We must not change variable sized shifts to a smaller
6193 // size, because it is undefined to shift more bits out than exist
6194 // in the value.
6195 if (DestBitSize == SrcBitSize ||
6196 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006197 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6198 Instruction::BitCast : Instruction::Trunc);
6199 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00006200 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006201 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006202 }
6203 break;
6204 case Instruction::AShr:
6205 // If this is a signed shr, and if all bits shifted in are about to be
6206 // truncated off, turn it into an unsigned shr to allow greater
6207 // simplifications.
6208 if (DestBitSize < SrcBitSize &&
6209 isa<ConstantInt>(Op1)) {
6210 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6211 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6212 // Insert the new logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00006213 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006214 }
6215 }
6216 break;
6217
Reid Spencer266e42b2006-12-23 06:05:41 +00006218 case Instruction::ICmp:
6219 // If we are just checking for a icmp eq of a single bit and casting it
6220 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006221 // cast to integer to avoid the comparison.
6222 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6223 uint64_t Op1CV = Op1C->getZExtValue();
6224 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6225 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6226 // cast (X == 1) to int --> X iff X has only the low bit set.
6227 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6228 // cast (X != 0) to int --> X iff X has only the low bit set.
6229 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6230 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6231 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6232 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6233 // If Op1C some other power of two, convert:
6234 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00006235 uint64_t TypeMask = Op1C->getType()->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006236 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006237
6238 // This only works for EQ and NE
6239 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6240 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6241 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006242
6243 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006244 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006245 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6246 // (X&4) == 2 --> false
6247 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00006248 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006249 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006250 return ReplaceInstUsesWith(CI, Res);
6251 }
6252
6253 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6254 Value *In = Op0;
6255 if (ShiftAmt) {
6256 // Perform a logical shr by shiftamt.
6257 // Insert the shift to put the result in the low bit.
6258 In = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006259 BinaryOperator::createLShr(In,
Reid Spencer2341c222007-02-02 02:16:23 +00006260 ConstantInt::get(In->getType(), ShiftAmt),
6261 In->getName()+".lobit"), CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006262 }
6263
Reid Spencer266e42b2006-12-23 06:05:41 +00006264 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006265 Constant *One = ConstantInt::get(In->getType(), 1);
6266 In = BinaryOperator::createXor(In, One, "tmp");
6267 InsertNewInstBefore(cast<Instruction>(In), CI);
6268 }
6269
6270 if (CI.getType() == In->getType())
6271 return ReplaceInstUsesWith(CI, In);
6272 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006273 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006274 }
6275 }
6276 }
6277 break;
6278 }
6279 return 0;
6280}
6281
6282Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006283 if (Instruction *Result = commonIntCastTransforms(CI))
6284 return Result;
6285
6286 Value *Src = CI.getOperand(0);
6287 const Type *Ty = CI.getType();
6288 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6289
6290 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6291 switch (SrcI->getOpcode()) {
6292 default: break;
6293 case Instruction::LShr:
6294 // We can shrink lshr to something smaller if we know the bits shifted in
6295 // are already zeros.
6296 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6297 unsigned ShAmt = ShAmtV->getZExtValue();
6298
6299 // Get a mask for the bits shifting in.
6300 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006301 Value* SrcIOp0 = SrcI->getOperand(0);
6302 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006303 if (ShAmt >= DestBitWidth) // All zeros.
6304 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6305
6306 // Okay, we can shrink this. Truncate the input, then return a new
6307 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00006308 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6309 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6310 Ty, CI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006311 return BinaryOperator::createLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00006312 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006313 } else { // This is a variable shr.
6314
6315 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6316 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6317 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006318 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006319 Value *One = ConstantInt::get(SrcI->getType(), 1);
6320
Reid Spencer2341c222007-02-02 02:16:23 +00006321 Value *V = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006322 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00006323 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00006324 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6325 SrcI->getOperand(0),
6326 "tmp"), CI);
6327 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006328 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006329 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006330 }
6331 break;
6332 }
6333 }
6334
6335 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006336}
6337
6338Instruction *InstCombiner::visitZExt(CastInst &CI) {
6339 // If one of the common conversion will work ..
6340 if (Instruction *Result = commonIntCastTransforms(CI))
6341 return Result;
6342
6343 Value *Src = CI.getOperand(0);
6344
6345 // If this is a cast of a cast
6346 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006347 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6348 // types and if the sizes are just right we can convert this into a logical
6349 // 'and' which will be much cheaper than the pair of casts.
6350 if (isa<TruncInst>(CSrc)) {
6351 // Get the sizes of the types involved
6352 Value *A = CSrc->getOperand(0);
6353 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6354 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6355 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6356 // If we're actually extending zero bits and the trunc is a no-op
6357 if (MidSize < DstSize && SrcSize == DstSize) {
6358 // Replace both of the casts with an And of the type mask.
Reid Spencera94d3942007-01-19 21:13:56 +00006359 uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006360 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6361 Instruction *And =
6362 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6363 // Unfortunately, if the type changed, we need to cast it back.
6364 if (And->getType() != CI.getType()) {
6365 And->setName(CSrc->getName()+".mask");
6366 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006367 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006368 }
6369 return And;
6370 }
6371 }
6372 }
6373
6374 return 0;
6375}
6376
6377Instruction *InstCombiner::visitSExt(CastInst &CI) {
6378 return commonIntCastTransforms(CI);
6379}
6380
6381Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6382 return commonCastTransforms(CI);
6383}
6384
6385Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6386 return commonCastTransforms(CI);
6387}
6388
6389Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006390 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006391}
6392
6393Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006394 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006395}
6396
6397Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6398 return commonCastTransforms(CI);
6399}
6400
6401Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6402 return commonCastTransforms(CI);
6403}
6404
6405Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006406 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006407}
6408
6409Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6410 return commonCastTransforms(CI);
6411}
6412
6413Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6414
6415 // If the operands are integer typed then apply the integer transforms,
6416 // otherwise just apply the common ones.
6417 Value *Src = CI.getOperand(0);
6418 const Type *SrcTy = Src->getType();
6419 const Type *DestTy = CI.getType();
6420
Chris Lattner03c49532007-01-15 02:27:26 +00006421 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006422 if (Instruction *Result = commonIntCastTransforms(CI))
6423 return Result;
6424 } else {
6425 if (Instruction *Result = commonCastTransforms(CI))
6426 return Result;
6427 }
6428
6429
6430 // Get rid of casts from one type to the same type. These are useless and can
6431 // be replaced by the operand.
6432 if (DestTy == Src->getType())
6433 return ReplaceInstUsesWith(CI, Src);
6434
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006435 // If the source and destination are pointers, and this cast is equivalent to
6436 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6437 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006438 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6439 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6440 const Type *DstElTy = DstPTy->getElementType();
6441 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006442
Reid Spencerc635f472006-12-31 05:48:39 +00006443 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006444 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006445 while (SrcElTy != DstElTy &&
6446 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6447 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6448 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006449 ++NumZeros;
6450 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006451
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006452 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006453 if (SrcElTy == DstElTy) {
Chris Lattner416a8932007-01-31 20:08:52 +00006454 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6455 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006456 }
6457 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006458 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006459
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006460 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6461 if (SVI->hasOneUse()) {
6462 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6463 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00006464 if (isa<VectorType>(DestTy) &&
6465 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006466 SVI->getType()->getNumElements()) {
6467 CastInst *Tmp;
6468 // If either of the operands is a cast from CI.getType(), then
6469 // evaluating the shuffle in the casted destination's type will allow
6470 // us to eliminate at least one cast.
6471 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6472 Tmp->getOperand(0)->getType() == DestTy) ||
6473 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6474 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006475 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6476 SVI->getOperand(0), DestTy, &CI);
6477 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6478 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006479 // Return a new shuffle vector. Use the same element ID's, as we
6480 // know the vector types match #elts.
6481 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006482 }
6483 }
6484 }
6485 }
Chris Lattner260ab202002-04-18 17:39:14 +00006486 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006487}
6488
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006489/// GetSelectFoldableOperands - We want to turn code that looks like this:
6490/// %C = or %A, %B
6491/// %D = select %cond, %C, %A
6492/// into:
6493/// %C = select %cond, %B, 0
6494/// %D = or %A, %C
6495///
6496/// Assuming that the specified instruction is an operand to the select, return
6497/// a bitmask indicating which operands of this instruction are foldable if they
6498/// equal the other incoming value of the select.
6499///
6500static unsigned GetSelectFoldableOperands(Instruction *I) {
6501 switch (I->getOpcode()) {
6502 case Instruction::Add:
6503 case Instruction::Mul:
6504 case Instruction::And:
6505 case Instruction::Or:
6506 case Instruction::Xor:
6507 return 3; // Can fold through either operand.
6508 case Instruction::Sub: // Can only fold on the amount subtracted.
6509 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006510 case Instruction::LShr:
6511 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006512 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006513 default:
6514 return 0; // Cannot fold
6515 }
6516}
6517
6518/// GetSelectFoldableConstant - For the same transformation as the previous
6519/// function, return the identity constant that goes into the select.
6520static Constant *GetSelectFoldableConstant(Instruction *I) {
6521 switch (I->getOpcode()) {
6522 default: assert(0 && "This cannot happen!"); abort();
6523 case Instruction::Add:
6524 case Instruction::Sub:
6525 case Instruction::Or:
6526 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006527 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006528 case Instruction::LShr:
6529 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00006530 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006531 case Instruction::And:
6532 return ConstantInt::getAllOnesValue(I->getType());
6533 case Instruction::Mul:
6534 return ConstantInt::get(I->getType(), 1);
6535 }
6536}
6537
Chris Lattner411336f2005-01-19 21:50:18 +00006538/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6539/// have the same opcode and only one use each. Try to simplify this.
6540Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6541 Instruction *FI) {
6542 if (TI->getNumOperands() == 1) {
6543 // If this is a non-volatile load or a cast from the same type,
6544 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006545 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006546 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6547 return 0;
6548 } else {
6549 return 0; // unknown unary op.
6550 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006551
Chris Lattner411336f2005-01-19 21:50:18 +00006552 // Fold this by inserting a select from the input values.
6553 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6554 FI->getOperand(0), SI.getName()+".v");
6555 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006556 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6557 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006558 }
6559
Reid Spencer2341c222007-02-02 02:16:23 +00006560 // Only handle binary operators here.
6561 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006562 return 0;
6563
6564 // Figure out if the operations have any operands in common.
6565 Value *MatchOp, *OtherOpT, *OtherOpF;
6566 bool MatchIsOpZero;
6567 if (TI->getOperand(0) == FI->getOperand(0)) {
6568 MatchOp = TI->getOperand(0);
6569 OtherOpT = TI->getOperand(1);
6570 OtherOpF = FI->getOperand(1);
6571 MatchIsOpZero = true;
6572 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6573 MatchOp = TI->getOperand(1);
6574 OtherOpT = TI->getOperand(0);
6575 OtherOpF = FI->getOperand(0);
6576 MatchIsOpZero = false;
6577 } else if (!TI->isCommutative()) {
6578 return 0;
6579 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6580 MatchOp = TI->getOperand(0);
6581 OtherOpT = TI->getOperand(1);
6582 OtherOpF = FI->getOperand(0);
6583 MatchIsOpZero = true;
6584 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6585 MatchOp = TI->getOperand(1);
6586 OtherOpT = TI->getOperand(0);
6587 OtherOpF = FI->getOperand(1);
6588 MatchIsOpZero = true;
6589 } else {
6590 return 0;
6591 }
6592
6593 // If we reach here, they do have operations in common.
6594 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6595 OtherOpF, SI.getName()+".v");
6596 InsertNewInstBefore(NewSI, SI);
6597
6598 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6599 if (MatchIsOpZero)
6600 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6601 else
6602 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006603 }
Reid Spencer2f34b982007-02-02 14:41:37 +00006604 assert(0 && "Shouldn't get here");
6605 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00006606}
6607
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006608Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006609 Value *CondVal = SI.getCondition();
6610 Value *TrueVal = SI.getTrueValue();
6611 Value *FalseVal = SI.getFalseValue();
6612
6613 // select true, X, Y -> X
6614 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006615 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006616 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006617
6618 // select C, X, X -> X
6619 if (TrueVal == FalseVal)
6620 return ReplaceInstUsesWith(SI, TrueVal);
6621
Chris Lattner81a7a232004-10-16 18:11:37 +00006622 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6623 return ReplaceInstUsesWith(SI, FalseVal);
6624 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6625 return ReplaceInstUsesWith(SI, TrueVal);
6626 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6627 if (isa<Constant>(TrueVal))
6628 return ReplaceInstUsesWith(SI, TrueVal);
6629 else
6630 return ReplaceInstUsesWith(SI, FalseVal);
6631 }
6632
Reid Spencer542964f2007-01-11 18:21:29 +00006633 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006634 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006635 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006636 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006637 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006638 } else {
6639 // Change: A = select B, false, C --> A = and !B, C
6640 Value *NotCond =
6641 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6642 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006643 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006644 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006645 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006646 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006647 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006648 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006649 } else {
6650 // Change: A = select B, C, true --> A = or !B, C
6651 Value *NotCond =
6652 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6653 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006654 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006655 }
6656 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00006657 }
Chris Lattner1c631e82004-04-08 04:43:23 +00006658
Chris Lattner183b3362004-04-09 19:05:30 +00006659 // Selecting between two integer constants?
6660 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6661 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6662 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006663 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006664 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006665 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006666 // select C, 0, 1 -> cast !C to int
6667 Value *NotCond =
6668 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006669 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006670 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006671 }
Chris Lattner35167c32004-06-09 07:59:58 +00006672
Reid Spencer266e42b2006-12-23 06:05:41 +00006673 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006674
Reid Spencer266e42b2006-12-23 06:05:41 +00006675 // (x <s 0) ? -1 : 0 -> ashr x, 31
6676 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattner380c7e92006-09-20 04:44:59 +00006677 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6678 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6679 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006680 if (IC->isSignedPredicate())
Chris Lattner380c7e92006-09-20 04:44:59 +00006681 CanXForm = CmpCst->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006682 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006683 else {
6684 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006685 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006686 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006687 }
6688
6689 if (CanXForm) {
6690 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006691 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006692 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006693 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00006694 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
6695 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
6696 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00006697 InsertNewInstBefore(SRA, SI);
6698
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006699 // Finally, convert to the type of the select RHS. We figure out
6700 // if this requires a SExt, Trunc or BitCast based on the sizes.
6701 Instruction::CastOps opc = Instruction::BitCast;
6702 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6703 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6704 if (SRASize < SISize)
6705 opc = Instruction::SExt;
6706 else if (SRASize > SISize)
6707 opc = Instruction::Trunc;
6708 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006709 }
6710 }
6711
6712
6713 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006714 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006715 // non-constant value, eliminate this whole mess. This corresponds to
6716 // cases like this: ((X & 27) ? 27 : 0)
6717 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006718 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006719 cast<Constant>(IC->getOperand(1))->isNullValue())
6720 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6721 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006722 isa<ConstantInt>(ICA->getOperand(1)) &&
6723 (ICA->getOperand(1) == TrueValC ||
6724 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006725 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6726 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006727 // know whether we have a icmp_ne or icmp_eq and whether the
6728 // true or false val is the zero.
Chris Lattner35167c32004-06-09 07:59:58 +00006729 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006730 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006731 Value *V = ICA;
6732 if (ShouldNotVal)
6733 V = InsertNewInstBefore(BinaryOperator::create(
6734 Instruction::Xor, V, ICA->getOperand(1)), SI);
6735 return ReplaceInstUsesWith(SI, V);
6736 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006737 }
Chris Lattner533bc492004-03-30 19:37:13 +00006738 }
Chris Lattner623fba12004-04-10 22:21:27 +00006739
6740 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006741 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6742 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006743 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006744 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006745 return ReplaceInstUsesWith(SI, FalseVal);
6746 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006747 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006748 return ReplaceInstUsesWith(SI, TrueVal);
6749 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6750
Reid Spencer266e42b2006-12-23 06:05:41 +00006751 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006752 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006753 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006754 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006755 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006756 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6757 return ReplaceInstUsesWith(SI, TrueVal);
6758 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6759 }
6760 }
6761
6762 // See if we are selecting two values based on a comparison of the two values.
6763 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6764 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6765 // Transform (X == Y) ? X : Y -> Y
6766 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6767 return ReplaceInstUsesWith(SI, FalseVal);
6768 // Transform (X != Y) ? X : Y -> X
6769 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6770 return ReplaceInstUsesWith(SI, TrueVal);
6771 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6772
6773 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6774 // Transform (X == Y) ? Y : X -> X
6775 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6776 return ReplaceInstUsesWith(SI, FalseVal);
6777 // Transform (X != Y) ? Y : X -> Y
6778 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006779 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006780 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6781 }
6782 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006783
Chris Lattnera04c9042005-01-13 22:52:24 +00006784 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6785 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6786 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006787 Instruction *AddOp = 0, *SubOp = 0;
6788
Chris Lattner411336f2005-01-19 21:50:18 +00006789 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6790 if (TI->getOpcode() == FI->getOpcode())
6791 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6792 return IV;
6793
6794 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6795 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006796 if (TI->getOpcode() == Instruction::Sub &&
6797 FI->getOpcode() == Instruction::Add) {
6798 AddOp = FI; SubOp = TI;
6799 } else if (FI->getOpcode() == Instruction::Sub &&
6800 TI->getOpcode() == Instruction::Add) {
6801 AddOp = TI; SubOp = FI;
6802 }
6803
6804 if (AddOp) {
6805 Value *OtherAddOp = 0;
6806 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6807 OtherAddOp = AddOp->getOperand(1);
6808 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6809 OtherAddOp = AddOp->getOperand(0);
6810 }
6811
6812 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006813 // So at this point we know we have (Y -> OtherAddOp):
6814 // select C, (add X, Y), (sub X, Z)
6815 Value *NegVal; // Compute -Z
6816 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6817 NegVal = ConstantExpr::getNeg(C);
6818 } else {
6819 NegVal = InsertNewInstBefore(
6820 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006821 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006822
6823 Value *NewTrueOp = OtherAddOp;
6824 Value *NewFalseOp = NegVal;
6825 if (AddOp != TI)
6826 std::swap(NewTrueOp, NewFalseOp);
6827 Instruction *NewSel =
6828 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6829
6830 NewSel = InsertNewInstBefore(NewSel, SI);
6831 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006832 }
6833 }
6834 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006835
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006836 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00006837 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006838 // See the comment above GetSelectFoldableOperands for a description of the
6839 // transformation we are doing here.
6840 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6841 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6842 !isa<Constant>(FalseVal))
6843 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6844 unsigned OpToFold = 0;
6845 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6846 OpToFold = 1;
6847 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6848 OpToFold = 2;
6849 }
6850
6851 if (OpToFold) {
6852 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006853 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00006854 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006855 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006856 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006857 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6858 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006859 else {
6860 assert(0 && "Unknown instruction!!");
6861 }
6862 }
6863 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006864
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006865 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6866 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6867 !isa<Constant>(TrueVal))
6868 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6869 unsigned OpToFold = 0;
6870 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6871 OpToFold = 1;
6872 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6873 OpToFold = 2;
6874 }
6875
6876 if (OpToFold) {
6877 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006878 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00006879 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006880 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006881 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006882 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6883 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00006884 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006885 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006886 }
6887 }
6888 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006889
6890 if (BinaryOperator::isNot(CondVal)) {
6891 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6892 SI.setOperand(1, FalseVal);
6893 SI.setOperand(2, TrueVal);
6894 return &SI;
6895 }
6896
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006897 return 0;
6898}
6899
Chris Lattner82f2ef22006-03-06 20:18:44 +00006900/// GetKnownAlignment - If the specified pointer has an alignment that we can
6901/// determine, return it, otherwise return 0.
6902static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6903 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6904 unsigned Align = GV->getAlignment();
6905 if (Align == 0 && TD)
Chris Lattner945e4372007-02-14 05:52:17 +00006906 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00006907 return Align;
6908 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6909 unsigned Align = AI->getAlignment();
6910 if (Align == 0 && TD) {
6911 if (isa<AllocaInst>(AI))
Chris Lattner945e4372007-02-14 05:52:17 +00006912 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00006913 else if (isa<MallocInst>(AI)) {
6914 // Malloc returns maximally aligned memory.
Chris Lattner945e4372007-02-14 05:52:17 +00006915 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner50ee0e42007-01-20 22:35:55 +00006916 Align =
6917 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00006918 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner50ee0e42007-01-20 22:35:55 +00006919 Align =
6920 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00006921 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006922 }
6923 }
6924 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006925 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00006926 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006927 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00006928 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006929 if (isa<PointerType>(CI->getOperand(0)->getType()))
6930 return GetKnownAlignment(CI->getOperand(0), TD);
6931 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006932 } else if (isa<GetElementPtrInst>(V) ||
6933 (isa<ConstantExpr>(V) &&
6934 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6935 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006936 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6937 if (BaseAlignment == 0) return 0;
6938
6939 // If all indexes are zero, it is just the alignment of the base pointer.
6940 bool AllZeroOperands = true;
6941 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6942 if (!isa<Constant>(GEPI->getOperand(i)) ||
6943 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6944 AllZeroOperands = false;
6945 break;
6946 }
6947 if (AllZeroOperands)
6948 return BaseAlignment;
6949
6950 // Otherwise, if the base alignment is >= the alignment we expect for the
6951 // base pointer type, then we know that the resultant pointer is aligned at
6952 // least as much as its type requires.
6953 if (!TD) return 0;
6954
6955 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00006956 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattner945e4372007-02-14 05:52:17 +00006957 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006958 <= BaseAlignment) {
6959 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00006960 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattner945e4372007-02-14 05:52:17 +00006961 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00006962 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006963 return 0;
6964 }
6965 return 0;
6966}
6967
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006968
Chris Lattnerc66b2232006-01-13 20:11:04 +00006969/// visitCallInst - CallInst simplification. This mostly only handles folding
6970/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6971/// the heavy lifting.
6972///
Chris Lattner970c33a2003-06-19 17:00:31 +00006973Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006974 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6975 if (!II) return visitCallSite(&CI);
6976
Chris Lattner51ea1272004-02-28 05:22:00 +00006977 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6978 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006979 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006980 bool Changed = false;
6981
6982 // memmove/cpy/set of zero bytes is a noop.
6983 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6984 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6985
Chris Lattner00648e12004-10-12 04:52:52 +00006986 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006987 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006988 // Replace the instruction with just byte operations. We would
6989 // transform other cases to loads/stores, but we don't know if
6990 // alignment is sufficient.
6991 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006992 }
6993
Chris Lattner00648e12004-10-12 04:52:52 +00006994 // If we have a memmove and the source operation is a constant global,
6995 // then the source and dest pointers can't alias, so we can change this
6996 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006997 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006998 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6999 if (GVSrc->isConstant()) {
7000 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007001 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007002 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00007003 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00007004 Name = "llvm.memcpy.i32";
7005 else
7006 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00007007 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007008 CI.getCalledFunction()->getFunctionType());
7009 CI.setOperand(0, MemCpy);
7010 Changed = true;
7011 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007012 }
Chris Lattner00648e12004-10-12 04:52:52 +00007013
Chris Lattner82f2ef22006-03-06 20:18:44 +00007014 // If we can determine a pointer alignment that is bigger than currently
7015 // set, update the alignment.
7016 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7017 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7018 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7019 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007020 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007021 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007022 Changed = true;
7023 }
7024 } else if (isa<MemSetInst>(MI)) {
7025 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007026 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007027 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007028 Changed = true;
7029 }
7030 }
7031
Chris Lattnerc66b2232006-01-13 20:11:04 +00007032 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007033 } else {
7034 switch (II->getIntrinsicID()) {
7035 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007036 case Intrinsic::ppc_altivec_lvx:
7037 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007038 case Intrinsic::x86_sse_loadu_ps:
7039 case Intrinsic::x86_sse2_loadu_pd:
7040 case Intrinsic::x86_sse2_loadu_dq:
7041 // Turn PPC lvx -> load if the pointer is known aligned.
7042 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007043 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007044 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007045 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007046 return new LoadInst(Ptr);
7047 }
7048 break;
7049 case Intrinsic::ppc_altivec_stvx:
7050 case Intrinsic::ppc_altivec_stvxl:
7051 // Turn stvx -> store if the pointer is known aligned.
7052 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007053 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007054 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7055 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007056 return new StoreInst(II->getOperand(1), Ptr);
7057 }
7058 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007059 case Intrinsic::x86_sse_storeu_ps:
7060 case Intrinsic::x86_sse2_storeu_pd:
7061 case Intrinsic::x86_sse2_storeu_dq:
7062 case Intrinsic::x86_sse2_storel_dq:
7063 // Turn X86 storeu -> store if the pointer is known aligned.
7064 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7065 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007066 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7067 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007068 return new StoreInst(II->getOperand(2), Ptr);
7069 }
7070 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007071
7072 case Intrinsic::x86_sse_cvttss2si: {
7073 // These intrinsics only demands the 0th element of its input vector. If
7074 // we can simplify the input based on that, do so now.
7075 uint64_t UndefElts;
7076 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7077 UndefElts)) {
7078 II->setOperand(1, V);
7079 return II;
7080 }
7081 break;
7082 }
7083
Chris Lattnere79d2492006-04-06 19:19:17 +00007084 case Intrinsic::ppc_altivec_vperm:
7085 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007086 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007087 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7088
7089 // Check that all of the elements are integer constants or undefs.
7090 bool AllEltsOk = true;
7091 for (unsigned i = 0; i != 16; ++i) {
7092 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7093 !isa<UndefValue>(Mask->getOperand(i))) {
7094 AllEltsOk = false;
7095 break;
7096 }
7097 }
7098
7099 if (AllEltsOk) {
7100 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007101 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7102 II->getOperand(1), Mask->getType(), CI);
7103 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7104 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007105 Value *Result = UndefValue::get(Op0->getType());
7106
7107 // Only extract each element once.
7108 Value *ExtractedElts[32];
7109 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7110
7111 for (unsigned i = 0; i != 16; ++i) {
7112 if (isa<UndefValue>(Mask->getOperand(i)))
7113 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007114 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007115 Idx &= 31; // Match the hardware behavior.
7116
7117 if (ExtractedElts[Idx] == 0) {
7118 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007119 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007120 InsertNewInstBefore(Elt, CI);
7121 ExtractedElts[Idx] = Elt;
7122 }
7123
7124 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007125 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007126 InsertNewInstBefore(cast<Instruction>(Result), CI);
7127 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007128 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007129 }
7130 }
7131 break;
7132
Chris Lattner503221f2006-01-13 21:28:09 +00007133 case Intrinsic::stackrestore: {
7134 // If the save is right next to the restore, remove the restore. This can
7135 // happen when variable allocas are DCE'd.
7136 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7137 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7138 BasicBlock::iterator BI = SS;
7139 if (&*++BI == II)
7140 return EraseInstFromFunction(CI);
7141 }
7142 }
7143
7144 // If the stack restore is in a return/unwind block and if there are no
7145 // allocas or calls between the restore and the return, nuke the restore.
7146 TerminatorInst *TI = II->getParent()->getTerminator();
7147 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7148 BasicBlock::iterator BI = II;
7149 bool CannotRemove = false;
7150 for (++BI; &*BI != TI; ++BI) {
7151 if (isa<AllocaInst>(BI) ||
7152 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7153 CannotRemove = true;
7154 break;
7155 }
7156 }
7157 if (!CannotRemove)
7158 return EraseInstFromFunction(CI);
7159 }
7160 break;
7161 }
7162 }
Chris Lattner00648e12004-10-12 04:52:52 +00007163 }
7164
Chris Lattnerc66b2232006-01-13 20:11:04 +00007165 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007166}
7167
7168// InvokeInst simplification
7169//
7170Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007171 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007172}
7173
Chris Lattneraec3d942003-10-07 22:32:43 +00007174// visitCallSite - Improvements for call and invoke instructions.
7175//
7176Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007177 bool Changed = false;
7178
7179 // If the callee is a constexpr cast of a function, attempt to move the cast
7180 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007181 if (transformConstExprCastCall(CS)) return 0;
7182
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007183 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007184
Chris Lattner61d9d812005-05-13 07:09:09 +00007185 if (Function *CalleeF = dyn_cast<Function>(Callee))
7186 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7187 Instruction *OldCall = CS.getInstruction();
7188 // If the call and callee calling conventions don't match, this call must
7189 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007190 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007191 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007192 if (!OldCall->use_empty())
7193 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7194 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7195 return EraseInstFromFunction(*OldCall);
7196 return 0;
7197 }
7198
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007199 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7200 // This instruction is not reachable, just remove it. We insert a store to
7201 // undef so that we know that this code is not reachable, despite the fact
7202 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007203 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007204 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007205 CS.getInstruction());
7206
7207 if (!CS.getInstruction()->use_empty())
7208 CS.getInstruction()->
7209 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7210
7211 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7212 // Don't break the CFG, insert a dummy cond branch.
7213 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007214 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007215 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007216 return EraseInstFromFunction(*CS.getInstruction());
7217 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007218
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007219 const PointerType *PTy = cast<PointerType>(Callee->getType());
7220 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7221 if (FTy->isVarArg()) {
7222 // See if we can optimize any arguments passed through the varargs area of
7223 // the call.
7224 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7225 E = CS.arg_end(); I != E; ++I)
7226 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7227 // If this cast does not effect the value passed through the varargs
7228 // area, we can eliminate the use of the cast.
7229 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007230 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007231 *I = Op;
7232 Changed = true;
7233 }
7234 }
7235 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007236
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007237 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007238}
7239
Chris Lattner970c33a2003-06-19 17:00:31 +00007240// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7241// attempt to move the cast to the arguments of the call/invoke.
7242//
7243bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7244 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7245 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007246 if (CE->getOpcode() != Instruction::BitCast ||
7247 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007248 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007249 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007250 Instruction *Caller = CS.getInstruction();
7251
7252 // Okay, this is a cast from a function to a different type. Unless doing so
7253 // would cause a type conversion of one of our arguments, change this call to
7254 // be a direct call with arguments casted to the appropriate types.
7255 //
7256 const FunctionType *FT = Callee->getFunctionType();
7257 const Type *OldRetTy = Caller->getType();
7258
Chris Lattner1f7942f2004-01-14 06:06:08 +00007259 // Check to see if we are changing the return type...
7260 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00007261 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007262 OldRetTy != FT->getReturnType() &&
7263 // Conversion is ok if changing from pointer to int of same size.
7264 !(isa<PointerType>(FT->getReturnType()) &&
7265 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007266 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007267
7268 // If the callsite is an invoke instruction, and the return value is used by
7269 // a PHI node in a successor, we cannot change the return type of the call
7270 // because there is no place to put the cast instruction (without breaking
7271 // the critical edge). Bail out in this case.
7272 if (!Caller->use_empty())
7273 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7274 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7275 UI != E; ++UI)
7276 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7277 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007278 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007279 return false;
7280 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007281
7282 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7283 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007284
Chris Lattner970c33a2003-06-19 17:00:31 +00007285 CallSite::arg_iterator AI = CS.arg_begin();
7286 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7287 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007288 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007289 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007290 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007291 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007292 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00007293 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007294 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7295 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7296 && c->getSExtValue() > 0);
Reid Spencer5301e7c2007-01-30 20:08:39 +00007297 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007298 }
7299
7300 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00007301 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00007302 return false; // Do not delete arguments unless we have a function body...
7303
7304 // Okay, we decided that this is a safe thing to do: go ahead and start
7305 // inserting cast instructions as necessary...
7306 std::vector<Value*> Args;
7307 Args.reserve(NumActualArgs);
7308
7309 AI = CS.arg_begin();
7310 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7311 const Type *ParamTy = FT->getParamType(i);
7312 if ((*AI)->getType() == ParamTy) {
7313 Args.push_back(*AI);
7314 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007315 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007316 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007317 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007318 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007319 }
7320 }
7321
7322 // If the function takes more arguments than the call was taking, add them
7323 // now...
7324 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7325 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7326
7327 // If we are removing arguments to the function, emit an obnoxious warning...
7328 if (FT->getNumParams() < NumActualArgs)
7329 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007330 cerr << "WARNING: While resolving call to function '"
7331 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007332 } else {
7333 // Add all of the arguments in their promoted form to the arg list...
7334 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7335 const Type *PTy = getPromotedType((*AI)->getType());
7336 if (PTy != (*AI)->getType()) {
7337 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007338 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7339 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007340 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007341 InsertNewInstBefore(Cast, *Caller);
7342 Args.push_back(Cast);
7343 } else {
7344 Args.push_back(*AI);
7345 }
7346 }
7347 }
7348
7349 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00007350 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00007351
7352 Instruction *NC;
7353 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007354 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007355 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007356 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007357 } else {
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007358 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007359 if (cast<CallInst>(Caller)->isTailCall())
7360 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007361 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007362 }
7363
Chris Lattner6e0123b2007-02-11 01:23:03 +00007364 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00007365 Value *NV = NC;
7366 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7367 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007368 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007369 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7370 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007371 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007372
7373 // If this is an invoke instruction, we should insert it after the first
7374 // non-phi, instruction in the normal successor block.
7375 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7376 BasicBlock::iterator I = II->getNormalDest()->begin();
7377 while (isa<PHINode>(I)) ++I;
7378 InsertNewInstBefore(NC, *I);
7379 } else {
7380 // Otherwise, it's a call, just insert cast right after the call instr
7381 InsertNewInstBefore(NC, *Caller);
7382 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007383 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007384 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007385 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007386 }
7387 }
7388
7389 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7390 Caller->replaceAllUsesWith(NV);
7391 Caller->getParent()->getInstList().erase(Caller);
7392 removeFromWorkList(Caller);
7393 return true;
7394}
7395
Chris Lattnercadac0c2006-11-01 04:51:18 +00007396/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7397/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7398/// and a single binop.
7399Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7400 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00007401 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7402 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007403 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007404 Value *LHSVal = FirstInst->getOperand(0);
7405 Value *RHSVal = FirstInst->getOperand(1);
7406
7407 const Type *LHSType = LHSVal->getType();
7408 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007409
7410 // Scan to see if all operands are the same opcode, all have one use, and all
7411 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007412 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007413 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007414 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007415 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007416 // types or GEP's with different index types.
7417 I->getOperand(0)->getType() != LHSType ||
7418 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007419 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007420
7421 // If they are CmpInst instructions, check their predicates
7422 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7423 if (cast<CmpInst>(I)->getPredicate() !=
7424 cast<CmpInst>(FirstInst)->getPredicate())
7425 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007426
7427 // Keep track of which operand needs a phi node.
7428 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7429 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007430 }
7431
Chris Lattner4f218d52006-11-08 19:42:28 +00007432 // Otherwise, this is safe to transform, determine if it is profitable.
7433
7434 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7435 // Indexes are often folded into load/store instructions, so we don't want to
7436 // hide them behind a phi.
7437 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7438 return 0;
7439
Chris Lattnercadac0c2006-11-01 04:51:18 +00007440 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007441 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007442 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007443 if (LHSVal == 0) {
7444 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7445 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7446 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007447 InsertNewInstBefore(NewLHS, PN);
7448 LHSVal = NewLHS;
7449 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007450
7451 if (RHSVal == 0) {
7452 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7453 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7454 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007455 InsertNewInstBefore(NewRHS, PN);
7456 RHSVal = NewRHS;
7457 }
7458
Chris Lattnercd62f112006-11-08 19:29:23 +00007459 // Add all operands to the new PHIs.
7460 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7461 if (NewLHS) {
7462 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7463 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7464 }
7465 if (NewRHS) {
7466 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7467 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7468 }
7469 }
7470
Chris Lattnercadac0c2006-11-01 04:51:18 +00007471 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007472 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007473 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7474 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7475 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007476 else {
7477 assert(isa<GetElementPtrInst>(FirstInst));
7478 return new GetElementPtrInst(LHSVal, RHSVal);
7479 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007480}
7481
Chris Lattner14f82c72006-11-01 07:13:54 +00007482/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7483/// of the block that defines it. This means that it must be obvious the value
7484/// of the load is not changed from the point of the load to the end of the
7485/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00007486///
7487/// Finally, it is safe, but not profitable, to sink a load targetting a
7488/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7489/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00007490static bool isSafeToSinkLoad(LoadInst *L) {
7491 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7492
7493 for (++BBI; BBI != E; ++BBI)
7494 if (BBI->mayWriteToMemory())
7495 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00007496
7497 // Check for non-address taken alloca. If not address-taken already, it isn't
7498 // profitable to do this xform.
7499 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7500 bool isAddressTaken = false;
7501 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7502 UI != E; ++UI) {
7503 if (isa<LoadInst>(UI)) continue;
7504 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7505 // If storing TO the alloca, then the address isn't taken.
7506 if (SI->getOperand(1) == AI) continue;
7507 }
7508 isAddressTaken = true;
7509 break;
7510 }
7511
7512 if (!isAddressTaken)
7513 return false;
7514 }
7515
Chris Lattner14f82c72006-11-01 07:13:54 +00007516 return true;
7517}
7518
Chris Lattner970c33a2003-06-19 17:00:31 +00007519
Chris Lattner7515cab2004-11-14 19:13:23 +00007520// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7521// operator and they all are only used by the PHI, PHI together their
7522// inputs, and do the operation once, to the result of the PHI.
7523Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7524 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7525
7526 // Scan the instruction, looking for input operations that can be folded away.
7527 // If all input operands to the phi are the same instruction (e.g. a cast from
7528 // the same type or "+42") we can pull the operation through the PHI, reducing
7529 // code size and simplifying code.
7530 Constant *ConstantOp = 0;
7531 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007532 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007533 if (isa<CastInst>(FirstInst)) {
7534 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00007535 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007536 // Can fold binop, compare or shift here if the RHS is a constant,
7537 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007538 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007539 if (ConstantOp == 0)
7540 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007541 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7542 isVolatile = LI->isVolatile();
7543 // We can't sink the load if the loaded value could be modified between the
7544 // load and the PHI.
7545 if (LI->getParent() != PN.getIncomingBlock(0) ||
7546 !isSafeToSinkLoad(LI))
7547 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007548 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007549 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007550 return FoldPHIArgBinOpIntoPHI(PN);
7551 // Can't handle general GEPs yet.
7552 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007553 } else {
7554 return 0; // Cannot fold this operation.
7555 }
7556
7557 // Check to see if all arguments are the same operation.
7558 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7559 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7560 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007561 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007562 return 0;
7563 if (CastSrcTy) {
7564 if (I->getOperand(0)->getType() != CastSrcTy)
7565 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007566 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007567 // We can't sink the load if the loaded value could be modified between
7568 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007569 if (LI->isVolatile() != isVolatile ||
7570 LI->getParent() != PN.getIncomingBlock(i) ||
7571 !isSafeToSinkLoad(LI))
7572 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007573 } else if (I->getOperand(1) != ConstantOp) {
7574 return 0;
7575 }
7576 }
7577
7578 // Okay, they are all the same operation. Create a new PHI node of the
7579 // correct type, and PHI together all of the LHS's of the instructions.
7580 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7581 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007582 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007583
7584 Value *InVal = FirstInst->getOperand(0);
7585 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007586
7587 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007588 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7589 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7590 if (NewInVal != InVal)
7591 InVal = 0;
7592 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7593 }
7594
7595 Value *PhiVal;
7596 if (InVal) {
7597 // The new PHI unions all of the same values together. This is really
7598 // common, so we handle it intelligently here for compile-time speed.
7599 PhiVal = InVal;
7600 delete NewPN;
7601 } else {
7602 InsertNewInstBefore(NewPN, PN);
7603 PhiVal = NewPN;
7604 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007605
Chris Lattner7515cab2004-11-14 19:13:23 +00007606 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007607 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7608 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007609 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007610 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007611 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007612 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007613 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7614 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7615 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007616 else
Reid Spencer2341c222007-02-02 02:16:23 +00007617 assert(0 && "Unknown operation");
Chris Lattner7515cab2004-11-14 19:13:23 +00007618}
Chris Lattner48a44f72002-05-02 17:06:02 +00007619
Chris Lattner71536432005-01-17 05:10:15 +00007620/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7621/// that is dead.
7622static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7623 if (PN->use_empty()) return true;
7624 if (!PN->hasOneUse()) return false;
7625
7626 // Remember this node, and if we find the cycle, return.
7627 if (!PotentiallyDeadPHIs.insert(PN).second)
7628 return true;
7629
7630 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7631 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007632
Chris Lattner71536432005-01-17 05:10:15 +00007633 return false;
7634}
7635
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007636// PHINode simplification
7637//
Chris Lattner113f4f42002-06-25 16:13:24 +00007638Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007639 // If LCSSA is around, don't mess with Phi nodes
7640 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007641
Owen Andersonae8aa642006-07-10 22:03:18 +00007642 if (Value *V = PN.hasConstantValue())
7643 return ReplaceInstUsesWith(PN, V);
7644
Owen Andersonae8aa642006-07-10 22:03:18 +00007645 // If all PHI operands are the same operation, pull them through the PHI,
7646 // reducing code size.
7647 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7648 PN.getIncomingValue(0)->hasOneUse())
7649 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7650 return Result;
7651
7652 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7653 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7654 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007655 if (PN.hasOneUse()) {
7656 Instruction *PHIUser = cast<Instruction>(PN.use_back());
7657 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Owen Andersonae8aa642006-07-10 22:03:18 +00007658 std::set<PHINode*> PotentiallyDeadPHIs;
7659 PotentiallyDeadPHIs.insert(&PN);
7660 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7661 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7662 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007663
7664 // If this phi has a single use, and if that use just computes a value for
7665 // the next iteration of a loop, delete the phi. This occurs with unused
7666 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7667 // common case here is good because the only other things that catch this
7668 // are induction variable analysis (sometimes) and ADCE, which is only run
7669 // late.
7670 if (PHIUser->hasOneUse() &&
7671 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7672 PHIUser->use_back() == &PN) {
7673 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7674 }
7675 }
Owen Andersonae8aa642006-07-10 22:03:18 +00007676
Chris Lattner91daeb52003-12-19 05:58:40 +00007677 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007678}
7679
Reid Spencer13bc5d72006-12-12 09:18:51 +00007680static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7681 Instruction *InsertPoint,
7682 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00007683 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7684 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007685 // We must cast correctly to the pointer type. Ensure that we
7686 // sign extend the integer value if it is smaller as this is
7687 // used for address computation.
7688 Instruction::CastOps opcode =
7689 (VTySize < PtrSize ? Instruction::SExt :
7690 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7691 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007692}
7693
Chris Lattner48a44f72002-05-02 17:06:02 +00007694
Chris Lattner113f4f42002-06-25 16:13:24 +00007695Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007696 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007697 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007698 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007699 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007700 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007701
Chris Lattner81a7a232004-10-16 18:11:37 +00007702 if (isa<UndefValue>(GEP.getOperand(0)))
7703 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7704
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007705 bool HasZeroPointerIndex = false;
7706 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7707 HasZeroPointerIndex = C->isNullValue();
7708
7709 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007710 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007711
Chris Lattner69193f92004-04-05 01:30:19 +00007712 // Eliminate unneeded casts for indices.
7713 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007714 gep_type_iterator GTI = gep_type_begin(GEP);
7715 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7716 if (isa<SequentialType>(*GTI)) {
7717 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00007718 if (CI->getOpcode() == Instruction::ZExt ||
7719 CI->getOpcode() == Instruction::SExt) {
7720 const Type *SrcTy = CI->getOperand(0)->getType();
7721 // We can eliminate a cast from i32 to i64 iff the target
7722 // is a 32-bit pointer target.
7723 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7724 MadeChange = true;
7725 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00007726 }
7727 }
7728 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007729 // If we are using a wider index than needed for this platform, shrink it
7730 // to what we need. If the incoming value needs a cast instruction,
7731 // insert it. This explicit cast can make subsequent optimizations more
7732 // obvious.
7733 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007734 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007735 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007736 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007737 MadeChange = true;
7738 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007739 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7740 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007741 GEP.setOperand(i, Op);
7742 MadeChange = true;
7743 }
Chris Lattner69193f92004-04-05 01:30:19 +00007744 }
7745 if (MadeChange) return &GEP;
7746
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007747 // Combine Indices - If the source pointer to this getelementptr instruction
7748 // is a getelementptr instruction, combine the indices of the two
7749 // getelementptr instructions into a single instruction.
7750 //
Chris Lattneraf6094f2007-02-15 22:48:32 +00007751 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007752 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +00007753 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007754
7755 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007756 // Note that if our source is a gep chain itself that we wait for that
7757 // chain to be resolved before we perform this transformation. This
7758 // avoids us creating a TON of code in some cases.
7759 //
7760 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7761 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7762 return 0; // Wait until our source is folded to completion.
7763
Chris Lattneraf6094f2007-02-15 22:48:32 +00007764 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007765
7766 // Find out whether the last index in the source GEP is a sequential idx.
7767 bool EndsWithSequential = false;
7768 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7769 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007770 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007771
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007772 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007773 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007774 // Replace: gep (gep %P, long B), long A, ...
7775 // With: T = long A+B; gep %P, T, ...
7776 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007777 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007778 if (SO1 == Constant::getNullValue(SO1->getType())) {
7779 Sum = GO1;
7780 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7781 Sum = SO1;
7782 } else {
7783 // If they aren't the same type, convert both to an integer of the
7784 // target's pointer size.
7785 if (SO1->getType() != GO1->getType()) {
7786 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007787 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007788 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007789 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007790 } else {
7791 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007792 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007793 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007794 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007795
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007796 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007797 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007798 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007799 } else {
7800 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007801 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7802 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007803 }
7804 }
7805 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007806 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7807 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7808 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007809 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7810 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007811 }
Chris Lattner69193f92004-04-05 01:30:19 +00007812 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007813
7814 // Recycle the GEP we already have if possible.
7815 if (SrcGEPOperands.size() == 2) {
7816 GEP.setOperand(0, SrcGEPOperands[0]);
7817 GEP.setOperand(1, Sum);
7818 return &GEP;
7819 } else {
7820 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7821 SrcGEPOperands.end()-1);
7822 Indices.push_back(Sum);
7823 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7824 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007825 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007826 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007827 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007828 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007829 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7830 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007831 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7832 }
7833
7834 if (!Indices.empty())
Chris Lattnera7315132007-02-12 22:56:41 +00007835 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
7836 Indices.size(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007837
Chris Lattner5f667a62004-05-07 22:09:22 +00007838 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007839 // GEP of global variable. If all of the indices for this GEP are
7840 // constants, we can promote this to a constexpr instead of an instruction.
7841
7842 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00007843 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007844 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7845 for (; I != E && isa<Constant>(*I); ++I)
7846 Indices.push_back(cast<Constant>(*I));
7847
7848 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00007849 Constant *CE = ConstantExpr::getGetElementPtr(GV,
7850 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007851
7852 // Replace all uses of the GEP with the new constexpr...
7853 return ReplaceInstUsesWith(GEP, CE);
7854 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007855 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00007856 if (!isa<PointerType>(X->getType())) {
7857 // Not interesting. Source pointer must be a cast from pointer.
7858 } else if (HasZeroPointerIndex) {
7859 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7860 // into : GEP [10 x ubyte]* X, long 0, ...
7861 //
7862 // This occurs when the program declares an array extern like "int X[];"
7863 //
7864 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7865 const PointerType *XTy = cast<PointerType>(X->getType());
7866 if (const ArrayType *XATy =
7867 dyn_cast<ArrayType>(XTy->getElementType()))
7868 if (const ArrayType *CATy =
7869 dyn_cast<ArrayType>(CPTy->getElementType()))
7870 if (CATy->getElementType() == XATy->getElementType()) {
7871 // At this point, we know that the cast source type is a pointer
7872 // to an array of the same type as the destination pointer
7873 // array. Because the array type is never stepped over (there
7874 // is a leading zero) we can fold the cast into this GEP.
7875 GEP.setOperand(0, X);
7876 return &GEP;
7877 }
7878 } else if (GEP.getNumOperands() == 2) {
7879 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007880 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7881 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007882 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7883 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7884 if (isa<ArrayType>(SrcElTy) &&
7885 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7886 TD->getTypeSize(ResElTy)) {
7887 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00007888 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00007889 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007890 // V and GEP are both pointer types --> BitCast
7891 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007892 }
Chris Lattner2a893292005-09-13 18:36:04 +00007893
7894 // Transform things like:
7895 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7896 // (where tmp = 8*tmp2) into:
7897 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7898
7899 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00007900 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00007901 uint64_t ArrayEltSize =
7902 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7903
7904 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7905 // allow either a mul, shift, or constant here.
7906 Value *NewIdx = 0;
7907 ConstantInt *Scale = 0;
7908 if (ArrayEltSize == 1) {
7909 NewIdx = GEP.getOperand(1);
7910 Scale = ConstantInt::get(NewIdx->getType(), 1);
7911 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007912 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007913 Scale = CI;
7914 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7915 if (Inst->getOpcode() == Instruction::Shl &&
7916 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007917 unsigned ShAmt =
7918 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007919 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007920 NewIdx = Inst->getOperand(0);
7921 } else if (Inst->getOpcode() == Instruction::Mul &&
7922 isa<ConstantInt>(Inst->getOperand(1))) {
7923 Scale = cast<ConstantInt>(Inst->getOperand(1));
7924 NewIdx = Inst->getOperand(0);
7925 }
7926 }
7927
7928 // If the index will be to exactly the right offset with the scale taken
7929 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007930 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007931 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007932 Scale = ConstantInt::get(Scale->getType(),
7933 Scale->getZExtValue() / ArrayEltSize);
7934 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007935 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7936 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00007937 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7938 NewIdx = InsertNewInstBefore(Sc, GEP);
7939 }
7940
7941 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007942 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00007943 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00007944 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007945 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7946 // The NewGEP must be pointer typed, so must the old one -> BitCast
7947 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00007948 }
7949 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007950 }
Chris Lattnerca081252001-12-14 16:52:21 +00007951 }
7952
Chris Lattnerca081252001-12-14 16:52:21 +00007953 return 0;
7954}
7955
Chris Lattner1085bdf2002-11-04 16:18:53 +00007956Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7957 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7958 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007959 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7960 const Type *NewTy =
7961 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007962 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007963
7964 // Create and insert the replacement instruction...
7965 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007966 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007967 else {
7968 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007969 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007970 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007971
7972 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007973
Chris Lattner1085bdf2002-11-04 16:18:53 +00007974 // Scan to the end of the allocation instructions, to skip over a block of
7975 // allocas if possible...
7976 //
7977 BasicBlock::iterator It = New;
7978 while (isa<AllocationInst>(*It)) ++It;
7979
7980 // Now that I is pointing to the first non-allocation-inst in the block,
7981 // insert our getelementptr instruction...
7982 //
Reid Spencerc635f472006-12-31 05:48:39 +00007983 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00007984 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7985 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007986
7987 // Now make everything use the getelementptr instead of the original
7988 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007989 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007990 } else if (isa<UndefValue>(AI.getArraySize())) {
7991 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007992 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007993
7994 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7995 // Note that we only do this for alloca's, because malloc should allocate and
7996 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007997 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007998 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007999 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8000
Chris Lattner1085bdf2002-11-04 16:18:53 +00008001 return 0;
8002}
8003
Chris Lattner8427bff2003-12-07 01:24:23 +00008004Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8005 Value *Op = FI.getOperand(0);
8006
8007 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8008 if (CastInst *CI = dyn_cast<CastInst>(Op))
8009 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8010 FI.setOperand(0, CI->getOperand(0));
8011 return &FI;
8012 }
8013
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008014 // free undef -> unreachable.
8015 if (isa<UndefValue>(Op)) {
8016 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008017 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008018 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008019 return EraseInstFromFunction(FI);
8020 }
8021
Chris Lattnerf3a36602004-02-28 04:57:37 +00008022 // If we have 'free null' delete the instruction. This can happen in stl code
8023 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008024 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008025 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00008026
Chris Lattner8427bff2003-12-07 01:24:23 +00008027 return 0;
8028}
8029
8030
Chris Lattner72684fe2005-01-31 05:51:45 +00008031/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008032static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8033 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008034 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008035
8036 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008037 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008038 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008039
Reid Spencer31a4ef42007-01-22 05:51:25 +00008040 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008041 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008042 // If the source is an array, the code below will not succeed. Check to
8043 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8044 // constants.
8045 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8046 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8047 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008048 Value *Idxs[2];
8049 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8050 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008051 SrcTy = cast<PointerType>(CastOp->getType());
8052 SrcPTy = SrcTy->getElementType();
8053 }
8054
Reid Spencer31a4ef42007-01-22 05:51:25 +00008055 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008056 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008057 // Do not allow turning this into a load of an integer, which is then
8058 // casted to a pointer, this pessimizes pointer analysis a lot.
8059 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008060 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8061 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008062
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008063 // Okay, we are casting from one integer or pointer type to another of
8064 // the same size. Instead of casting the pointer before the load, cast
8065 // the result of the loaded value.
8066 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8067 CI->getName(),
8068 LI.isVolatile()),LI);
8069 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008070 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008071 }
Chris Lattner35e24772004-07-13 01:49:43 +00008072 }
8073 }
8074 return 0;
8075}
8076
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008077/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008078/// from this value cannot trap. If it is not obviously safe to load from the
8079/// specified pointer, we do a quick local scan of the basic block containing
8080/// ScanFrom, to determine if the address is already accessed.
8081static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8082 // If it is an alloca or global variable, it is always safe to load from.
8083 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8084
8085 // Otherwise, be a little bit agressive by scanning the local block where we
8086 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008087 // from/to. If so, the previous load or store would have already trapped,
8088 // so there is no harm doing an extra load (also, CSE will later eliminate
8089 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008090 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8091
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008092 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008093 --BBI;
8094
8095 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8096 if (LI->getOperand(0) == V) return true;
8097 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8098 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008099
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008100 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008101 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008102}
8103
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008104Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8105 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008106
Chris Lattnera9d84e32005-05-01 04:24:53 +00008107 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008108 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008109 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8110 return Res;
8111
8112 // None of the following transforms are legal for volatile loads.
8113 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008114
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008115 if (&LI.getParent()->front() != &LI) {
8116 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008117 // If the instruction immediately before this is a store to the same
8118 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008119 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8120 if (SI->getOperand(1) == LI.getOperand(0))
8121 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008122 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8123 if (LIB->getOperand(0) == LI.getOperand(0))
8124 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008125 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008126
8127 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8128 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8129 isa<UndefValue>(GEPI->getOperand(0))) {
8130 // Insert a new store to null instruction before the load to indicate
8131 // that this code is not reachable. We do this instead of inserting
8132 // an unreachable instruction directly because we cannot modify the
8133 // CFG.
8134 new StoreInst(UndefValue::get(LI.getType()),
8135 Constant::getNullValue(Op->getType()), &LI);
8136 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8137 }
8138
Chris Lattner81a7a232004-10-16 18:11:37 +00008139 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008140 // load null/undef -> undef
8141 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008142 // Insert a new store to null instruction before the load to indicate that
8143 // this code is not reachable. We do this instead of inserting an
8144 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008145 new StoreInst(UndefValue::get(LI.getType()),
8146 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008147 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008148 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008149
Chris Lattner81a7a232004-10-16 18:11:37 +00008150 // Instcombine load (constant global) into the value loaded.
8151 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008152 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00008153 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008154
Chris Lattner81a7a232004-10-16 18:11:37 +00008155 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8156 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8157 if (CE->getOpcode() == Instruction::GetElementPtr) {
8158 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008159 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008160 if (Constant *V =
8161 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008162 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008163 if (CE->getOperand(0)->isNullValue()) {
8164 // Insert a new store to null instruction before the load to indicate
8165 // that this code is not reachable. We do this instead of inserting
8166 // an unreachable instruction directly because we cannot modify the
8167 // CFG.
8168 new StoreInst(UndefValue::get(LI.getType()),
8169 Constant::getNullValue(Op->getType()), &LI);
8170 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8171 }
8172
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008173 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008174 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8175 return Res;
8176 }
8177 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008178
Chris Lattnera9d84e32005-05-01 04:24:53 +00008179 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008180 // Change select and PHI nodes to select values instead of addresses: this
8181 // helps alias analysis out a lot, allows many others simplifications, and
8182 // exposes redundancy in the code.
8183 //
8184 // Note that we cannot do the transformation unless we know that the
8185 // introduced loads cannot trap! Something like this is valid as long as
8186 // the condition is always false: load (select bool %C, int* null, int* %G),
8187 // but it would not be valid if we transformed it to load from null
8188 // unconditionally.
8189 //
8190 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8191 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008192 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8193 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008194 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008195 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008196 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008197 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008198 return new SelectInst(SI->getCondition(), V1, V2);
8199 }
8200
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008201 // load (select (cond, null, P)) -> load P
8202 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8203 if (C->isNullValue()) {
8204 LI.setOperand(0, SI->getOperand(2));
8205 return &LI;
8206 }
8207
8208 // load (select (cond, P, null)) -> load P
8209 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8210 if (C->isNullValue()) {
8211 LI.setOperand(0, SI->getOperand(1));
8212 return &LI;
8213 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008214 }
8215 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008216 return 0;
8217}
8218
Reid Spencere928a152007-01-19 21:20:31 +00008219/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00008220/// when possible.
8221static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8222 User *CI = cast<User>(SI.getOperand(1));
8223 Value *CastOp = CI->getOperand(0);
8224
8225 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8226 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8227 const Type *SrcPTy = SrcTy->getElementType();
8228
Reid Spencer31a4ef42007-01-22 05:51:25 +00008229 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008230 // If the source is an array, the code below will not succeed. Check to
8231 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8232 // constants.
8233 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8234 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8235 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008236 Value* Idxs[2];
8237 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8238 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00008239 SrcTy = cast<PointerType>(CastOp->getType());
8240 SrcPTy = SrcTy->getElementType();
8241 }
8242
Reid Spencer9a4bed02007-01-20 23:35:48 +00008243 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8244 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8245 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008246
8247 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00008248 // the same size. Instead of casting the pointer before
8249 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00008250 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008251 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00008252 Instruction::CastOps opcode = Instruction::BitCast;
8253 const Type* CastSrcTy = SIOp0->getType();
8254 const Type* CastDstTy = SrcPTy;
8255 if (isa<PointerType>(CastDstTy)) {
8256 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008257 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00008258 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008259 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008260 opcode = Instruction::PtrToInt;
8261 }
8262 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00008263 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008264 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008265 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00008266 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8267 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008268 return new StoreInst(NewCast, CastOp);
8269 }
8270 }
8271 }
8272 return 0;
8273}
8274
Chris Lattner31f486c2005-01-31 05:36:43 +00008275Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8276 Value *Val = SI.getOperand(0);
8277 Value *Ptr = SI.getOperand(1);
8278
8279 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008280 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008281 ++NumCombined;
8282 return 0;
8283 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00008284
8285 // If the RHS is an alloca with a single use, zapify the store, making the
8286 // alloca dead.
8287 if (Ptr->hasOneUse()) {
8288 if (isa<AllocaInst>(Ptr)) {
8289 EraseInstFromFunction(SI);
8290 ++NumCombined;
8291 return 0;
8292 }
8293
8294 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8295 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8296 GEP->getOperand(0)->hasOneUse()) {
8297 EraseInstFromFunction(SI);
8298 ++NumCombined;
8299 return 0;
8300 }
8301 }
Chris Lattner31f486c2005-01-31 05:36:43 +00008302
Chris Lattner5997cf92006-02-08 03:25:32 +00008303 // Do really simple DSE, to catch cases where there are several consequtive
8304 // stores to the same location, separated by a few arithmetic operations. This
8305 // situation often occurs with bitfield accesses.
8306 BasicBlock::iterator BBI = &SI;
8307 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8308 --ScanInsts) {
8309 --BBI;
8310
8311 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8312 // Prev store isn't volatile, and stores to the same location?
8313 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8314 ++NumDeadStore;
8315 ++BBI;
8316 EraseInstFromFunction(*PrevSI);
8317 continue;
8318 }
8319 break;
8320 }
8321
Chris Lattnerdab43b22006-05-26 19:19:20 +00008322 // If this is a load, we have to stop. However, if the loaded value is from
8323 // the pointer we're loading and is producing the pointer we're storing,
8324 // then *this* store is dead (X = load P; store X -> P).
8325 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8326 if (LI == Val && LI->getOperand(0) == Ptr) {
8327 EraseInstFromFunction(SI);
8328 ++NumCombined;
8329 return 0;
8330 }
8331 // Otherwise, this is a load from some other location. Stores before it
8332 // may not be dead.
8333 break;
8334 }
8335
Chris Lattner5997cf92006-02-08 03:25:32 +00008336 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008337 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008338 break;
8339 }
8340
8341
8342 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008343
8344 // store X, null -> turns into 'unreachable' in SimplifyCFG
8345 if (isa<ConstantPointerNull>(Ptr)) {
8346 if (!isa<UndefValue>(Val)) {
8347 SI.setOperand(0, UndefValue::get(Val->getType()));
8348 if (Instruction *U = dyn_cast<Instruction>(Val))
8349 WorkList.push_back(U); // Dropped a use.
8350 ++NumCombined;
8351 }
8352 return 0; // Do not modify these!
8353 }
8354
8355 // store undef, Ptr -> noop
8356 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008357 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008358 ++NumCombined;
8359 return 0;
8360 }
8361
Chris Lattner72684fe2005-01-31 05:51:45 +00008362 // If the pointer destination is a cast, see if we can fold the cast into the
8363 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008364 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008365 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8366 return Res;
8367 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008368 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008369 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8370 return Res;
8371
Chris Lattner219175c2005-09-12 23:23:25 +00008372
8373 // If this store is the last instruction in the basic block, and if the block
8374 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008375 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008376 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8377 if (BI->isUnconditional()) {
8378 // Check to see if the successor block has exactly two incoming edges. If
8379 // so, see if the other predecessor contains a store to the same location.
8380 // if so, insert a PHI node (if needed) and move the stores down.
8381 BasicBlock *Dest = BI->getSuccessor(0);
8382
8383 pred_iterator PI = pred_begin(Dest);
8384 BasicBlock *Other = 0;
8385 if (*PI != BI->getParent())
8386 Other = *PI;
8387 ++PI;
8388 if (PI != pred_end(Dest)) {
8389 if (*PI != BI->getParent())
8390 if (Other)
8391 Other = 0;
8392 else
8393 Other = *PI;
8394 if (++PI != pred_end(Dest))
8395 Other = 0;
8396 }
8397 if (Other) { // If only one other pred...
8398 BBI = Other->getTerminator();
8399 // Make sure this other block ends in an unconditional branch and that
8400 // there is an instruction before the branch.
8401 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8402 BBI != Other->begin()) {
8403 --BBI;
8404 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8405
8406 // If this instruction is a store to the same location.
8407 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8408 // Okay, we know we can perform this transformation. Insert a PHI
8409 // node now if we need it.
8410 Value *MergedVal = OtherStore->getOperand(0);
8411 if (MergedVal != SI.getOperand(0)) {
8412 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8413 PN->reserveOperandSpace(2);
8414 PN->addIncoming(SI.getOperand(0), SI.getParent());
8415 PN->addIncoming(OtherStore->getOperand(0), Other);
8416 MergedVal = InsertNewInstBefore(PN, Dest->front());
8417 }
8418
8419 // Advance to a place where it is safe to insert the new store and
8420 // insert it.
8421 BBI = Dest->begin();
8422 while (isa<PHINode>(BBI)) ++BBI;
8423 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8424 OtherStore->isVolatile()), *BBI);
8425
8426 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008427 EraseInstFromFunction(SI);
8428 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008429 ++NumCombined;
8430 return 0;
8431 }
8432 }
8433 }
8434 }
8435
Chris Lattner31f486c2005-01-31 05:36:43 +00008436 return 0;
8437}
8438
8439
Chris Lattner9eef8a72003-06-04 04:46:00 +00008440Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8441 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008442 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008443 BasicBlock *TrueDest;
8444 BasicBlock *FalseDest;
8445 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8446 !isa<Constant>(X)) {
8447 // Swap Destinations and condition...
8448 BI.setCondition(X);
8449 BI.setSuccessor(0, FalseDest);
8450 BI.setSuccessor(1, TrueDest);
8451 return &BI;
8452 }
8453
Reid Spencer266e42b2006-12-23 06:05:41 +00008454 // Cannonicalize fcmp_one -> fcmp_oeq
8455 FCmpInst::Predicate FPred; Value *Y;
8456 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8457 TrueDest, FalseDest)))
8458 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8459 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8460 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008461 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008462 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8463 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +00008464 // Swap Destinations and condition...
8465 BI.setCondition(NewSCC);
8466 BI.setSuccessor(0, FalseDest);
8467 BI.setSuccessor(1, TrueDest);
8468 removeFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008469 I->eraseFromParent();
8470 WorkList.push_back(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +00008471 return &BI;
8472 }
8473
8474 // Cannonicalize icmp_ne -> icmp_eq
8475 ICmpInst::Predicate IPred;
8476 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8477 TrueDest, FalseDest)))
8478 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8479 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8480 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8481 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008482 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008483 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8484 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +00008485 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008486 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008487 BI.setSuccessor(0, FalseDest);
8488 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00008489 removeFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008490 I->eraseFromParent();;
8491 WorkList.push_back(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008492 return &BI;
8493 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008494
Chris Lattner9eef8a72003-06-04 04:46:00 +00008495 return 0;
8496}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008497
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008498Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8499 Value *Cond = SI.getCondition();
8500 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8501 if (I->getOpcode() == Instruction::Add)
8502 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8503 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8504 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008505 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008506 AddRHS));
8507 SI.setOperand(0, I->getOperand(0));
8508 WorkList.push_back(I);
8509 return &SI;
8510 }
8511 }
8512 return 0;
8513}
8514
Chris Lattner6bc98652006-03-05 00:22:33 +00008515/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8516/// is to leave as a vector operation.
8517static bool CheapToScalarize(Value *V, bool isConstant) {
8518 if (isa<ConstantAggregateZero>(V))
8519 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008520 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008521 if (isConstant) return true;
8522 // If all elts are the same, we can extract.
8523 Constant *Op0 = C->getOperand(0);
8524 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8525 if (C->getOperand(i) != Op0)
8526 return false;
8527 return true;
8528 }
8529 Instruction *I = dyn_cast<Instruction>(V);
8530 if (!I) return false;
8531
8532 // Insert element gets simplified to the inserted element or is deleted if
8533 // this is constant idx extract element and its a constant idx insertelt.
8534 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8535 isa<ConstantInt>(I->getOperand(2)))
8536 return true;
8537 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8538 return true;
8539 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8540 if (BO->hasOneUse() &&
8541 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8542 CheapToScalarize(BO->getOperand(1), isConstant)))
8543 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008544 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8545 if (CI->hasOneUse() &&
8546 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8547 CheapToScalarize(CI->getOperand(1), isConstant)))
8548 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008549
8550 return false;
8551}
8552
Chris Lattner945e4372007-02-14 05:52:17 +00008553/// Read and decode a shufflevector mask.
8554///
8555/// It turns undef elements into values that are larger than the number of
8556/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +00008557static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8558 unsigned NElts = SVI->getType()->getNumElements();
8559 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8560 return std::vector<unsigned>(NElts, 0);
8561 if (isa<UndefValue>(SVI->getOperand(2)))
8562 return std::vector<unsigned>(NElts, 2*NElts);
8563
8564 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008565 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner12249be2006-05-25 23:48:38 +00008566 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8567 if (isa<UndefValue>(CP->getOperand(i)))
8568 Result.push_back(NElts*2); // undef -> 8
8569 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008570 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008571 return Result;
8572}
8573
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008574/// FindScalarElement - Given a vector and an element number, see if the scalar
8575/// value is already around as a register, for example if it were inserted then
8576/// extracted from the vector.
8577static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00008578 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8579 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008580 unsigned Width = PTy->getNumElements();
8581 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008582 return UndefValue::get(PTy->getElementType());
8583
8584 if (isa<UndefValue>(V))
8585 return UndefValue::get(PTy->getElementType());
8586 else if (isa<ConstantAggregateZero>(V))
8587 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +00008588 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008589 return CP->getOperand(EltNo);
8590 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8591 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008592 if (!isa<ConstantInt>(III->getOperand(2)))
8593 return 0;
8594 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008595
8596 // If this is an insert to the element we are looking for, return the
8597 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008598 if (EltNo == IIElt)
8599 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008600
8601 // Otherwise, the insertelement doesn't modify the value, recurse on its
8602 // vector input.
8603 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008604 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008605 unsigned InEl = getShuffleMask(SVI)[EltNo];
8606 if (InEl < Width)
8607 return FindScalarElement(SVI->getOperand(0), InEl);
8608 else if (InEl < Width*2)
8609 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8610 else
8611 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008612 }
8613
8614 // Otherwise, we don't know.
8615 return 0;
8616}
8617
Robert Bocchinoa8352962006-01-13 22:48:06 +00008618Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008619
Chris Lattner92346c32006-03-31 18:25:14 +00008620 // If packed val is undef, replace extract with scalar undef.
8621 if (isa<UndefValue>(EI.getOperand(0)))
8622 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8623
8624 // If packed val is constant 0, replace extract with scalar 0.
8625 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8626 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8627
Reid Spencerd84d35b2007-02-15 02:26:10 +00008628 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008629 // If packed val is constant with uniform operands, replace EI
8630 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008631 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008632 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008633 if (C->getOperand(i) != op0) {
8634 op0 = 0;
8635 break;
8636 }
8637 if (op0)
8638 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008639 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008640
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008641 // If extracting a specified index from the vector, see if we can recursively
8642 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008643 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008644 // This instruction only demands the single element from the input vector.
8645 // If the input vector has a single use, simplify it based on this use
8646 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008647 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008648 if (EI.getOperand(0)->hasOneUse()) {
8649 uint64_t UndefElts;
8650 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008651 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008652 UndefElts)) {
8653 EI.setOperand(0, V);
8654 return &EI;
8655 }
8656 }
8657
Reid Spencere0fc4df2006-10-20 07:07:24 +00008658 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008659 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008660 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008661
Chris Lattner83f65782006-05-25 22:53:38 +00008662 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008663 if (I->hasOneUse()) {
8664 // Push extractelement into predecessor operation if legal and
8665 // profitable to do so
8666 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008667 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8668 if (CheapToScalarize(BO, isConstantElt)) {
8669 ExtractElementInst *newEI0 =
8670 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8671 EI.getName()+".lhs");
8672 ExtractElementInst *newEI1 =
8673 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8674 EI.getName()+".rhs");
8675 InsertNewInstBefore(newEI0, EI);
8676 InsertNewInstBefore(newEI1, EI);
8677 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8678 }
Reid Spencerde46e482006-11-02 20:25:50 +00008679 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008680 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008681 PointerType::get(EI.getType()), EI);
8682 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008683 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008684 InsertNewInstBefore(GEP, EI);
8685 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008686 }
8687 }
8688 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8689 // Extracting the inserted element?
8690 if (IE->getOperand(2) == EI.getOperand(1))
8691 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8692 // If the inserted and extracted elements are constants, they must not
8693 // be the same value, extract from the pre-inserted value instead.
8694 if (isa<Constant>(IE->getOperand(2)) &&
8695 isa<Constant>(EI.getOperand(1))) {
8696 AddUsesToWorkList(EI);
8697 EI.setOperand(0, IE->getOperand(0));
8698 return &EI;
8699 }
8700 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8701 // If this is extracting an element from a shufflevector, figure out where
8702 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008703 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8704 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008705 Value *Src;
8706 if (SrcIdx < SVI->getType()->getNumElements())
8707 Src = SVI->getOperand(0);
8708 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8709 SrcIdx -= SVI->getType()->getNumElements();
8710 Src = SVI->getOperand(1);
8711 } else {
8712 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008713 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008714 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008715 }
8716 }
Chris Lattner83f65782006-05-25 22:53:38 +00008717 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008718 return 0;
8719}
8720
Chris Lattner90951862006-04-16 00:51:47 +00008721/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8722/// elements from either LHS or RHS, return the shuffle mask and true.
8723/// Otherwise, return false.
8724static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8725 std::vector<Constant*> &Mask) {
8726 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8727 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +00008728 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +00008729
8730 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008731 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00008732 return true;
8733 } else if (V == LHS) {
8734 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008735 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00008736 return true;
8737 } else if (V == RHS) {
8738 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008739 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008740 return true;
8741 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8742 // If this is an insert of an extract from some other vector, include it.
8743 Value *VecOp = IEI->getOperand(0);
8744 Value *ScalarOp = IEI->getOperand(1);
8745 Value *IdxOp = IEI->getOperand(2);
8746
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008747 if (!isa<ConstantInt>(IdxOp))
8748 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008749 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008750
8751 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8752 // Okay, we can handle this if the vector we are insertinting into is
8753 // transitively ok.
8754 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8755 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00008756 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008757 return true;
8758 }
8759 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8760 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008761 EI->getOperand(0)->getType() == V->getType()) {
8762 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008763 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008764
8765 // This must be extracting from either LHS or RHS.
8766 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8767 // Okay, we can handle this if the vector we are insertinting into is
8768 // transitively ok.
8769 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8770 // If so, update the mask to reflect the inserted value.
8771 if (EI->getOperand(0) == LHS) {
8772 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008773 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008774 } else {
8775 assert(EI->getOperand(0) == RHS);
8776 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008777 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008778
8779 }
8780 return true;
8781 }
8782 }
8783 }
8784 }
8785 }
8786 // TODO: Handle shufflevector here!
8787
8788 return false;
8789}
8790
8791/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8792/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8793/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008794static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008795 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00008796 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +00008797 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008798 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00008799 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +00008800
8801 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008802 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008803 return V;
8804 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008805 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008806 return V;
8807 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8808 // If this is an insert of an extract from some other vector, include it.
8809 Value *VecOp = IEI->getOperand(0);
8810 Value *ScalarOp = IEI->getOperand(1);
8811 Value *IdxOp = IEI->getOperand(2);
8812
8813 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8814 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8815 EI->getOperand(0)->getType() == V->getType()) {
8816 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008817 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8818 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008819
8820 // Either the extracted from or inserted into vector must be RHSVec,
8821 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008822 if (EI->getOperand(0) == RHS || RHS == 0) {
8823 RHS = EI->getOperand(0);
8824 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008825 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008826 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008827 return V;
8828 }
8829
Chris Lattner90951862006-04-16 00:51:47 +00008830 if (VecOp == RHS) {
8831 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008832 // Everything but the extracted element is replaced with the RHS.
8833 for (unsigned i = 0; i != NumElts; ++i) {
8834 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00008835 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008836 }
8837 return V;
8838 }
Chris Lattner90951862006-04-16 00:51:47 +00008839
8840 // If this insertelement is a chain that comes from exactly these two
8841 // vectors, return the vector and the effective shuffle.
8842 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8843 return EI->getOperand(0);
8844
Chris Lattner39fac442006-04-15 01:39:45 +00008845 }
8846 }
8847 }
Chris Lattner90951862006-04-16 00:51:47 +00008848 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008849
8850 // Otherwise, can't do anything fancy. Return an identity vector.
8851 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008852 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008853 return V;
8854}
8855
8856Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8857 Value *VecOp = IE.getOperand(0);
8858 Value *ScalarOp = IE.getOperand(1);
8859 Value *IdxOp = IE.getOperand(2);
8860
8861 // If the inserted element was extracted from some other vector, and if the
8862 // indexes are constant, try to turn this into a shufflevector operation.
8863 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8864 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8865 EI->getOperand(0)->getType() == IE.getType()) {
8866 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008867 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8868 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008869
8870 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8871 return ReplaceInstUsesWith(IE, VecOp);
8872
8873 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8874 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8875
8876 // If we are extracting a value from a vector, then inserting it right
8877 // back into the same place, just use the input vector.
8878 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8879 return ReplaceInstUsesWith(IE, VecOp);
8880
8881 // We could theoretically do this for ANY input. However, doing so could
8882 // turn chains of insertelement instructions into a chain of shufflevector
8883 // instructions, and right now we do not merge shufflevectors. As such,
8884 // only do this in a situation where it is clear that there is benefit.
8885 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8886 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8887 // the values of VecOp, except then one read from EIOp0.
8888 // Build a new shuffle mask.
8889 std::vector<Constant*> Mask;
8890 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00008891 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008892 else {
8893 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00008894 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00008895 NumVectorElts));
8896 }
Reid Spencerc635f472006-12-31 05:48:39 +00008897 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008898 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +00008899 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008900 }
8901
8902 // If this insertelement isn't used by some other insertelement, turn it
8903 // (and any insertelements it points to), into one big shuffle.
8904 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8905 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008906 Value *RHS = 0;
8907 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8908 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8909 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +00008910 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008911 }
8912 }
8913 }
8914
8915 return 0;
8916}
8917
8918
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008919Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8920 Value *LHS = SVI.getOperand(0);
8921 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008922 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008923
8924 bool MadeChange = false;
8925
Chris Lattner2deeaea2006-10-05 06:55:50 +00008926 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008927 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008928 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8929
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008930 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00008931 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008932 if (isa<UndefValue>(SVI.getOperand(1))) {
8933 // Scan to see if there are any references to the RHS. If so, replace them
8934 // with undef element refs and set MadeChange to true.
8935 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8936 if (Mask[i] >= e && Mask[i] != 2*e) {
8937 Mask[i] = 2*e;
8938 MadeChange = true;
8939 }
8940 }
8941
8942 if (MadeChange) {
8943 // Remap any references to RHS to use LHS.
8944 std::vector<Constant*> Elts;
8945 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8946 if (Mask[i] == 2*e)
8947 Elts.push_back(UndefValue::get(Type::Int32Ty));
8948 else
8949 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8950 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00008951 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008952 }
8953 }
Chris Lattner39fac442006-04-15 01:39:45 +00008954
Chris Lattner12249be2006-05-25 23:48:38 +00008955 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8956 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8957 if (LHS == RHS || isa<UndefValue>(LHS)) {
8958 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008959 // shuffle(undef,undef,mask) -> undef.
8960 return ReplaceInstUsesWith(SVI, LHS);
8961 }
8962
Chris Lattner12249be2006-05-25 23:48:38 +00008963 // Remap any references to RHS to use LHS.
8964 std::vector<Constant*> Elts;
8965 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008966 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00008967 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00008968 else {
8969 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8970 (Mask[i] < e && isa<UndefValue>(LHS)))
8971 Mask[i] = 2*e; // Turn into undef.
8972 else
8973 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00008974 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008975 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008976 }
Chris Lattner12249be2006-05-25 23:48:38 +00008977 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008978 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00008979 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008980 LHS = SVI.getOperand(0);
8981 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008982 MadeChange = true;
8983 }
8984
Chris Lattner0e477162006-05-26 00:29:06 +00008985 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008986 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008987
Chris Lattner12249be2006-05-25 23:48:38 +00008988 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8989 if (Mask[i] >= e*2) continue; // Ignore undef values.
8990 // Is this an identity shuffle of the LHS value?
8991 isLHSID &= (Mask[i] == i);
8992
8993 // Is this an identity shuffle of the RHS value?
8994 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008995 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008996
Chris Lattner12249be2006-05-25 23:48:38 +00008997 // Eliminate identity shuffles.
8998 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8999 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009000
Chris Lattner0e477162006-05-26 00:29:06 +00009001 // If the LHS is a shufflevector itself, see if we can combine it with this
9002 // one without producing an unusual shuffle. Here we are really conservative:
9003 // we are absolutely afraid of producing a shuffle mask not in the input
9004 // program, because the code gen may not be smart enough to turn a merged
9005 // shuffle into two specific shuffles: it may produce worse code. As such,
9006 // we only merge two shuffles if the result is one of the two input shuffle
9007 // masks. In this case, merging the shuffles just removes one instruction,
9008 // which we know is safe. This is good for things like turning:
9009 // (splat(splat)) -> splat.
9010 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9011 if (isa<UndefValue>(RHS)) {
9012 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9013
9014 std::vector<unsigned> NewMask;
9015 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9016 if (Mask[i] >= 2*e)
9017 NewMask.push_back(2*e);
9018 else
9019 NewMask.push_back(LHSMask[Mask[i]]);
9020
9021 // If the result mask is equal to the src shuffle or this shuffle mask, do
9022 // the replacement.
9023 if (NewMask == LHSMask || NewMask == Mask) {
9024 std::vector<Constant*> Elts;
9025 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9026 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00009027 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009028 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00009029 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009030 }
9031 }
9032 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9033 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +00009034 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009035 }
9036 }
9037 }
Chris Lattner4284f642007-01-30 22:32:46 +00009038
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009039 return MadeChange ? &SVI : 0;
9040}
9041
9042
Robert Bocchinoa8352962006-01-13 22:48:06 +00009043
Chris Lattner99f48c62002-09-02 04:59:56 +00009044void InstCombiner::removeFromWorkList(Instruction *I) {
9045 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
9046 WorkList.end());
9047}
9048
Chris Lattner39c98bb2004-12-08 23:43:58 +00009049
9050/// TryToSinkInstruction - Try to move the specified instruction from its
9051/// current block into the beginning of DestBlock, which can only happen if it's
9052/// safe to move the instruction past all of the instructions between it and the
9053/// end of its block.
9054static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9055 assert(I->hasOneUse() && "Invariants didn't hold!");
9056
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009057 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9058 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009059
Chris Lattner39c98bb2004-12-08 23:43:58 +00009060 // Do not sink alloca instructions out of the entry block.
9061 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9062 return false;
9063
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009064 // We can only sink load instructions if there is nothing between the load and
9065 // the end of block that could change the value.
9066 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009067 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9068 Scan != E; ++Scan)
9069 if (Scan->mayWriteToMemory())
9070 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009071 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009072
9073 BasicBlock::iterator InsertPos = DestBlock->begin();
9074 while (isa<PHINode>(InsertPos)) ++InsertPos;
9075
Chris Lattner9f269e42005-08-08 19:11:57 +00009076 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009077 ++NumSunkInst;
9078 return true;
9079}
9080
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009081
9082/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9083/// all reachable code to the worklist.
9084///
9085/// This has a couple of tricks to make the code faster and more powerful. In
9086/// particular, we constant fold and DCE instructions as we go, to avoid adding
9087/// them to the worklist (this significantly speeds up instcombine on code where
9088/// many instructions are dead or constant). Additionally, if we find a branch
9089/// whose condition is a known constant, we only visit the reachable successors.
9090///
9091static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +00009092 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00009093 std::vector<Instruction*> &WorkList,
9094 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009095 // We have now visited this block! If we've already been here, bail out.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009096 if (!Visited.insert(BB)) return;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009097
9098 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9099 Instruction *Inst = BBI++;
9100
9101 // DCE instruction if trivially dead.
9102 if (isInstructionTriviallyDead(Inst)) {
9103 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009104 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009105 Inst->eraseFromParent();
9106 continue;
9107 }
9108
9109 // ConstantProp instruction if trivially constant.
Chris Lattnere3eda252007-01-30 23:16:15 +00009110 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009111 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009112 Inst->replaceAllUsesWith(C);
9113 ++NumConstProp;
9114 Inst->eraseFromParent();
9115 continue;
9116 }
9117
9118 WorkList.push_back(Inst);
9119 }
9120
9121 // Recursively visit successors. If this is a branch or switch on a constant,
9122 // only visit the reachable successor.
9123 TerminatorInst *TI = BB->getTerminator();
9124 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00009125 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
Reid Spencercddc9df2007-01-12 04:24:46 +00009126 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00009127 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9128 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009129 return;
9130 }
9131 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9132 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9133 // See if this is an explicit destination.
9134 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9135 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009136 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009137 return;
9138 }
9139
9140 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00009141 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009142 return;
9143 }
9144 }
9145
9146 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00009147 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009148}
9149
Chris Lattner113f4f42002-06-25 16:13:24 +00009150bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00009151 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009152 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00009153
Chris Lattner4ed40f72005-07-07 20:40:38 +00009154 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009155 // Do a depth-first traversal of the function, populate the worklist with
9156 // the reachable instructions. Ignore blocks that are not reachable. Keep
9157 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009158 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00009159 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009160
Chris Lattner4ed40f72005-07-07 20:40:38 +00009161 // Do a quick scan over the function. If we find any blocks that are
9162 // unreachable, remove any instructions inside of them. This prevents
9163 // the instcombine code from having to deal with some bad special cases.
9164 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9165 if (!Visited.count(BB)) {
9166 Instruction *Term = BB->getTerminator();
9167 while (Term != BB->begin()) { // Remove instrs bottom-up
9168 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009169
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009170 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009171 ++NumDeadInst;
9172
9173 if (!I->use_empty())
9174 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9175 I->eraseFromParent();
9176 }
9177 }
9178 }
Chris Lattnerca081252001-12-14 16:52:21 +00009179
9180 while (!WorkList.empty()) {
9181 Instruction *I = WorkList.back(); // Get an instruction from the worklist
9182 WorkList.pop_back();
9183
Chris Lattner1443bc52006-05-11 17:11:52 +00009184 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009185 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009186 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009187 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009188 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009189 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009190
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009191 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009192
9193 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009194 removeFromWorkList(I);
9195 continue;
9196 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009197
Chris Lattner1443bc52006-05-11 17:11:52 +00009198 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +00009199 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009200 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009201
Chris Lattner1443bc52006-05-11 17:11:52 +00009202 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009203 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009204 ReplaceInstUsesWith(*I, C);
9205
Chris Lattner99f48c62002-09-02 04:59:56 +00009206 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009207 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00009208 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009209 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009210 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009211
Chris Lattner39c98bb2004-12-08 23:43:58 +00009212 // See if we can trivially sink this instruction to a successor basic block.
9213 if (I->hasOneUse()) {
9214 BasicBlock *BB = I->getParent();
9215 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9216 if (UserParent != BB) {
9217 bool UserIsSuccessor = false;
9218 // See if the user is one of our successors.
9219 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9220 if (*SI == UserParent) {
9221 UserIsSuccessor = true;
9222 break;
9223 }
9224
9225 // If the user is one of our immediate successors, and if that successor
9226 // only has us as a predecessors (we'd have to split the critical edge
9227 // otherwise), we can keep going.
9228 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9229 next(pred_begin(UserParent)) == pred_end(UserParent))
9230 // Okay, the CFG is simple enough, try to sink this instruction.
9231 Changed |= TryToSinkInstruction(I, UserParent);
9232 }
9233 }
9234
Chris Lattnerca081252001-12-14 16:52:21 +00009235 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009236 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009237 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009238 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009239 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009240 DOUT << "IC: Old = " << *I
9241 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009242
Chris Lattner396dbfe2004-06-09 05:08:07 +00009243 // Everything uses the new instruction now.
9244 I->replaceAllUsesWith(Result);
9245
9246 // Push the new instruction and any users onto the worklist.
9247 WorkList.push_back(Result);
9248 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009249
Chris Lattner6e0123b2007-02-11 01:23:03 +00009250 // Move the name to the new instruction first.
9251 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009252
9253 // Insert the new instruction into the basic block...
9254 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009255 BasicBlock::iterator InsertPos = I;
9256
9257 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9258 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9259 ++InsertPos;
9260
9261 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009262
Chris Lattner63d75af2004-05-01 23:27:23 +00009263 // Make sure that we reprocess all operands now that we reduced their
9264 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009265 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9266 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9267 WorkList.push_back(OpI);
9268
Chris Lattner396dbfe2004-06-09 05:08:07 +00009269 // Instructions can end up on the worklist more than once. Make sure
9270 // we do not process an instruction that has been deleted.
9271 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009272
9273 // Erase the old instruction.
9274 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009275 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009276 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009277
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009278 // If the instruction was modified, it's possible that it is now dead.
9279 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009280 if (isInstructionTriviallyDead(I)) {
9281 // Make sure we process all operands now that we are reducing their
9282 // use counts.
9283 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9284 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9285 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009286
Chris Lattner63d75af2004-05-01 23:27:23 +00009287 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009288 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009289 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009290 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009291 } else {
9292 WorkList.push_back(Result);
9293 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009294 }
Chris Lattner053c0932002-05-14 15:24:07 +00009295 }
Chris Lattner260ab202002-04-18 17:39:14 +00009296 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009297 }
9298 }
9299
Chris Lattner260ab202002-04-18 17:39:14 +00009300 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009301}
9302
Brian Gaeke38b79e82004-07-27 17:43:21 +00009303FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009304 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009305}
Brian Gaeke960707c2003-11-11 22:41:34 +00009306