blob: 0306c3919bd53cbc69b5a288e0c0aad323118c30 [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"
Reid Spencer7c16caa2004-09-01 22:55:40 +000054#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000055#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000056#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000057using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000058using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000059
Chris Lattner79a42ac2006-12-19 21:40:18 +000060STATISTIC(NumCombined , "Number of insts combined");
61STATISTIC(NumConstProp, "Number of constant folds");
62STATISTIC(NumDeadInst , "Number of dead inst eliminated");
63STATISTIC(NumDeadStore, "Number of dead stores eliminated");
64STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000065
Chris Lattner79a42ac2006-12-19 21:40:18 +000066namespace {
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000067 class VISIBILITY_HIDDEN InstCombiner
68 : public FunctionPass,
69 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000070 // Worklist of all of the instructions that need to be simplified.
71 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000072 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000073
Chris Lattner51ea1272004-02-28 05:22:00 +000074 /// AddUsersToWorkList - When an instruction is simplified, add all users of
75 /// the instruction to the work lists because they might get more simplified
76 /// now.
77 ///
Chris Lattner2590e512006-02-07 06:56:34 +000078 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000079 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000080 UI != UE; ++UI)
81 WorkList.push_back(cast<Instruction>(*UI));
82 }
83
Chris Lattner51ea1272004-02-28 05:22:00 +000084 /// AddUsesToWorkList - When an instruction is simplified, add operands to
85 /// the work lists because they might get more simplified now.
86 ///
87 void AddUsesToWorkList(Instruction &I) {
88 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
89 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
90 WorkList.push_back(Op);
91 }
Chris Lattner2deeaea2006-10-05 06:55:50 +000092
93 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
94 /// dead. Add all of its operands to the worklist, turning them into
95 /// undef's to reduce the number of uses of those instructions.
96 ///
97 /// Return the specified operand before it is turned into an undef.
98 ///
99 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
100 Value *R = I.getOperand(op);
101
102 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
103 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
104 WorkList.push_back(Op);
105 // Set the operand to undef to drop the use.
106 I.setOperand(i, UndefValue::get(Op->getType()));
107 }
108
109 return R;
110 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000111
Chris Lattner99f48c62002-09-02 04:59:56 +0000112 // removeFromWorkList - remove all instances of I from the worklist.
113 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +0000114 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000115 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +0000116
Chris Lattnerf12cc842002-04-28 21:27:06 +0000117 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000118 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000119 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000120 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000121 }
122
Chris Lattner69193f92004-04-05 01:30:19 +0000123 TargetData &getTargetData() const { return *TD; }
124
Chris Lattner260ab202002-04-18 17:39:14 +0000125 // Visitation implementation - Implement instruction combining for different
126 // instruction types. The semantics are as follows:
127 // Return Value:
128 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000129 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000130 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000131 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000132 Instruction *visitAdd(BinaryOperator &I);
133 Instruction *visitSub(BinaryOperator &I);
134 Instruction *visitMul(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000135 Instruction *visitURem(BinaryOperator &I);
136 Instruction *visitSRem(BinaryOperator &I);
137 Instruction *visitFRem(BinaryOperator &I);
138 Instruction *commonRemTransforms(BinaryOperator &I);
139 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000140 Instruction *commonDivTransforms(BinaryOperator &I);
141 Instruction *commonIDivTransforms(BinaryOperator &I);
142 Instruction *visitUDiv(BinaryOperator &I);
143 Instruction *visitSDiv(BinaryOperator &I);
144 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000145 Instruction *visitAnd(BinaryOperator &I);
146 Instruction *visitOr (BinaryOperator &I);
147 Instruction *visitXor(BinaryOperator &I);
Reid Spencer2341c222007-02-02 02:16:23 +0000148 Instruction *visitShl(BinaryOperator &I);
149 Instruction *visitAShr(BinaryOperator &I);
150 Instruction *visitLShr(BinaryOperator &I);
151 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000152 Instruction *visitFCmpInst(FCmpInst &I);
153 Instruction *visitICmpInst(ICmpInst &I);
154 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000155
Reid Spencer266e42b2006-12-23 06:05:41 +0000156 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
157 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000158 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +0000159 BinaryOperator &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000160 Instruction *commonCastTransforms(CastInst &CI);
161 Instruction *commonIntCastTransforms(CastInst &CI);
162 Instruction *visitTrunc(CastInst &CI);
163 Instruction *visitZExt(CastInst &CI);
164 Instruction *visitSExt(CastInst &CI);
165 Instruction *visitFPTrunc(CastInst &CI);
166 Instruction *visitFPExt(CastInst &CI);
167 Instruction *visitFPToUI(CastInst &CI);
168 Instruction *visitFPToSI(CastInst &CI);
169 Instruction *visitUIToFP(CastInst &CI);
170 Instruction *visitSIToFP(CastInst &CI);
171 Instruction *visitPtrToInt(CastInst &CI);
172 Instruction *visitIntToPtr(CastInst &CI);
173 Instruction *visitBitCast(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000174 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
175 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000176 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000177 Instruction *visitCallInst(CallInst &CI);
178 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000179 Instruction *visitPHINode(PHINode &PN);
180 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000181 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000182 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000183 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000184 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000185 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000186 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000187 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000188 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000189 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000190
191 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000192 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000193
Chris Lattner970c33a2003-06-19 17:00:31 +0000194 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000195 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000196 bool transformConstExprCastCall(CallSite CS);
197
Chris Lattner69193f92004-04-05 01:30:19 +0000198 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000199 // InsertNewInstBefore - insert an instruction New before instruction Old
200 // in the program. Add the new instruction to the worklist.
201 //
Chris Lattner623826c2004-09-28 21:48:02 +0000202 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000203 assert(New && New->getParent() == 0 &&
204 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000205 BasicBlock *BB = Old.getParent();
206 BB->getInstList().insert(&Old, New); // Insert inst
207 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000208 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000209 }
210
Chris Lattner7e794272004-09-24 15:21:34 +0000211 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
212 /// This also adds the cast to the worklist. Finally, this returns the
213 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000214 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
215 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000216 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000217
Chris Lattnere79d2492006-04-06 19:19:17 +0000218 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000219 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000220
Reid Spencer13bc5d72006-12-12 09:18:51 +0000221 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattner7e794272004-09-24 15:21:34 +0000222 WorkList.push_back(C);
223 return C;
224 }
225
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000226 // ReplaceInstUsesWith - This method is to be used when an instruction is
227 // found to be dead, replacable with another preexisting expression. Here
228 // we add all uses of I to the worklist, replace all uses of I with the new
229 // value, then return I, so that the inst combiner will know that I was
230 // modified.
231 //
232 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000233 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000234 if (&I != V) {
235 I.replaceAllUsesWith(V);
236 return &I;
237 } else {
238 // If we are replacing the instruction with itself, this must be in a
239 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000240 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000241 return &I;
242 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000243 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000244
Chris Lattner2590e512006-02-07 06:56:34 +0000245 // UpdateValueUsesWith - This method is to be used when an value is
246 // found to be replacable with another preexisting expression or was
247 // updated. Here we add all uses of I to the worklist, replace all uses of
248 // I with the new value (unless the instruction was just updated), then
249 // return true, so that the inst combiner will know that I was modified.
250 //
251 bool UpdateValueUsesWith(Value *Old, Value *New) {
252 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
253 if (Old != New)
254 Old->replaceAllUsesWith(New);
255 if (Instruction *I = dyn_cast<Instruction>(Old))
256 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000257 if (Instruction *I = dyn_cast<Instruction>(New))
258 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000259 return true;
260 }
261
Chris Lattner51ea1272004-02-28 05:22:00 +0000262 // EraseInstFromFunction - When dealing with an instruction that has side
263 // effects or produces a void value, we can't rely on DCE to delete the
264 // instruction. Instead, visit methods should return the value returned by
265 // this function.
266 Instruction *EraseInstFromFunction(Instruction &I) {
267 assert(I.use_empty() && "Cannot erase instruction that is used!");
268 AddUsesToWorkList(I);
269 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000270 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000271 return 0; // Don't do anything with FI
272 }
273
Chris Lattner3ac7c262003-08-13 20:16:26 +0000274 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000275 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
276 /// InsertBefore instruction. This is specialized a bit to avoid inserting
277 /// casts that are known to not do anything...
278 ///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000279 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
280 Value *V, const Type *DestTy,
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000281 Instruction *InsertBefore);
282
Reid Spencer266e42b2006-12-23 06:05:41 +0000283 /// SimplifyCommutative - This performs a few simplifications for
284 /// commutative operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000285 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000286
Reid Spencer266e42b2006-12-23 06:05:41 +0000287 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
288 /// most-complex to least-complex order.
289 bool SimplifyCompare(CmpInst &I);
290
Chris Lattner0157e7f2006-02-11 09:31:47 +0000291 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
292 uint64_t &KnownZero, uint64_t &KnownOne,
293 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000294
Chris Lattner2deeaea2006-10-05 06:55:50 +0000295 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
296 uint64_t &UndefElts, unsigned Depth = 0);
297
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000298 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
299 // PHI node as operand #0, see if we can fold the instruction into the PHI
300 // (which is only possible if all operands to the PHI are constants).
301 Instruction *FoldOpIntoPhi(Instruction &I);
302
Chris Lattner7515cab2004-11-14 19:13:23 +0000303 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
304 // operator and they all are only used by the PHI, PHI together their
305 // inputs, and do the operation once, to the result of the PHI.
306 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000307 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
308
309
Zhou Sheng75b871f2007-01-11 12:24:14 +0000310 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
311 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000312
Zhou Sheng75b871f2007-01-11 12:24:14 +0000313 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000314 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000315 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000316 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000317 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000318 Instruction *MatchBSwap(BinaryOperator &I);
319
Reid Spencer74a528b2006-12-13 18:21:21 +0000320 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000321 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000322
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000323 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000324}
325
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000326// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000327// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000328static unsigned getComplexity(Value *V) {
329 if (isa<Instruction>(V)) {
330 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000331 return 3;
332 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000333 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000334 if (isa<Argument>(V)) return 3;
335 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000336}
Chris Lattner260ab202002-04-18 17:39:14 +0000337
Chris Lattner7fb29e12003-03-11 00:12:48 +0000338// isOnlyUse - Return true if this instruction will be deleted if we stop using
339// it.
340static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000341 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000342}
343
Chris Lattnere79e8542004-02-23 06:38:22 +0000344// getPromotedType - Return the specified type promoted as it would be to pass
345// though a va_arg area...
346static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000347 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
348 if (ITy->getBitWidth() < 32)
349 return Type::Int32Ty;
350 } else if (Ty == Type::FloatTy)
351 return Type::DoubleTy;
352 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000353}
354
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000355/// getBitCastOperand - If the specified operand is a CastInst or a constant
356/// expression bitcast, return the operand value, otherwise return null.
357static Value *getBitCastOperand(Value *V) {
358 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000359 return I->getOperand(0);
360 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000361 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000362 return CE->getOperand(0);
363 return 0;
364}
365
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000366/// This function is a wrapper around CastInst::isEliminableCastPair. It
367/// simply extracts arguments and returns what that function returns.
368/// @Determine if it is valid to eliminate a Convert pair
369static Instruction::CastOps
370isEliminableCastPair(
371 const CastInst *CI, ///< The first cast instruction
372 unsigned opcode, ///< The opcode of the second cast instruction
373 const Type *DstTy, ///< The target type for the second cast instruction
374 TargetData *TD ///< The target data for pointer size
375) {
376
377 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
378 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000379
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000380 // Get the opcodes of the two Cast instructions
381 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
382 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000383
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000384 return Instruction::CastOps(
385 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
386 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000387}
388
389/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
390/// in any code being generated. It does not require codegen if V is simple
391/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000392static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
393 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000394 if (V->getType() == Ty || isa<Constant>(V)) return false;
395
Chris Lattner99155be2006-05-25 23:24:33 +0000396 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000397 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000398 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000399 return false;
400 return true;
401}
402
403/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
404/// InsertBefore instruction. This is specialized a bit to avoid inserting
405/// casts that are known to not do anything...
406///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000407Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
408 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000409 Instruction *InsertBefore) {
410 if (V->getType() == DestTy) return V;
411 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000412 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000413
Reid Spencer13bc5d72006-12-12 09:18:51 +0000414 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000415}
416
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000417// SimplifyCommutative - This performs a few simplifications for commutative
418// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000419//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000420// 1. Order operands such that they are listed from right (least complex) to
421// left (most complex). This puts constants before unary operators before
422// binary operators.
423//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000424// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
425// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000426//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000427bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000428 bool Changed = false;
429 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
430 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000431
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000432 if (!I.isAssociative()) return Changed;
433 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000434 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
435 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
436 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000437 Constant *Folded = ConstantExpr::get(I.getOpcode(),
438 cast<Constant>(I.getOperand(1)),
439 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000440 I.setOperand(0, Op->getOperand(0));
441 I.setOperand(1, Folded);
442 return true;
443 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
444 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
445 isOnlyUse(Op) && isOnlyUse(Op1)) {
446 Constant *C1 = cast<Constant>(Op->getOperand(1));
447 Constant *C2 = cast<Constant>(Op1->getOperand(1));
448
449 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000450 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000451 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
452 Op1->getOperand(0),
453 Op1->getName(), &I);
454 WorkList.push_back(New);
455 I.setOperand(0, New);
456 I.setOperand(1, Folded);
457 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000458 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000459 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000460 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000461}
Chris Lattnerca081252001-12-14 16:52:21 +0000462
Reid Spencer266e42b2006-12-23 06:05:41 +0000463/// SimplifyCompare - For a CmpInst this function just orders the operands
464/// so that theyare listed from right (least complex) to left (most complex).
465/// This puts constants before unary operators before binary operators.
466bool InstCombiner::SimplifyCompare(CmpInst &I) {
467 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
468 return false;
469 I.swapOperands();
470 // Compare instructions are not associative so there's nothing else we can do.
471 return true;
472}
473
Chris Lattnerbb74e222003-03-10 23:06:50 +0000474// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
475// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000476//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000477static inline Value *dyn_castNegVal(Value *V) {
478 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000479 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000480
Chris Lattner9ad0d552004-12-14 20:08:06 +0000481 // Constants can be considered to be negated values if they can be folded.
482 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
483 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000484 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000485}
486
Chris Lattnerbb74e222003-03-10 23:06:50 +0000487static inline Value *dyn_castNotVal(Value *V) {
488 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000489 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000490
491 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000492 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000493 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000494 return 0;
495}
496
Chris Lattner7fb29e12003-03-11 00:12:48 +0000497// dyn_castFoldableMul - If this value is a multiply that can be folded into
498// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000499// non-constant operand of the multiply, and set CST to point to the multiplier.
500// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000501//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000502static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000503 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000504 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000505 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000506 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000507 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000508 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000509 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000510 // The multiplier is really 1 << CST.
511 Constant *One = ConstantInt::get(V->getType(), 1);
512 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
513 return I->getOperand(0);
514 }
515 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000516 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000517}
Chris Lattner31ae8632002-08-14 17:51:49 +0000518
Chris Lattner0798af32005-01-13 20:14:25 +0000519/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
520/// expression, return it.
521static User *dyn_castGetElementPtr(Value *V) {
522 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
523 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
524 if (CE->getOpcode() == Instruction::GetElementPtr)
525 return cast<User>(V);
526 return false;
527}
528
Chris Lattner623826c2004-09-28 21:48:02 +0000529// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000530static ConstantInt *AddOne(ConstantInt *C) {
531 return cast<ConstantInt>(ConstantExpr::getAdd(C,
532 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000533}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000534static ConstantInt *SubOne(ConstantInt *C) {
535 return cast<ConstantInt>(ConstantExpr::getSub(C,
536 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000537}
538
Chris Lattner4534dd592006-02-09 07:38:58 +0000539/// ComputeMaskedBits - Determine which of the bits specified in Mask are
540/// known to be either zero or one and return them in the KnownZero/KnownOne
541/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
542/// processing.
543static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
544 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000545 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
546 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000547 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000548 // optimized based on the contradictory assumption that it is non-zero.
549 // Because instcombine aggressively folds operations with undef args anyway,
550 // this won't lose us code quality.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000551 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000552 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000553 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000554 KnownZero = ~KnownOne & Mask;
555 return;
556 }
557
558 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000559 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000560 return; // Limit search depth.
561
562 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000563 Instruction *I = dyn_cast<Instruction>(V);
564 if (!I) return;
565
Reid Spencera94d3942007-01-19 21:13:56 +0000566 Mask &= cast<IntegerType>(V->getType())->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +0000567
Chris Lattner0157e7f2006-02-11 09:31:47 +0000568 switch (I->getOpcode()) {
569 case Instruction::And:
570 // If either the LHS or the RHS are Zero, the result is zero.
571 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
572 Mask &= ~KnownZero;
573 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
574 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
575 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
576
577 // Output known-1 bits are only known if set in both the LHS & RHS.
578 KnownOne &= KnownOne2;
579 // Output known-0 are known to be clear if zero in either the LHS | RHS.
580 KnownZero |= KnownZero2;
581 return;
582 case Instruction::Or:
583 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
584 Mask &= ~KnownOne;
585 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
586 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
587 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
588
589 // Output known-0 bits are only known if clear in both the LHS & RHS.
590 KnownZero &= KnownZero2;
591 // Output known-1 are known to be set if set in either the LHS | RHS.
592 KnownOne |= KnownOne2;
593 return;
594 case Instruction::Xor: {
595 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
596 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
597 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
598 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
599
600 // Output known-0 bits are known if clear or set in both the LHS & RHS.
601 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
602 // Output known-1 are known to be set if set in only one of the LHS, RHS.
603 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
604 KnownZero = KnownZeroOut;
605 return;
606 }
607 case Instruction::Select:
608 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
609 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
610 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
611 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
612
613 // Only known if known in both the LHS and RHS.
614 KnownOne &= KnownOne2;
615 KnownZero &= KnownZero2;
616 return;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000617 case Instruction::FPTrunc:
618 case Instruction::FPExt:
619 case Instruction::FPToUI:
620 case Instruction::FPToSI:
621 case Instruction::SIToFP:
622 case Instruction::PtrToInt:
623 case Instruction::UIToFP:
624 case Instruction::IntToPtr:
625 return; // Can't work with floating point or pointers
626 case Instruction::Trunc:
627 // All these have integer operands
628 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
629 return;
630 case Instruction::BitCast: {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000631 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +0000632 if (SrcTy->isInteger()) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000633 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000634 return;
635 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000636 break;
637 }
638 case Instruction::ZExt: {
639 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +0000640 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
641 uint64_t NotIn = ~SrcTy->getBitMask();
642 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000643
Reid Spencera94d3942007-01-19 21:13:56 +0000644 Mask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000645 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
646 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
647 // The top bits are known to be zero.
648 KnownZero |= NewBits;
649 return;
650 }
651 case Instruction::SExt: {
652 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +0000653 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
654 uint64_t NotIn = ~SrcTy->getBitMask();
655 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000656
Reid Spencera94d3942007-01-19 21:13:56 +0000657 Mask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000658 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
659 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000660
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000661 // If the sign bit of the input is known set or clear, then we know the
662 // top bits of the result.
663 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
664 if (KnownZero & InSignBit) { // Input sign bit known zero
665 KnownZero |= NewBits;
666 KnownOne &= ~NewBits;
667 } else if (KnownOne & InSignBit) { // Input sign bit known set
668 KnownOne |= NewBits;
669 KnownZero &= ~NewBits;
670 } else { // Input sign bit unknown
671 KnownZero &= ~NewBits;
672 KnownOne &= ~NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000673 }
674 return;
675 }
676 case Instruction::Shl:
677 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000678 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
679 uint64_t ShiftAmt = SA->getZExtValue();
680 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000681 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
682 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000683 KnownZero <<= ShiftAmt;
684 KnownOne <<= ShiftAmt;
685 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000686 return;
687 }
688 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000689 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000690 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000691 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000692 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000693 uint64_t ShiftAmt = SA->getZExtValue();
694 uint64_t HighBits = (1ULL << ShiftAmt)-1;
695 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000696
Reid Spencerfdff9382006-11-08 06:47:33 +0000697 // Unsigned shift right.
698 Mask <<= ShiftAmt;
699 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
700 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
701 KnownZero >>= ShiftAmt;
702 KnownOne >>= ShiftAmt;
703 KnownZero |= HighBits; // high bits known zero.
704 return;
705 }
706 break;
707 case Instruction::AShr:
708 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
709 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
710 // Compute the new bits that are at the top now.
711 uint64_t ShiftAmt = SA->getZExtValue();
712 uint64_t HighBits = (1ULL << ShiftAmt)-1;
713 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
714
715 // Signed shift right.
716 Mask <<= ShiftAmt;
717 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
718 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
719 KnownZero >>= ShiftAmt;
720 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000721
Reid Spencerfdff9382006-11-08 06:47:33 +0000722 // Handle the sign bits.
723 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
724 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000725
Reid Spencerfdff9382006-11-08 06:47:33 +0000726 if (KnownZero & SignBit) { // New bits are known zero.
727 KnownZero |= HighBits;
728 } else if (KnownOne & SignBit) { // New bits are known one.
729 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000730 }
731 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000732 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000733 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000734 }
Chris Lattner92a68652006-02-07 08:05:22 +0000735}
736
737/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
738/// this predicate to simplify operations downstream. Mask is known to be zero
739/// for bits that V cannot have.
740static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000741 uint64_t KnownZero, KnownOne;
742 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
743 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
744 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000745}
746
Chris Lattner0157e7f2006-02-11 09:31:47 +0000747/// ShrinkDemandedConstant - Check to see if the specified operand of the
748/// specified instruction is a constant integer. If so, check to see if there
749/// are any bits set in the constant that are not demanded. If so, shrink the
750/// constant and return true.
751static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
752 uint64_t Demanded) {
753 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
754 if (!OpC) return false;
755
756 // If there are no bits set that aren't demanded, nothing to do.
757 if ((~Demanded & OpC->getZExtValue()) == 0)
758 return false;
759
760 // This is producing any bits that are not needed, shrink the RHS.
761 uint64_t Val = Demanded & OpC->getZExtValue();
Zhou Sheng75b871f2007-01-11 12:24:14 +0000762 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000763 return true;
764}
765
Chris Lattneree0f2802006-02-12 02:07:56 +0000766// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
767// set of known zero and one bits, compute the maximum and minimum values that
768// could have the specified known zero and known one bits, returning them in
769// min/max.
770static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
771 uint64_t KnownZero,
772 uint64_t KnownOne,
773 int64_t &Min, int64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +0000774 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +0000775 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
776
777 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
778
779 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
780 // bit if it is unknown.
781 Min = KnownOne;
782 Max = KnownOne|UnknownBits;
783
784 if (SignBit & UnknownBits) { // Sign bit is unknown
785 Min |= SignBit;
786 Max &= ~SignBit;
787 }
788
789 // Sign extend the min/max values.
790 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
791 Min = (Min << ShAmt) >> ShAmt;
792 Max = (Max << ShAmt) >> ShAmt;
793}
794
795// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
796// a set of known zero and one bits, compute the maximum and minimum values that
797// could have the specified known zero and known one bits, returning them in
798// min/max.
799static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
800 uint64_t KnownZero,
801 uint64_t KnownOne,
802 uint64_t &Min,
803 uint64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +0000804 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +0000805 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
806
807 // The minimum value is when the unknown bits are all zeros.
808 Min = KnownOne;
809 // The maximum value is when the unknown bits are all ones.
810 Max = KnownOne|UnknownBits;
811}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000812
813
814/// SimplifyDemandedBits - Look at V. At this point, we know that only the
815/// DemandedMask bits of the result of V are ever used downstream. If we can
816/// use this information to simplify V, do so and return true. Otherwise,
817/// analyze the expression and return a mask of KnownOne and KnownZero bits for
818/// the expression (used to simplify the caller). The KnownZero/One bits may
819/// only be accurate for those bits in the DemandedMask.
820bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
821 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000822 unsigned Depth) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000823 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000824 // We know all of the bits for a constant!
825 KnownOne = CI->getZExtValue() & DemandedMask;
826 KnownZero = ~KnownOne & DemandedMask;
827 return false;
828 }
829
830 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000831 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000832 if (Depth != 0) { // Not at the root.
833 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
834 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000835 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000836 }
Chris Lattner2590e512006-02-07 06:56:34 +0000837 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000838 // just set the DemandedMask to all bits.
Reid Spencera94d3942007-01-19 21:13:56 +0000839 DemandedMask = cast<IntegerType>(V->getType())->getBitMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000840 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000841 if (V != UndefValue::get(V->getType()))
842 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
843 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000844 } else if (Depth == 6) { // Limit search depth.
845 return false;
846 }
847
848 Instruction *I = dyn_cast<Instruction>(V);
849 if (!I) return false; // Only analyze instructions.
850
Reid Spencera94d3942007-01-19 21:13:56 +0000851 DemandedMask &= cast<IntegerType>(V->getType())->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +0000852
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000853 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000854 switch (I->getOpcode()) {
855 default: break;
856 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000857 // If either the LHS or the RHS are Zero, the result is zero.
858 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
859 KnownZero, KnownOne, Depth+1))
860 return true;
861 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
862
863 // If something is known zero on the RHS, the bits aren't demanded on the
864 // LHS.
865 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
866 KnownZero2, KnownOne2, Depth+1))
867 return true;
868 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
869
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000870 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000871 // These bits cannot contribute to the result of the 'and'.
872 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
873 return UpdateValueUsesWith(I, I->getOperand(0));
874 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
875 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000876
877 // If all of the demanded bits in the inputs are known zeros, return zero.
878 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
879 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
880
Chris Lattner0157e7f2006-02-11 09:31:47 +0000881 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000882 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000883 return UpdateValueUsesWith(I, I);
884
885 // Output known-1 bits are only known if set in both the LHS & RHS.
886 KnownOne &= KnownOne2;
887 // Output known-0 are known to be clear if zero in either the LHS | RHS.
888 KnownZero |= KnownZero2;
889 break;
890 case Instruction::Or:
891 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
892 KnownZero, KnownOne, Depth+1))
893 return true;
894 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
895 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
896 KnownZero2, KnownOne2, Depth+1))
897 return true;
898 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
899
900 // If all of the demanded bits are known zero on one side, return the other.
901 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000902 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000903 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000904 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000905 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000906
907 // If all of the potentially set bits on one side are known to be set on
908 // the other side, just use the 'other' side.
909 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
910 (DemandedMask & (~KnownZero)))
911 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000912 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
913 (DemandedMask & (~KnownZero2)))
914 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000915
916 // If the RHS is a constant, see if we can simplify it.
917 if (ShrinkDemandedConstant(I, 1, DemandedMask))
918 return UpdateValueUsesWith(I, I);
919
920 // Output known-0 bits are only known if clear in both the LHS & RHS.
921 KnownZero &= KnownZero2;
922 // Output known-1 are known to be set if set in either the LHS | RHS.
923 KnownOne |= KnownOne2;
924 break;
925 case Instruction::Xor: {
926 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
927 KnownZero, KnownOne, Depth+1))
928 return true;
929 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
930 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
931 KnownZero2, KnownOne2, Depth+1))
932 return true;
933 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
934
935 // If all of the demanded bits are known zero on one side, return the other.
936 // These bits cannot contribute to the result of the 'xor'.
937 if ((DemandedMask & KnownZero) == DemandedMask)
938 return UpdateValueUsesWith(I, I->getOperand(0));
939 if ((DemandedMask & KnownZero2) == DemandedMask)
940 return UpdateValueUsesWith(I, I->getOperand(1));
941
942 // Output known-0 bits are known if clear or set in both the LHS & RHS.
943 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
944 // Output known-1 are known to be set if set in only one of the LHS, RHS.
945 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
946
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000947 // If all of the demanded bits are known to be zero on one side or the
948 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000949 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000950 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
951 Instruction *Or =
952 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
953 I->getName());
954 InsertNewInstBefore(Or, *I);
955 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000956 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000957
Chris Lattner5b2edb12006-02-12 08:02:11 +0000958 // If all of the demanded bits on one side are known, and all of the set
959 // bits on that side are also known to be set on the other side, turn this
960 // into an AND, as we know the bits will be cleared.
961 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
962 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
963 if ((KnownOne & KnownOne2) == KnownOne) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000964 Constant *AndC = ConstantInt::get(I->getType(),
965 ~KnownOne & DemandedMask);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000966 Instruction *And =
967 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
968 InsertNewInstBefore(And, *I);
969 return UpdateValueUsesWith(I, And);
970 }
971 }
972
Chris Lattner0157e7f2006-02-11 09:31:47 +0000973 // If the RHS is a constant, see if we can simplify it.
974 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
975 if (ShrinkDemandedConstant(I, 1, DemandedMask))
976 return UpdateValueUsesWith(I, I);
977
978 KnownZero = KnownZeroOut;
979 KnownOne = KnownOneOut;
980 break;
981 }
982 case Instruction::Select:
983 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
984 KnownZero, KnownOne, Depth+1))
985 return true;
986 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
987 KnownZero2, KnownOne2, Depth+1))
988 return true;
989 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
990 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
991
992 // If the operands are constants, see if we can simplify them.
993 if (ShrinkDemandedConstant(I, 1, DemandedMask))
994 return UpdateValueUsesWith(I, I);
995 if (ShrinkDemandedConstant(I, 2, DemandedMask))
996 return UpdateValueUsesWith(I, I);
997
998 // Only known if known in both the LHS and RHS.
999 KnownOne &= KnownOne2;
1000 KnownZero &= KnownZero2;
1001 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001002 case Instruction::Trunc:
1003 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1004 KnownZero, KnownOne, Depth+1))
1005 return true;
1006 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1007 break;
1008 case Instruction::BitCast:
Chris Lattner03c49532007-01-15 02:27:26 +00001009 if (!I->getOperand(0)->getType()->isInteger())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001010 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001011
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001012 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1013 KnownZero, KnownOne, Depth+1))
1014 return true;
1015 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1016 break;
1017 case Instruction::ZExt: {
1018 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001019 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1020 uint64_t NotIn = ~SrcTy->getBitMask();
1021 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001022
Reid Spencera94d3942007-01-19 21:13:56 +00001023 DemandedMask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001024 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1025 KnownZero, KnownOne, Depth+1))
1026 return true;
1027 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1028 // The top bits are known to be zero.
1029 KnownZero |= NewBits;
1030 break;
1031 }
1032 case Instruction::SExt: {
1033 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001034 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1035 uint64_t NotIn = ~SrcTy->getBitMask();
1036 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001037
1038 // Get the sign bit for the source type
1039 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
Reid Spencera94d3942007-01-19 21:13:56 +00001040 int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
Chris Lattner7d852282006-02-13 22:41:07 +00001041
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001042 // If any of the sign extended bits are demanded, we know that the sign
1043 // bit is demanded.
1044 if (NewBits & DemandedMask)
1045 InputDemandedBits |= InSignBit;
Chris Lattner7d852282006-02-13 22:41:07 +00001046
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001047 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1048 KnownZero, KnownOne, Depth+1))
1049 return true;
1050 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0157e7f2006-02-11 09:31:47 +00001051
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001052 // If the sign bit of the input is known set or clear, then we know the
1053 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001054
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001055 // If the input sign bit is known zero, or if the NewBits are not demanded
1056 // convert this into a zero extension.
1057 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1058 // Convert to ZExt cast
1059 CastInst *NewCast = CastInst::create(
1060 Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1061 return UpdateValueUsesWith(I, NewCast);
1062 } else if (KnownOne & InSignBit) { // Input sign bit known set
1063 KnownOne |= NewBits;
1064 KnownZero &= ~NewBits;
1065 } else { // Input sign bit unknown
1066 KnownZero &= ~NewBits;
1067 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001068 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001069 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001070 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001071 case Instruction::Add:
1072 // If there is a constant on the RHS, there are a variety of xformations
1073 // we can do.
1074 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1075 // If null, this should be simplified elsewhere. Some of the xforms here
1076 // won't work if the RHS is zero.
1077 if (RHS->isNullValue())
1078 break;
1079
1080 // Figure out what the input bits are. If the top bits of the and result
1081 // are not demanded, then the add doesn't demand them from its input
1082 // either.
1083
1084 // Shift the demanded mask up so that it's at the top of the uint64_t.
1085 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1086 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1087
1088 // If the top bit of the output is demanded, demand everything from the
1089 // input. Otherwise, we demand all the input bits except NLZ top bits.
Jeff Cohen223004c2007-01-08 20:17:17 +00001090 uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001091
1092 // Find information about known zero/one bits in the input.
1093 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1094 KnownZero2, KnownOne2, Depth+1))
1095 return true;
1096
1097 // If the RHS of the add has bits set that can't affect the input, reduce
1098 // the constant.
1099 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1100 return UpdateValueUsesWith(I, I);
1101
1102 // Avoid excess work.
1103 if (KnownZero2 == 0 && KnownOne2 == 0)
1104 break;
1105
1106 // Turn it into OR if input bits are zero.
1107 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1108 Instruction *Or =
1109 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1110 I->getName());
1111 InsertNewInstBefore(Or, *I);
1112 return UpdateValueUsesWith(I, Or);
1113 }
1114
1115 // We can say something about the output known-zero and known-one bits,
1116 // depending on potential carries from the input constant and the
1117 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1118 // bits set and the RHS constant is 0x01001, then we know we have a known
1119 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1120
1121 // To compute this, we first compute the potential carry bits. These are
1122 // the bits which may be modified. I'm not aware of a better way to do
1123 // this scan.
1124 uint64_t RHSVal = RHS->getZExtValue();
1125
1126 bool CarryIn = false;
1127 uint64_t CarryBits = 0;
1128 uint64_t CurBit = 1;
1129 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1130 // Record the current carry in.
1131 if (CarryIn) CarryBits |= CurBit;
1132
1133 bool CarryOut;
1134
1135 // This bit has a carry out unless it is "zero + zero" or
1136 // "zero + anything" with no carry in.
1137 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1138 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1139 } else if (!CarryIn &&
1140 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1141 CarryOut = false; // 0 + anything has no carry out if no carry in.
1142 } else {
1143 // Otherwise, we have to assume we have a carry out.
1144 CarryOut = true;
1145 }
1146
1147 // This stage's carry out becomes the next stage's carry-in.
1148 CarryIn = CarryOut;
1149 }
1150
1151 // Now that we know which bits have carries, compute the known-1/0 sets.
1152
1153 // Bits are known one if they are known zero in one operand and one in the
1154 // other, and there is no input carry.
1155 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1156
1157 // Bits are known zero if they are known zero in both operands and there
1158 // is no input carry.
1159 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1160 }
1161 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001162 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001163 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1164 uint64_t ShiftAmt = SA->getZExtValue();
1165 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001166 KnownZero, KnownOne, Depth+1))
1167 return true;
1168 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001169 KnownZero <<= ShiftAmt;
1170 KnownOne <<= ShiftAmt;
1171 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001172 }
Chris Lattner2590e512006-02-07 06:56:34 +00001173 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001174 case Instruction::LShr:
1175 // For a logical shift right
1176 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1177 unsigned ShiftAmt = SA->getZExtValue();
1178
1179 // Compute the new bits that are at the top now.
1180 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1181 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Reid Spencera94d3942007-01-19 21:13:56 +00001182 uint64_t TypeMask = cast<IntegerType>(I->getType())->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001183 // Unsigned shift right.
1184 if (SimplifyDemandedBits(I->getOperand(0),
1185 (DemandedMask << ShiftAmt) & TypeMask,
1186 KnownZero, KnownOne, Depth+1))
1187 return true;
1188 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1189 KnownZero &= TypeMask;
1190 KnownOne &= TypeMask;
1191 KnownZero >>= ShiftAmt;
1192 KnownOne >>= ShiftAmt;
1193 KnownZero |= HighBits; // high bits known zero.
1194 }
1195 break;
1196 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001197 // If this is an arithmetic shift right and only the low-bit is set, we can
1198 // always convert this into a logical shr, even if the shift amount is
1199 // variable. The low bit of the shift cannot be an input sign bit unless
1200 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001201 if (DemandedMask == 1) {
1202 // Perform the logical shift right.
Reid Spencer2341c222007-02-02 02:16:23 +00001203 Value *NewVal = BinaryOperator::create(Instruction::LShr,
1204 I->getOperand(0), I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001205 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001206 return UpdateValueUsesWith(I, NewVal);
1207 }
1208
Reid Spencere0fc4df2006-10-20 07:07:24 +00001209 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1210 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001211
1212 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001213 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1214 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Reid Spencera94d3942007-01-19 21:13:56 +00001215 uint64_t TypeMask = cast<IntegerType>(I->getType())->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001216 // Signed shift right.
1217 if (SimplifyDemandedBits(I->getOperand(0),
1218 (DemandedMask << ShiftAmt) & TypeMask,
1219 KnownZero, KnownOne, Depth+1))
1220 return true;
1221 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1222 KnownZero &= TypeMask;
1223 KnownOne &= TypeMask;
1224 KnownZero >>= ShiftAmt;
1225 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001226
Reid Spencerfdff9382006-11-08 06:47:33 +00001227 // Handle the sign bits.
1228 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1229 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001230
Reid Spencerfdff9382006-11-08 06:47:33 +00001231 // If the input sign bit is known to be zero, or if none of the top bits
1232 // are demanded, turn this into an unsigned shift right.
1233 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1234 // Perform the logical shift right.
Reid Spencer2341c222007-02-02 02:16:23 +00001235 Value *NewVal = BinaryOperator::create(Instruction::LShr,
1236 I->getOperand(0), SA, I->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00001237 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1238 return UpdateValueUsesWith(I, NewVal);
1239 } else if (KnownOne & SignBit) { // New bits are known one.
1240 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001241 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001242 }
Chris Lattner2590e512006-02-07 06:56:34 +00001243 break;
1244 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001245
1246 // If the client is only demanding bits that we know, return the known
1247 // constant.
1248 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001249 return UpdateValueUsesWith(I, ConstantInt::get(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001250 return false;
1251}
1252
Chris Lattner2deeaea2006-10-05 06:55:50 +00001253
1254/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1255/// 64 or fewer elements. DemandedElts contains the set of elements that are
1256/// actually used by the caller. This method analyzes which elements of the
1257/// operand are undef and returns that information in UndefElts.
1258///
1259/// If the information about demanded elements can be used to simplify the
1260/// operation, the operation is simplified, then the resultant value is
1261/// returned. This returns null if no change was made.
1262Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1263 uint64_t &UndefElts,
1264 unsigned Depth) {
1265 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1266 assert(VWidth <= 64 && "Vector too wide to analyze!");
1267 uint64_t EltMask = ~0ULL >> (64-VWidth);
1268 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1269 "Invalid DemandedElts!");
1270
1271 if (isa<UndefValue>(V)) {
1272 // If the entire vector is undefined, just return this info.
1273 UndefElts = EltMask;
1274 return 0;
1275 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1276 UndefElts = EltMask;
1277 return UndefValue::get(V->getType());
1278 }
1279
1280 UndefElts = 0;
1281 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1282 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1283 Constant *Undef = UndefValue::get(EltTy);
1284
1285 std::vector<Constant*> Elts;
1286 for (unsigned i = 0; i != VWidth; ++i)
1287 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1288 Elts.push_back(Undef);
1289 UndefElts |= (1ULL << i);
1290 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1291 Elts.push_back(Undef);
1292 UndefElts |= (1ULL << i);
1293 } else { // Otherwise, defined.
1294 Elts.push_back(CP->getOperand(i));
1295 }
1296
1297 // If we changed the constant, return it.
1298 Constant *NewCP = ConstantPacked::get(Elts);
1299 return NewCP != CP ? NewCP : 0;
1300 } else if (isa<ConstantAggregateZero>(V)) {
1301 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1302 // set to undef.
1303 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1304 Constant *Zero = Constant::getNullValue(EltTy);
1305 Constant *Undef = UndefValue::get(EltTy);
1306 std::vector<Constant*> Elts;
1307 for (unsigned i = 0; i != VWidth; ++i)
1308 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1309 UndefElts = DemandedElts ^ EltMask;
1310 return ConstantPacked::get(Elts);
1311 }
1312
1313 if (!V->hasOneUse()) { // Other users may use these bits.
1314 if (Depth != 0) { // Not at the root.
1315 // TODO: Just compute the UndefElts information recursively.
1316 return false;
1317 }
1318 return false;
1319 } else if (Depth == 10) { // Limit search depth.
1320 return false;
1321 }
1322
1323 Instruction *I = dyn_cast<Instruction>(V);
1324 if (!I) return false; // Only analyze instructions.
1325
1326 bool MadeChange = false;
1327 uint64_t UndefElts2;
1328 Value *TmpV;
1329 switch (I->getOpcode()) {
1330 default: break;
1331
1332 case Instruction::InsertElement: {
1333 // If this is a variable index, we don't know which element it overwrites.
1334 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001335 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001336 if (Idx == 0) {
1337 // Note that we can't propagate undef elt info, because we don't know
1338 // which elt is getting updated.
1339 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1340 UndefElts2, Depth+1);
1341 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1342 break;
1343 }
1344
1345 // If this is inserting an element that isn't demanded, remove this
1346 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001347 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001348 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1349 return AddSoonDeadInstToWorklist(*I, 0);
1350
1351 // Otherwise, the element inserted overwrites whatever was there, so the
1352 // input demanded set is simpler than the output set.
1353 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1354 DemandedElts & ~(1ULL << IdxNo),
1355 UndefElts, Depth+1);
1356 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1357
1358 // The inserted element is defined.
1359 UndefElts |= 1ULL << IdxNo;
1360 break;
1361 }
1362
1363 case Instruction::And:
1364 case Instruction::Or:
1365 case Instruction::Xor:
1366 case Instruction::Add:
1367 case Instruction::Sub:
1368 case Instruction::Mul:
1369 // div/rem demand all inputs, because they don't want divide by zero.
1370 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1371 UndefElts, Depth+1);
1372 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1373 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1374 UndefElts2, Depth+1);
1375 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1376
1377 // Output elements are undefined if both are undefined. Consider things
1378 // like undef&0. The result is known zero, not undef.
1379 UndefElts &= UndefElts2;
1380 break;
1381
1382 case Instruction::Call: {
1383 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1384 if (!II) break;
1385 switch (II->getIntrinsicID()) {
1386 default: break;
1387
1388 // Binary vector operations that work column-wise. A dest element is a
1389 // function of the corresponding input elements from the two inputs.
1390 case Intrinsic::x86_sse_sub_ss:
1391 case Intrinsic::x86_sse_mul_ss:
1392 case Intrinsic::x86_sse_min_ss:
1393 case Intrinsic::x86_sse_max_ss:
1394 case Intrinsic::x86_sse2_sub_sd:
1395 case Intrinsic::x86_sse2_mul_sd:
1396 case Intrinsic::x86_sse2_min_sd:
1397 case Intrinsic::x86_sse2_max_sd:
1398 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1399 UndefElts, Depth+1);
1400 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1401 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1402 UndefElts2, Depth+1);
1403 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1404
1405 // If only the low elt is demanded and this is a scalarizable intrinsic,
1406 // scalarize it now.
1407 if (DemandedElts == 1) {
1408 switch (II->getIntrinsicID()) {
1409 default: break;
1410 case Intrinsic::x86_sse_sub_ss:
1411 case Intrinsic::x86_sse_mul_ss:
1412 case Intrinsic::x86_sse2_sub_sd:
1413 case Intrinsic::x86_sse2_mul_sd:
1414 // TODO: Lower MIN/MAX/ABS/etc
1415 Value *LHS = II->getOperand(1);
1416 Value *RHS = II->getOperand(2);
1417 // Extract the element as scalars.
1418 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1419 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1420
1421 switch (II->getIntrinsicID()) {
1422 default: assert(0 && "Case stmts out of sync!");
1423 case Intrinsic::x86_sse_sub_ss:
1424 case Intrinsic::x86_sse2_sub_sd:
1425 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1426 II->getName()), *II);
1427 break;
1428 case Intrinsic::x86_sse_mul_ss:
1429 case Intrinsic::x86_sse2_mul_sd:
1430 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1431 II->getName()), *II);
1432 break;
1433 }
1434
1435 Instruction *New =
1436 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1437 II->getName());
1438 InsertNewInstBefore(New, *II);
1439 AddSoonDeadInstToWorklist(*II, 0);
1440 return New;
1441 }
1442 }
1443
1444 // Output elements are undefined if both are undefined. Consider things
1445 // like undef&0. The result is known zero, not undef.
1446 UndefElts &= UndefElts2;
1447 break;
1448 }
1449 break;
1450 }
1451 }
1452 return MadeChange ? I : 0;
1453}
1454
Reid Spencer266e42b2006-12-23 06:05:41 +00001455/// @returns true if the specified compare instruction is
1456/// true when both operands are equal...
1457/// @brief Determine if the ICmpInst returns true if both operands are equal
1458static bool isTrueWhenEqual(ICmpInst &ICI) {
1459 ICmpInst::Predicate pred = ICI.getPredicate();
1460 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1461 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1462 pred == ICmpInst::ICMP_SLE;
1463}
1464
Chris Lattnerb8b97502003-08-13 19:01:45 +00001465/// AssociativeOpt - Perform an optimization on an associative operator. This
1466/// function is designed to check a chain of associative operators for a
1467/// potential to apply a certain optimization. Since the optimization may be
1468/// applicable if the expression was reassociated, this checks the chain, then
1469/// reassociates the expression as necessary to expose the optimization
1470/// opportunity. This makes use of a special Functor, which must define
1471/// 'shouldApply' and 'apply' methods.
1472///
1473template<typename Functor>
1474Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1475 unsigned Opcode = Root.getOpcode();
1476 Value *LHS = Root.getOperand(0);
1477
1478 // Quick check, see if the immediate LHS matches...
1479 if (F.shouldApply(LHS))
1480 return F.apply(Root);
1481
1482 // Otherwise, if the LHS is not of the same opcode as the root, return.
1483 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001484 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001485 // Should we apply this transform to the RHS?
1486 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1487
1488 // If not to the RHS, check to see if we should apply to the LHS...
1489 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1490 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1491 ShouldApply = true;
1492 }
1493
1494 // If the functor wants to apply the optimization to the RHS of LHSI,
1495 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1496 if (ShouldApply) {
1497 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001498
Chris Lattnerb8b97502003-08-13 19:01:45 +00001499 // Now all of the instructions are in the current basic block, go ahead
1500 // and perform the reassociation.
1501 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1502
1503 // First move the selected RHS to the LHS of the root...
1504 Root.setOperand(0, LHSI->getOperand(1));
1505
1506 // Make what used to be the LHS of the root be the user of the root...
1507 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001508 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001509 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1510 return 0;
1511 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001512 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001513 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001514 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1515 BasicBlock::iterator ARI = &Root; ++ARI;
1516 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1517 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001518
1519 // Now propagate the ExtraOperand down the chain of instructions until we
1520 // get to LHSI.
1521 while (TmpLHSI != LHSI) {
1522 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001523 // Move the instruction to immediately before the chain we are
1524 // constructing to avoid breaking dominance properties.
1525 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1526 BB->getInstList().insert(ARI, NextLHSI);
1527 ARI = NextLHSI;
1528
Chris Lattnerb8b97502003-08-13 19:01:45 +00001529 Value *NextOp = NextLHSI->getOperand(1);
1530 NextLHSI->setOperand(1, ExtraOperand);
1531 TmpLHSI = NextLHSI;
1532 ExtraOperand = NextOp;
1533 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001534
Chris Lattnerb8b97502003-08-13 19:01:45 +00001535 // Now that the instructions are reassociated, have the functor perform
1536 // the transformation...
1537 return F.apply(Root);
1538 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001539
Chris Lattnerb8b97502003-08-13 19:01:45 +00001540 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1541 }
1542 return 0;
1543}
1544
1545
1546// AddRHS - Implements: X + X --> X << 1
1547struct AddRHS {
1548 Value *RHS;
1549 AddRHS(Value *rhs) : RHS(rhs) {}
1550 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1551 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer2341c222007-02-02 02:16:23 +00001552 return BinaryOperator::create(Instruction::Shl, Add.getOperand(0),
1553 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001554 }
1555};
1556
1557// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1558// iff C1&C2 == 0
1559struct AddMaskingAnd {
1560 Constant *C2;
1561 AddMaskingAnd(Constant *c) : C2(c) {}
1562 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001563 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001564 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001565 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001566 }
1567 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001568 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001569 }
1570};
1571
Chris Lattner86102b82005-01-01 16:22:27 +00001572static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001573 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001574 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001575 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001576 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001577
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001578 return IC->InsertNewInstBefore(CastInst::create(
1579 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001580 }
1581
Chris Lattner183b3362004-04-09 19:05:30 +00001582 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001583 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1584 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001585
Chris Lattner183b3362004-04-09 19:05:30 +00001586 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1587 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001588 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1589 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001590 }
1591
1592 Value *Op0 = SO, *Op1 = ConstOperand;
1593 if (!ConstIsRHS)
1594 std::swap(Op0, Op1);
1595 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001596 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1597 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001598 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1599 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1600 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001601 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001602 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001603 abort();
1604 }
Chris Lattner86102b82005-01-01 16:22:27 +00001605 return IC->InsertNewInstBefore(New, I);
1606}
1607
1608// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1609// constant as the other operand, try to fold the binary operator into the
1610// select arguments. This also works for Cast instructions, which obviously do
1611// not have a second operand.
1612static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1613 InstCombiner *IC) {
1614 // Don't modify shared select instructions
1615 if (!SI->hasOneUse()) return 0;
1616 Value *TV = SI->getOperand(1);
1617 Value *FV = SI->getOperand(2);
1618
1619 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001620 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001621 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001622
Chris Lattner86102b82005-01-01 16:22:27 +00001623 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1624 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1625
1626 return new SelectInst(SI->getCondition(), SelectTrueVal,
1627 SelectFalseVal);
1628 }
1629 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001630}
1631
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001632
1633/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1634/// node as operand #0, see if we can fold the instruction into the PHI (which
1635/// is only possible if all operands to the PHI are constants).
1636Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1637 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001638 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001639 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001640
Chris Lattner04689872006-09-09 22:02:56 +00001641 // Check to see if all of the operands of the PHI are constants. If there is
1642 // one non-constant value, remember the BB it is. If there is more than one
1643 // bail out.
1644 BasicBlock *NonConstBB = 0;
1645 for (unsigned i = 0; i != NumPHIValues; ++i)
1646 if (!isa<Constant>(PN->getIncomingValue(i))) {
1647 if (NonConstBB) return 0; // More than one non-const value.
1648 NonConstBB = PN->getIncomingBlock(i);
1649
1650 // If the incoming non-constant value is in I's block, we have an infinite
1651 // loop.
1652 if (NonConstBB == I.getParent())
1653 return 0;
1654 }
1655
1656 // If there is exactly one non-constant value, we can insert a copy of the
1657 // operation in that block. However, if this is a critical edge, we would be
1658 // inserting the computation one some other paths (e.g. inside a loop). Only
1659 // do this if the pred block is unconditionally branching into the phi block.
1660 if (NonConstBB) {
1661 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1662 if (!BI || !BI->isUnconditional()) return 0;
1663 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001664
1665 // Okay, we can do the transformation: create the new PHI node.
1666 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1667 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001668 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001669 InsertNewInstBefore(NewPN, *PN);
1670
1671 // Next, add all of the operands to the PHI.
1672 if (I.getNumOperands() == 2) {
1673 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001674 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001675 Value *InV;
1676 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001677 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1678 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1679 else
1680 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001681 } else {
1682 assert(PN->getIncomingBlock(i) == NonConstBB);
1683 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1684 InV = BinaryOperator::create(BO->getOpcode(),
1685 PN->getIncomingValue(i), C, "phitmp",
1686 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001687 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1688 InV = CmpInst::create(CI->getOpcode(),
1689 CI->getPredicate(),
1690 PN->getIncomingValue(i), C, "phitmp",
1691 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001692 else
1693 assert(0 && "Unknown binop!");
1694
1695 WorkList.push_back(cast<Instruction>(InV));
1696 }
1697 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001698 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001699 } else {
1700 CastInst *CI = cast<CastInst>(&I);
1701 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001702 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001703 Value *InV;
1704 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001705 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001706 } else {
1707 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001708 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1709 I.getType(), "phitmp",
1710 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001711 WorkList.push_back(cast<Instruction>(InV));
1712 }
1713 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001714 }
1715 }
1716 return ReplaceInstUsesWith(I, NewPN);
1717}
1718
Chris Lattner113f4f42002-06-25 16:13:24 +00001719Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001720 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001721 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001722
Chris Lattnercf4a9962004-04-10 22:01:55 +00001723 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001724 // X + undef -> undef
1725 if (isa<UndefValue>(RHS))
1726 return ReplaceInstUsesWith(I, RHS);
1727
Chris Lattnercf4a9962004-04-10 22:01:55 +00001728 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001729 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001730 if (RHSC->isNullValue())
1731 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001732 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1733 if (CFP->isExactlyValue(-0.0))
1734 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001735 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001736
Chris Lattnercf4a9962004-04-10 22:01:55 +00001737 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001738 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00001739 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001740 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001741 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001742
1743 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1744 // (X & 254)+1 -> (X&254)|1
1745 uint64_t KnownZero, KnownOne;
1746 if (!isa<PackedType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00001747 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001748 KnownZero, KnownOne))
1749 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00001750 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001751
1752 if (isa<PHINode>(LHS))
1753 if (Instruction *NV = FoldOpIntoPhi(I))
1754 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001755
Chris Lattner330628a2006-01-06 17:59:59 +00001756 ConstantInt *XorRHS = 0;
1757 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00001758 if (isa<ConstantInt>(RHSC) &&
1759 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001760 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1761 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1762 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1763
1764 uint64_t C0080Val = 1ULL << 31;
1765 int64_t CFF80Val = -C0080Val;
1766 unsigned Size = 32;
1767 do {
1768 if (TySizeBits > Size) {
1769 bool Found = false;
1770 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1771 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1772 if (RHSSExt == CFF80Val) {
1773 if (XorRHS->getZExtValue() == C0080Val)
1774 Found = true;
1775 } else if (RHSZExt == C0080Val) {
1776 if (XorRHS->getSExtValue() == CFF80Val)
1777 Found = true;
1778 }
1779 if (Found) {
1780 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001781 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001782 Mask <<= 64-(TySizeBits-Size);
Reid Spencera94d3942007-01-19 21:13:56 +00001783 Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001784 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001785 Size = 0; // Not a sign ext, but can't be any others either.
1786 goto FoundSExt;
1787 }
1788 }
1789 Size >>= 1;
1790 C0080Val >>= Size;
1791 CFF80Val >>= Size;
1792 } while (Size >= 8);
1793
1794FoundSExt:
1795 const Type *MiddleType = 0;
1796 switch (Size) {
1797 default: break;
Reid Spencerc635f472006-12-31 05:48:39 +00001798 case 32: MiddleType = Type::Int32Ty; break;
1799 case 16: MiddleType = Type::Int16Ty; break;
1800 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001801 }
1802 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001803 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001804 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001805 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001806 }
1807 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001808 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001809
Chris Lattnerb8b97502003-08-13 19:01:45 +00001810 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00001811 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001812 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001813
1814 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1815 if (RHSI->getOpcode() == Instruction::Sub)
1816 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1817 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1818 }
1819 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1820 if (LHSI->getOpcode() == Instruction::Sub)
1821 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1822 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1823 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001824 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001825
Chris Lattner147e9752002-05-08 22:46:53 +00001826 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001827 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001828 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001829
1830 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001831 if (!isa<Constant>(RHS))
1832 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001833 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001834
Misha Brukmanb1c93172005-04-21 23:48:37 +00001835
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001836 ConstantInt *C2;
1837 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1838 if (X == RHS) // X*C + X --> X * (C+1)
1839 return BinaryOperator::createMul(RHS, AddOne(C2));
1840
1841 // X*C1 + X*C2 --> X * (C1+C2)
1842 ConstantInt *C1;
1843 if (X == dyn_castFoldableMul(RHS, C1))
1844 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001845 }
1846
1847 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001848 if (dyn_castFoldableMul(RHS, C2) == LHS)
1849 return BinaryOperator::createMul(LHS, AddOne(C2));
1850
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001851 // X + ~X --> -1 since ~X = -X-1
1852 if (dyn_castNotVal(LHS) == RHS ||
1853 dyn_castNotVal(RHS) == LHS)
1854 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1855
Chris Lattner57c8d992003-02-18 19:57:07 +00001856
Chris Lattnerb8b97502003-08-13 19:01:45 +00001857 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001858 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001859 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1860 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001861
Chris Lattnerb9cde762003-10-02 15:11:26 +00001862 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001863 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001864 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1865 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1866 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001867 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001868
Chris Lattnerbff91d92004-10-08 05:07:56 +00001869 // (X & FF00) + xx00 -> (X+xx00) & FF00
1870 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1871 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1872 if (Anded == CRHS) {
1873 // See if all bits from the first bit set in the Add RHS up are included
1874 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001875 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001876
1877 // Form a mask of all bits from the lowest bit added through the top.
1878 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Reid Spencera94d3942007-01-19 21:13:56 +00001879 AddRHSHighBits &= C2->getType()->getBitMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001880
1881 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001882 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001883
Chris Lattnerbff91d92004-10-08 05:07:56 +00001884 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1885 // Okay, the xform is safe. Insert the new add pronto.
1886 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1887 LHS->getName()), I);
1888 return BinaryOperator::createAnd(NewAdd, C2);
1889 }
1890 }
1891 }
1892
Chris Lattnerd4252a72004-07-30 07:50:03 +00001893 // Try to fold constant add into select arguments.
1894 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001895 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001896 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001897 }
1898
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001899 // add (cast *A to intptrtype) B ->
1900 // cast (GEP (cast *A to sbyte*) B) ->
1901 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001902 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001903 CastInst *CI = dyn_cast<CastInst>(LHS);
1904 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001905 if (!CI) {
1906 CI = dyn_cast<CastInst>(RHS);
1907 Other = LHS;
1908 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001909 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00001910 (CI->getType()->getPrimitiveSizeInBits() ==
1911 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001912 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00001913 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001914 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001915 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001916 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001917 }
1918 }
1919
Chris Lattner113f4f42002-06-25 16:13:24 +00001920 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001921}
1922
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001923// isSignBit - Return true if the value represented by the constant only has the
1924// highest order bit set.
1925static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001926 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001927 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001928}
1929
Chris Lattner113f4f42002-06-25 16:13:24 +00001930Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001931 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001932
Chris Lattnere6794492002-08-12 21:17:25 +00001933 if (Op0 == Op1) // sub X, X -> 0
1934 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001935
Chris Lattnere6794492002-08-12 21:17:25 +00001936 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001937 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001938 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001939
Chris Lattner81a7a232004-10-16 18:11:37 +00001940 if (isa<UndefValue>(Op0))
1941 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1942 if (isa<UndefValue>(Op1))
1943 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1944
Chris Lattner8f2f5982003-11-05 01:06:05 +00001945 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1946 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001947 if (C->isAllOnesValue())
1948 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001949
Chris Lattner8f2f5982003-11-05 01:06:05 +00001950 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001951 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001952 if (match(Op1, m_Not(m_Value(X))))
1953 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001954 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner27df1db2007-01-15 07:02:54 +00001955 // -(X >>u 31) -> (X >>s 31)
1956 // -(X >>s 31) -> (X >>u 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001957 if (C->isNullValue()) {
Reid Spencer2341c222007-02-02 02:16:23 +00001958 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00001959 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001960 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001961 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001962 if (CU->getZExtValue() ==
1963 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001964 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00001965 return BinaryOperator::create(Instruction::AShr,
1966 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00001967 }
1968 }
Reid Spencerfdff9382006-11-08 06:47:33 +00001969 }
1970 else if (SI->getOpcode() == Instruction::AShr) {
1971 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1972 // Check to see if we are shifting out everything but the sign bit.
1973 if (CU->getZExtValue() ==
1974 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00001975 // Ok, the transformation is safe. Insert LShr.
Reid Spencer2341c222007-02-02 02:16:23 +00001976 return BinaryOperator::create(Instruction::LShr,
1977 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00001978 }
1979 }
1980 }
Chris Lattner022167f2004-03-13 00:11:49 +00001981 }
Chris Lattner183b3362004-04-09 19:05:30 +00001982
1983 // Try to fold constant sub into select arguments.
1984 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001985 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001986 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001987
1988 if (isa<PHINode>(Op0))
1989 if (Instruction *NV = FoldOpIntoPhi(I))
1990 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001991 }
1992
Chris Lattnera9be4492005-04-07 16:15:25 +00001993 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1994 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00001995 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001996 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001997 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001998 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001999 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002000 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2001 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2002 // C1-(X+C2) --> (C1-C2)-X
2003 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2004 Op1I->getOperand(0));
2005 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002006 }
2007
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002008 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002009 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2010 // is not used by anyone else...
2011 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002012 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002013 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002014 // Swap the two operands of the subexpr...
2015 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2016 Op1I->setOperand(0, IIOp1);
2017 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002018
Chris Lattner3082c5a2003-02-18 19:28:33 +00002019 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002020 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002021 }
2022
2023 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2024 //
2025 if (Op1I->getOpcode() == Instruction::And &&
2026 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2027 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2028
Chris Lattner396dbfe2004-06-09 05:08:07 +00002029 Value *NewNot =
2030 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002031 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002032 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002033
Reid Spencer3c514952006-10-16 23:08:08 +00002034 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002035 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002036 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002037 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002038 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002039 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002040 ConstantExpr::getNeg(DivRHS));
2041
Chris Lattner57c8d992003-02-18 19:57:07 +00002042 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002043 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002044 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002045 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002046 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002047 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002048 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002049 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002050 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002051
Chris Lattner7a002fe2006-12-02 00:13:08 +00002052 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002053 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2054 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002055 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2056 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2057 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2058 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002059 } else if (Op0I->getOpcode() == Instruction::Sub) {
2060 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2061 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002062 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002063
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002064 ConstantInt *C1;
2065 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2066 if (X == Op1) { // X*C - X --> X * (C-1)
2067 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2068 return BinaryOperator::createMul(Op1, CP1);
2069 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002070
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002071 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2072 if (X == dyn_castFoldableMul(Op1, C2))
2073 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2074 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002075 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002076}
2077
Reid Spencer266e42b2006-12-23 06:05:41 +00002078/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002079/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002080static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2081 switch (pred) {
2082 case ICmpInst::ICMP_SLT:
2083 // True if LHS s< RHS and RHS == 0
2084 return RHS->isNullValue();
2085 case ICmpInst::ICMP_SLE:
2086 // True if LHS s<= RHS and RHS == -1
2087 return RHS->isAllOnesValue();
2088 case ICmpInst::ICMP_UGE:
2089 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2090 return RHS->getZExtValue() == (1ULL <<
2091 (RHS->getType()->getPrimitiveSizeInBits()-1));
2092 case ICmpInst::ICMP_UGT:
2093 // True if LHS u> RHS and RHS == high-bit-mask - 1
2094 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002095 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002096 default:
2097 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002098 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002099}
2100
Chris Lattner113f4f42002-06-25 16:13:24 +00002101Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002102 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002103 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002104
Chris Lattner81a7a232004-10-16 18:11:37 +00002105 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2106 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2107
Chris Lattnere6794492002-08-12 21:17:25 +00002108 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002109 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2110 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002111
2112 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002113 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002114 if (SI->getOpcode() == Instruction::Shl)
2115 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002116 return BinaryOperator::createMul(SI->getOperand(0),
2117 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002118
Chris Lattnercce81be2003-09-11 22:24:54 +00002119 if (CI->isNullValue())
2120 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2121 if (CI->equalsInt(1)) // X * 1 == X
2122 return ReplaceInstUsesWith(I, Op0);
2123 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002124 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002125
Reid Spencere0fc4df2006-10-20 07:07:24 +00002126 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002127 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2128 uint64_t C = Log2_64(Val);
Reid Spencer2341c222007-02-02 02:16:23 +00002129 return BinaryOperator::create(Instruction::Shl, Op0,
2130 ConstantInt::get(Op0->getType(), C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002131 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002132 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002133 if (Op1F->isNullValue())
2134 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002135
Chris Lattner3082c5a2003-02-18 19:28:33 +00002136 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2137 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2138 if (Op1F->getValue() == 1.0)
2139 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2140 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002141
2142 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2143 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2144 isa<ConstantInt>(Op0I->getOperand(1))) {
2145 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2146 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2147 Op1, "tmp");
2148 InsertNewInstBefore(Add, I);
2149 Value *C1C2 = ConstantExpr::getMul(Op1,
2150 cast<Constant>(Op0I->getOperand(1)));
2151 return BinaryOperator::createAdd(Add, C1C2);
2152
2153 }
Chris Lattner183b3362004-04-09 19:05:30 +00002154
2155 // Try to fold constant mul into select arguments.
2156 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002157 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002158 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002159
2160 if (isa<PHINode>(Op0))
2161 if (Instruction *NV = FoldOpIntoPhi(I))
2162 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002163 }
2164
Chris Lattner934a64cf2003-03-10 23:23:04 +00002165 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2166 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002167 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002168
Chris Lattner2635b522004-02-23 05:39:21 +00002169 // If one of the operands of the multiply is a cast from a boolean value, then
2170 // we know the bool is either zero or one, so this is a 'masking' multiply.
2171 // See if we can simplify things based on how the boolean was originally
2172 // formed.
2173 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002174 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002175 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002176 BoolCast = CI;
2177 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002178 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002179 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002180 BoolCast = CI;
2181 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002182 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002183 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2184 const Type *SCOpTy = SCIOp0->getType();
2185
Reid Spencer266e42b2006-12-23 06:05:41 +00002186 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002187 // multiply into a shift/and combination.
2188 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002189 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002190 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00002191 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002192 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002193 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002194 InsertNewInstBefore(
2195 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002196 BoolCast->getOperand(0)->getName()+
2197 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002198
2199 // If the multiply type is not the same as the source type, sign extend
2200 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002201 if (I.getType() != V->getType()) {
2202 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2203 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2204 Instruction::CastOps opcode =
2205 (SrcBits == DstBits ? Instruction::BitCast :
2206 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2207 V = InsertCastBefore(opcode, V, I.getType(), I);
2208 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002209
Chris Lattner2635b522004-02-23 05:39:21 +00002210 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002211 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002212 }
2213 }
2214 }
2215
Chris Lattner113f4f42002-06-25 16:13:24 +00002216 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002217}
2218
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002219/// This function implements the transforms on div instructions that work
2220/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2221/// used by the visitors to those instructions.
2222/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002223Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002224 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002225
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002226 // undef / X -> 0
2227 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002228 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002229
2230 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002231 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002232 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002233
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002234 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002235 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2236 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002237 // same basic block, then we replace the select with Y, and the condition
2238 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002239 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002240 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002241 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2242 if (ST->isNullValue()) {
2243 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2244 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002245 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002246 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2247 I.setOperand(1, SI->getOperand(2));
2248 else
2249 UpdateValueUsesWith(SI, SI->getOperand(2));
2250 return &I;
2251 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002252
Chris Lattnerd79dc792006-09-09 20:26:32 +00002253 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2254 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2255 if (ST->isNullValue()) {
2256 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2257 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002258 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002259 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2260 I.setOperand(1, SI->getOperand(1));
2261 else
2262 UpdateValueUsesWith(SI, SI->getOperand(1));
2263 return &I;
2264 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002265 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002266
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002267 return 0;
2268}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002269
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002270/// This function implements the transforms common to both integer division
2271/// instructions (udiv and sdiv). It is called by the visitors to those integer
2272/// division instructions.
2273/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002274Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002275 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2276
2277 if (Instruction *Common = commonDivTransforms(I))
2278 return Common;
2279
2280 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2281 // div X, 1 == X
2282 if (RHS->equalsInt(1))
2283 return ReplaceInstUsesWith(I, Op0);
2284
2285 // (X / C1) / C2 -> X / (C1*C2)
2286 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2287 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2288 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2289 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2290 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002291 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002292
2293 if (!RHS->isNullValue()) { // avoid X udiv 0
2294 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2295 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2296 return R;
2297 if (isa<PHINode>(Op0))
2298 if (Instruction *NV = FoldOpIntoPhi(I))
2299 return NV;
2300 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002301 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002302
Chris Lattner3082c5a2003-02-18 19:28:33 +00002303 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002304 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002305 if (LHS->equalsInt(0))
2306 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2307
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002308 return 0;
2309}
2310
2311Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2312 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2313
2314 // Handle the integer div common cases
2315 if (Instruction *Common = commonIDivTransforms(I))
2316 return Common;
2317
2318 // X udiv C^2 -> X >> C
2319 // Check to see if this is an unsigned division with an exact power of 2,
2320 // if so, convert to a right shift.
2321 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2322 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2323 if (isPowerOf2_64(Val)) {
2324 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencer2341c222007-02-02 02:16:23 +00002325 return BinaryOperator::create(Instruction::LShr, Op0,
2326 ConstantInt::get(Op0->getType(), ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002327 }
2328 }
2329
2330 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00002331 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002332 if (RHSI->getOpcode() == Instruction::Shl &&
2333 isa<ConstantInt>(RHSI->getOperand(0))) {
2334 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2335 if (isPowerOf2_64(C1)) {
2336 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002337 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002338 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002339 Constant *C2V = ConstantInt::get(NTy, C2);
2340 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002341 }
Reid Spencer2341c222007-02-02 02:16:23 +00002342 return BinaryOperator::create(Instruction::LShr, Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002343 }
2344 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002345 }
2346
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002347 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2348 // where C1&C2 are powers of two.
2349 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2350 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2351 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2352 if (!STO->isNullValue() && !STO->isNullValue()) {
2353 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2354 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2355 // Compute the shift amounts
2356 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002357 // Construct the "on true" case of the select
Reid Spencer2341c222007-02-02 02:16:23 +00002358 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2359 Instruction *TSI = BinaryOperator::create(Instruction::LShr,
2360 Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002361 TSI = InsertNewInstBefore(TSI, I);
2362
2363 // Construct the "on false" case of the select
Reid Spencer2341c222007-02-02 02:16:23 +00002364 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2365 Instruction *FSI = BinaryOperator::create(Instruction::LShr,
2366 Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002367 FSI = InsertNewInstBefore(FSI, I);
2368
2369 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002370 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002371 }
2372 }
2373 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002374 return 0;
2375}
2376
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002377Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2378 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2379
2380 // Handle the integer div common cases
2381 if (Instruction *Common = commonIDivTransforms(I))
2382 return Common;
2383
2384 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2385 // sdiv X, -1 == -X
2386 if (RHS->isAllOnesValue())
2387 return BinaryOperator::createNeg(Op0);
2388
2389 // -X/C -> X/-C
2390 if (Value *LHSNeg = dyn_castNegVal(Op0))
2391 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2392 }
2393
2394 // If the sign bits of both operands are zero (i.e. we can prove they are
2395 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002396 if (I.getType()->isInteger()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002397 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2398 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2399 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2400 }
2401 }
2402
2403 return 0;
2404}
2405
2406Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2407 return commonDivTransforms(I);
2408}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002409
Chris Lattner85dda9a2006-03-02 06:50:58 +00002410/// GetFactor - If we can prove that the specified value is at least a multiple
2411/// of some factor, return that factor.
2412static Constant *GetFactor(Value *V) {
2413 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2414 return CI;
2415
2416 // Unless we can be tricky, we know this is a multiple of 1.
2417 Constant *Result = ConstantInt::get(V->getType(), 1);
2418
2419 Instruction *I = dyn_cast<Instruction>(V);
2420 if (!I) return Result;
2421
2422 if (I->getOpcode() == Instruction::Mul) {
2423 // Handle multiplies by a constant, etc.
2424 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2425 GetFactor(I->getOperand(1)));
2426 } else if (I->getOpcode() == Instruction::Shl) {
2427 // (X<<C) -> X * (1 << C)
2428 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2429 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2430 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2431 }
2432 } else if (I->getOpcode() == Instruction::And) {
2433 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2434 // X & 0xFFF0 is known to be a multiple of 16.
2435 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2436 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2437 return ConstantExpr::getShl(Result,
Reid Spencer2341c222007-02-02 02:16:23 +00002438 ConstantInt::get(Result->getType(), Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002439 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002440 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002441 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002442 if (!CI->isIntegerCast())
2443 return Result;
2444 Value *Op = CI->getOperand(0);
2445 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002446 }
2447 return Result;
2448}
2449
Reid Spencer7eb55b32006-11-02 01:53:59 +00002450/// This function implements the transforms on rem instructions that work
2451/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2452/// is used by the visitors to those instructions.
2453/// @brief Transforms common to all three rem instructions
2454Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002455 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002456
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002457 // 0 % X == 0, we don't need to preserve faults!
2458 if (Constant *LHS = dyn_cast<Constant>(Op0))
2459 if (LHS->isNullValue())
2460 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2461
2462 if (isa<UndefValue>(Op0)) // undef % X -> 0
2463 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2464 if (isa<UndefValue>(Op1))
2465 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002466
2467 // Handle cases involving: rem X, (select Cond, Y, Z)
2468 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2469 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2470 // the same basic block, then we replace the select with Y, and the
2471 // condition of the select with false (if the cond value is in the same
2472 // BB). If the select has uses other than the div, this allows them to be
2473 // simplified also.
2474 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2475 if (ST->isNullValue()) {
2476 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2477 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002478 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002479 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2480 I.setOperand(1, SI->getOperand(2));
2481 else
2482 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002483 return &I;
2484 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002485 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2486 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2487 if (ST->isNullValue()) {
2488 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2489 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002490 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002491 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2492 I.setOperand(1, SI->getOperand(1));
2493 else
2494 UpdateValueUsesWith(SI, SI->getOperand(1));
2495 return &I;
2496 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002497 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002498
Reid Spencer7eb55b32006-11-02 01:53:59 +00002499 return 0;
2500}
2501
2502/// This function implements the transforms common to both integer remainder
2503/// instructions (urem and srem). It is called by the visitors to those integer
2504/// remainder instructions.
2505/// @brief Common integer remainder transforms
2506Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2507 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2508
2509 if (Instruction *common = commonRemTransforms(I))
2510 return common;
2511
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002512 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002513 // X % 0 == undef, we don't need to preserve faults!
2514 if (RHS->equalsInt(0))
2515 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2516
Chris Lattner3082c5a2003-02-18 19:28:33 +00002517 if (RHS->equalsInt(1)) // X % 1 == 0
2518 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2519
Chris Lattnerb70f1412006-02-28 05:49:21 +00002520 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2521 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2522 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2523 return R;
2524 } else if (isa<PHINode>(Op0I)) {
2525 if (Instruction *NV = FoldOpIntoPhi(I))
2526 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002527 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002528 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2529 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002530 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002531 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002532 }
2533
Reid Spencer7eb55b32006-11-02 01:53:59 +00002534 return 0;
2535}
2536
2537Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2538 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2539
2540 if (Instruction *common = commonIRemTransforms(I))
2541 return common;
2542
2543 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2544 // X urem C^2 -> X and C
2545 // Check to see if this is an unsigned remainder with an exact power of 2,
2546 // if so, convert to a bitwise and.
2547 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2548 if (isPowerOf2_64(C->getZExtValue()))
2549 return BinaryOperator::createAnd(Op0, SubOne(C));
2550 }
2551
Chris Lattner2e90b732006-02-05 07:54:04 +00002552 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002553 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2554 if (RHSI->getOpcode() == Instruction::Shl &&
2555 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002556 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002557 if (isPowerOf2_64(C1)) {
2558 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2559 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2560 "tmp"), I);
2561 return BinaryOperator::createAnd(Op0, Add);
2562 }
2563 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002564 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002565
Reid Spencer7eb55b32006-11-02 01:53:59 +00002566 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2567 // where C1&C2 are powers of two.
2568 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2569 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2570 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2571 // STO == 0 and SFO == 0 handled above.
2572 if (isPowerOf2_64(STO->getZExtValue()) &&
2573 isPowerOf2_64(SFO->getZExtValue())) {
2574 Value *TrueAnd = InsertNewInstBefore(
2575 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2576 Value *FalseAnd = InsertNewInstBefore(
2577 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2578 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2579 }
2580 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002581 }
2582
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002583 return 0;
2584}
2585
Reid Spencer7eb55b32006-11-02 01:53:59 +00002586Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2587 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2588
2589 if (Instruction *common = commonIRemTransforms(I))
2590 return common;
2591
2592 if (Value *RHSNeg = dyn_castNegVal(Op1))
2593 if (!isa<ConstantInt>(RHSNeg) ||
2594 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2595 // X % -Y -> X % Y
2596 AddUsesToWorkList(I);
2597 I.setOperand(1, RHSNeg);
2598 return &I;
2599 }
2600
2601 // If the top bits of both operands are zero (i.e. we can prove they are
2602 // unsigned inputs), turn this into a urem.
2603 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2604 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2605 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2606 return BinaryOperator::createURem(Op0, Op1, I.getName());
2607 }
2608
2609 return 0;
2610}
2611
2612Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002613 return commonRemTransforms(I);
2614}
2615
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002616// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002617static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2618 if (isSigned) {
2619 // Calculate 0111111111..11111
2620 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2621 int64_t Val = INT64_MAX; // All ones
2622 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2623 return C->getSExtValue() == Val-1;
2624 }
Reid Spencera94d3942007-01-19 21:13:56 +00002625 return C->getZExtValue() == C->getType()->getBitMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002626}
2627
2628// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002629static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2630 if (isSigned) {
2631 // Calculate 1111111111000000000000
2632 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2633 int64_t Val = -1; // All ones
2634 Val <<= TypeBits-1; // Shift over to the right spot
2635 return C->getSExtValue() == Val+1;
2636 }
2637 return C->getZExtValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002638}
2639
Chris Lattner35167c32004-06-09 07:59:58 +00002640// isOneBitSet - Return true if there is exactly one bit set in the specified
2641// constant.
2642static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002643 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002644 return V && (V & (V-1)) == 0;
2645}
2646
Chris Lattner8fc5af42004-09-23 21:46:38 +00002647#if 0 // Currently unused
2648// isLowOnes - Return true if the constant is of the form 0+1+.
2649static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002650 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002651
2652 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002653 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002654
2655 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2656 return U && V && (U & V) == 0;
2657}
2658#endif
2659
2660// isHighOnes - Return true if the constant is of the form 1+0+.
2661// This is the same as lowones(~X).
2662static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002663 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002664 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002665
2666 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002667 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002668
2669 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2670 return U && V && (U & V) == 0;
2671}
2672
Reid Spencer266e42b2006-12-23 06:05:41 +00002673/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002674/// are carefully arranged to allow folding of expressions such as:
2675///
2676/// (A < B) | (A > B) --> (A != B)
2677///
Reid Spencer266e42b2006-12-23 06:05:41 +00002678/// Note that this is only valid if the first and second predicates have the
2679/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002680///
Reid Spencer266e42b2006-12-23 06:05:41 +00002681/// Three bits are used to represent the condition, as follows:
2682/// 0 A > B
2683/// 1 A == B
2684/// 2 A < B
2685///
2686/// <=> Value Definition
2687/// 000 0 Always false
2688/// 001 1 A > B
2689/// 010 2 A == B
2690/// 011 3 A >= B
2691/// 100 4 A < B
2692/// 101 5 A != B
2693/// 110 6 A <= B
2694/// 111 7 Always true
2695///
2696static unsigned getICmpCode(const ICmpInst *ICI) {
2697 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002698 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002699 case ICmpInst::ICMP_UGT: return 1; // 001
2700 case ICmpInst::ICMP_SGT: return 1; // 001
2701 case ICmpInst::ICMP_EQ: return 2; // 010
2702 case ICmpInst::ICMP_UGE: return 3; // 011
2703 case ICmpInst::ICMP_SGE: return 3; // 011
2704 case ICmpInst::ICMP_ULT: return 4; // 100
2705 case ICmpInst::ICMP_SLT: return 4; // 100
2706 case ICmpInst::ICMP_NE: return 5; // 101
2707 case ICmpInst::ICMP_ULE: return 6; // 110
2708 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002709 // True -> 7
2710 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002711 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002712 return 0;
2713 }
2714}
2715
Reid Spencer266e42b2006-12-23 06:05:41 +00002716/// getICmpValue - This is the complement of getICmpCode, which turns an
2717/// opcode and two operands into either a constant true or false, or a brand
2718/// new /// ICmp instruction. The sign is passed in to determine which kind
2719/// of predicate to use in new icmp instructions.
2720static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2721 switch (code) {
2722 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002723 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002724 case 1:
2725 if (sign)
2726 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2727 else
2728 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2729 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2730 case 3:
2731 if (sign)
2732 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2733 else
2734 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2735 case 4:
2736 if (sign)
2737 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2738 else
2739 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2740 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2741 case 6:
2742 if (sign)
2743 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2744 else
2745 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002746 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002747 }
2748}
2749
Reid Spencer266e42b2006-12-23 06:05:41 +00002750static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2751 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2752 (ICmpInst::isSignedPredicate(p1) &&
2753 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2754 (ICmpInst::isSignedPredicate(p2) &&
2755 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2756}
2757
2758namespace {
2759// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2760struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002761 InstCombiner &IC;
2762 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002763 ICmpInst::Predicate pred;
2764 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2765 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2766 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002767 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002768 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2769 if (PredicatesFoldable(pred, ICI->getPredicate()))
2770 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2771 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002772 return false;
2773 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002774 Instruction *apply(Instruction &Log) const {
2775 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2776 if (ICI->getOperand(0) != LHS) {
2777 assert(ICI->getOperand(1) == LHS);
2778 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002779 }
2780
Reid Spencer266e42b2006-12-23 06:05:41 +00002781 unsigned LHSCode = getICmpCode(ICI);
2782 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattner3ac7c262003-08-13 20:16:26 +00002783 unsigned Code;
2784 switch (Log.getOpcode()) {
2785 case Instruction::And: Code = LHSCode & RHSCode; break;
2786 case Instruction::Or: Code = LHSCode | RHSCode; break;
2787 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002788 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002789 }
2790
Reid Spencer266e42b2006-12-23 06:05:41 +00002791 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002792 if (Instruction *I = dyn_cast<Instruction>(RV))
2793 return I;
2794 // Otherwise, it's a constant boolean value...
2795 return IC.ReplaceInstUsesWith(Log, RV);
2796 }
2797};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002798} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002799
Chris Lattnerba1cb382003-09-19 17:17:26 +00002800// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2801// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00002802// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00002803Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00002804 ConstantInt *OpRHS,
2805 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00002806 BinaryOperator &TheAnd) {
2807 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002808 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00002809 if (!Op->isShift())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002810 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002811
Chris Lattnerba1cb382003-09-19 17:17:26 +00002812 switch (Op->getOpcode()) {
2813 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002814 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002815 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2816 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002817 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002818 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002819 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002820 }
2821 break;
2822 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002823 if (Together == AndRHS) // (X | C) & C --> C
2824 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002825
Chris Lattner86102b82005-01-01 16:22:27 +00002826 if (Op->hasOneUse() && Together != OpRHS) {
2827 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2828 std::string Op0Name = Op->getName(); Op->setName("");
2829 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2830 InsertNewInstBefore(Or, TheAnd);
2831 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002832 }
2833 break;
2834 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002835 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002836 // Adding a one to a single bit bit-field should be turned into an XOR
2837 // of the bit. First thing to check is to see if this AND is with a
2838 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002839 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002840
2841 // Clear bits that are not part of the constant.
Reid Spencera94d3942007-01-19 21:13:56 +00002842 AndRHSV &= AndRHS->getType()->getBitMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002843
2844 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002845 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002846 // Ok, at this point, we know that we are masking the result of the
2847 // ADD down to exactly one bit. If the constant we are adding has
2848 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002849 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002850
Chris Lattnerba1cb382003-09-19 17:17:26 +00002851 // Check to see if any bits below the one bit set in AndRHSV are set.
2852 if ((AddRHS & (AndRHSV-1)) == 0) {
2853 // If not, the only thing that can effect the output of the AND is
2854 // the bit specified by AndRHSV. If that bit is set, the effect of
2855 // the XOR is to toggle the bit. If it is clear, then the ADD has
2856 // no effect.
2857 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2858 TheAnd.setOperand(0, X);
2859 return &TheAnd;
2860 } else {
2861 std::string Name = Op->getName(); Op->setName("");
2862 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002863 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002864 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002865 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002866 }
2867 }
2868 }
2869 }
2870 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002871
2872 case Instruction::Shl: {
2873 // We know that the AND will not produce any of the bits shifted in, so if
2874 // the anded constant includes them, clear them now!
2875 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002876 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002877 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2878 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002879
Chris Lattner7e794272004-09-24 15:21:34 +00002880 if (CI == ShlMask) { // Masking out bits that the shift already masks
2881 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2882 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002883 TheAnd.setOperand(1, CI);
2884 return &TheAnd;
2885 }
2886 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002887 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002888 case Instruction::LShr:
2889 {
Chris Lattner2da29172003-09-19 19:05:02 +00002890 // We know that the AND will not produce any of the bits shifted in, so if
2891 // the anded constant includes them, clear them now! This only applies to
2892 // unsigned shifts, because a signed shr may bring in set bits!
2893 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002894 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00002895 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2896 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002897
Reid Spencerfdff9382006-11-08 06:47:33 +00002898 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2899 return ReplaceInstUsesWith(TheAnd, Op);
2900 } else if (CI != AndRHS) {
2901 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2902 return &TheAnd;
2903 }
2904 break;
2905 }
2906 case Instruction::AShr:
2907 // Signed shr.
2908 // See if this is shifting in some sign extension, then masking it out
2909 // with an and.
2910 if (Op->hasOneUse()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002911 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00002912 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00002913 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2914 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002915 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00002916 // Make the argument unsigned.
2917 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00002918 ShVal = InsertNewInstBefore(
2919 BinaryOperator::create(Instruction::LShr, ShVal, OpRHS,
2920 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00002921 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002922 }
Chris Lattner2da29172003-09-19 19:05:02 +00002923 }
2924 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002925 }
2926 return 0;
2927}
2928
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002929
Chris Lattner6862fbd2004-09-29 17:40:11 +00002930/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2931/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00002932/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2933/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00002934/// insert new instructions.
2935Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00002936 bool isSigned, bool Inside,
2937 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002938 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00002939 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00002940 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002941
Chris Lattner6862fbd2004-09-29 17:40:11 +00002942 if (Inside) {
2943 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00002944 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002945
Reid Spencer266e42b2006-12-23 06:05:41 +00002946 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00002947 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002948 ICmpInst::Predicate pred = (isSigned ?
2949 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2950 return new ICmpInst(pred, V, Hi);
2951 }
2952
2953 // Emit V-Lo <u Hi-Lo
2954 Constant *NegLo = ConstantExpr::getNeg(Lo);
2955 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00002956 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00002957 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2958 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002959 }
2960
2961 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00002962 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002963
Reid Spencer266e42b2006-12-23 06:05:41 +00002964 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattner6862fbd2004-09-29 17:40:11 +00002965 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00002966 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002967 ICmpInst::Predicate pred = (isSigned ?
2968 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
2969 return new ICmpInst(pred, V, Hi);
2970 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00002971
Reid Spencer266e42b2006-12-23 06:05:41 +00002972 // Emit V-Lo > Hi-1-Lo
2973 Constant *NegLo = ConstantExpr::getNeg(Lo);
2974 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00002975 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00002976 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
2977 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002978}
2979
Chris Lattnerb4b25302005-09-18 07:22:02 +00002980// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2981// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2982// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2983// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00002984static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002985 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00002986 if (!isShiftedMask_64(V)) return false;
2987
2988 // look for the first zero bit after the run of ones
2989 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2990 // look for the first non-zero bit
2991 ME = 64-CountLeadingZeros_64(V);
2992 return true;
2993}
2994
2995
2996
2997/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2998/// where isSub determines whether the operator is a sub. If we can fold one of
2999/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003000///
3001/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3002/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3003/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3004///
3005/// return (A +/- B).
3006///
3007Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003008 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003009 Instruction &I) {
3010 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3011 if (!LHSI || LHSI->getNumOperands() != 2 ||
3012 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3013
3014 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3015
3016 switch (LHSI->getOpcode()) {
3017 default: return 0;
3018 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003019 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3020 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003021 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003022 break;
3023
3024 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3025 // part, we don't need any explicit masks to take them out of A. If that
3026 // is all N is, ignore it.
3027 unsigned MB, ME;
3028 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencera94d3942007-01-19 21:13:56 +00003029 uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003030 Mask >>= 64-MB+1;
3031 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003032 break;
3033 }
3034 }
Chris Lattneraf517572005-09-18 04:24:45 +00003035 return 0;
3036 case Instruction::Or:
3037 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003038 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003039 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003040 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003041 break;
3042 return 0;
3043 }
3044
3045 Instruction *New;
3046 if (isSub)
3047 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3048 else
3049 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3050 return InsertNewInstBefore(New, I);
3051}
3052
Chris Lattner113f4f42002-06-25 16:13:24 +00003053Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003054 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003055 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003056
Chris Lattner81a7a232004-10-16 18:11:37 +00003057 if (isa<UndefValue>(Op1)) // X & undef -> 0
3058 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3059
Chris Lattner86102b82005-01-01 16:22:27 +00003060 // and X, X = X
3061 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003062 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003063
Chris Lattner5b2edb12006-02-12 08:02:11 +00003064 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003065 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003066 uint64_t KnownZero, KnownOne;
Chris Lattner120ab032007-01-18 22:16:33 +00003067 if (!isa<PackedType>(I.getType())) {
Reid Spencera94d3942007-01-19 21:13:56 +00003068 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner120ab032007-01-18 22:16:33 +00003069 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003070 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003071 } else {
3072 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Op1)) {
3073 if (CP->isAllOnesValue())
3074 return ReplaceInstUsesWith(I, I.getOperand(0));
3075 }
3076 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003077
Zhou Sheng75b871f2007-01-11 12:24:14 +00003078 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003079 uint64_t AndRHSMask = AndRHS->getZExtValue();
Reid Spencera94d3942007-01-19 21:13:56 +00003080 uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003081 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003082
Chris Lattnerba1cb382003-09-19 17:17:26 +00003083 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003084 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003085 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003086 Value *Op0LHS = Op0I->getOperand(0);
3087 Value *Op0RHS = Op0I->getOperand(1);
3088 switch (Op0I->getOpcode()) {
3089 case Instruction::Xor:
3090 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003091 // If the mask is only needed on one incoming arm, push it up.
3092 if (Op0I->hasOneUse()) {
3093 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3094 // Not masking anything out for the LHS, move to RHS.
3095 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3096 Op0RHS->getName()+".masked");
3097 InsertNewInstBefore(NewRHS, I);
3098 return BinaryOperator::create(
3099 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003100 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003101 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003102 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3103 // Not masking anything out for the RHS, move to LHS.
3104 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3105 Op0LHS->getName()+".masked");
3106 InsertNewInstBefore(NewLHS, I);
3107 return BinaryOperator::create(
3108 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3109 }
3110 }
3111
Chris Lattner86102b82005-01-01 16:22:27 +00003112 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003113 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003114 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3115 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3116 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3117 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3118 return BinaryOperator::createAnd(V, AndRHS);
3119 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3120 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003121 break;
3122
3123 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003124 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3125 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3126 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3127 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3128 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003129 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003130 }
3131
Chris Lattner16464b32003-07-23 19:25:52 +00003132 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003133 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003134 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003135 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003136 // If this is an integer truncation or change from signed-to-unsigned, and
3137 // if the source is an and/or with immediate, transform it. This
3138 // frequently occurs for bitfield accesses.
3139 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003140 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003141 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003142 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003143 if (CastOp->getOpcode() == Instruction::And) {
3144 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003145 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3146 // This will fold the two constants together, which may allow
3147 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003148 Instruction *NewCast = CastInst::createTruncOrBitCast(
3149 CastOp->getOperand(0), I.getType(),
3150 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003151 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003152 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003153 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003154 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003155 return BinaryOperator::createAnd(NewCast, C3);
3156 } else if (CastOp->getOpcode() == Instruction::Or) {
3157 // Change: and (cast (or X, C1) to T), C2
3158 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003159 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003160 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3161 return ReplaceInstUsesWith(I, AndRHS);
3162 }
3163 }
Chris Lattner33217db2003-07-23 19:36:21 +00003164 }
Chris Lattner183b3362004-04-09 19:05:30 +00003165
3166 // Try to fold constant and into select arguments.
3167 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003168 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003169 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003170 if (isa<PHINode>(Op0))
3171 if (Instruction *NV = FoldOpIntoPhi(I))
3172 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003173 }
3174
Chris Lattnerbb74e222003-03-10 23:06:50 +00003175 Value *Op0NotVal = dyn_castNotVal(Op0);
3176 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003177
Chris Lattner023a4832004-06-18 06:07:51 +00003178 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3179 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3180
Misha Brukman9c003d82004-07-30 12:50:08 +00003181 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003182 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003183 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3184 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003185 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003186 return BinaryOperator::createNot(Or);
3187 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003188
3189 {
3190 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003191 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3192 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3193 return ReplaceInstUsesWith(I, Op1);
3194 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3195 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3196 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003197
3198 if (Op0->hasOneUse() &&
3199 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3200 if (A == Op1) { // (A^B)&A -> A&(A^B)
3201 I.swapOperands(); // Simplify below
3202 std::swap(Op0, Op1);
3203 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3204 cast<BinaryOperator>(Op0)->swapOperands();
3205 I.swapOperands(); // Simplify below
3206 std::swap(Op0, Op1);
3207 }
3208 }
3209 if (Op1->hasOneUse() &&
3210 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3211 if (B == Op0) { // B&(A^B) -> B&(B^A)
3212 cast<BinaryOperator>(Op1)->swapOperands();
3213 std::swap(A, B);
3214 }
3215 if (A == Op0) { // A&(A^B) -> A & ~B
3216 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3217 InsertNewInstBefore(NotB, I);
3218 return BinaryOperator::createAnd(A, NotB);
3219 }
3220 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003221 }
3222
Reid Spencer266e42b2006-12-23 06:05:41 +00003223 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3224 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3225 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003226 return R;
3227
Chris Lattner623826c2004-09-28 21:48:02 +00003228 Value *LHSVal, *RHSVal;
3229 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003230 ICmpInst::Predicate LHSCC, RHSCC;
3231 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3232 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3233 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3234 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3235 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3236 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3237 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3238 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003239 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003240 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3241 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3242 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3243 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003244 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003245 std::swap(LHS, RHS);
3246 std::swap(LHSCst, RHSCst);
3247 std::swap(LHSCC, RHSCC);
3248 }
3249
Reid Spencer266e42b2006-12-23 06:05:41 +00003250 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003251 // comparing a value against two constants and and'ing the result
3252 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003253 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3254 // (from the FoldICmpLogical check above), that the two constants
3255 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003256 assert(LHSCst != RHSCst && "Compares not folded above?");
3257
3258 switch (LHSCC) {
3259 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003260 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003261 switch (RHSCC) {
3262 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003263 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3264 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3265 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003266 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003267 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3268 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3269 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003270 return ReplaceInstUsesWith(I, LHS);
3271 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003272 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003273 switch (RHSCC) {
3274 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003275 case ICmpInst::ICMP_ULT:
3276 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3277 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3278 break; // (X != 13 & X u< 15) -> no change
3279 case ICmpInst::ICMP_SLT:
3280 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3281 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3282 break; // (X != 13 & X s< 15) -> no change
3283 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3284 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3285 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003286 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003287 case ICmpInst::ICMP_NE:
3288 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003289 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3290 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3291 LHSVal->getName()+".off");
3292 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00003293 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3294 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00003295 }
3296 break; // (X != 13 & X != 15) -> no change
3297 }
3298 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003299 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003300 switch (RHSCC) {
3301 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003302 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3303 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003304 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003305 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3306 break;
3307 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3308 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003309 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003310 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3311 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003312 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003313 break;
3314 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003315 switch (RHSCC) {
3316 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003317 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3318 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003319 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003320 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3321 break;
3322 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3323 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003324 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003325 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3326 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003327 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003328 break;
3329 case ICmpInst::ICMP_UGT:
3330 switch (RHSCC) {
3331 default: assert(0 && "Unknown integer condition code!");
3332 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3333 return ReplaceInstUsesWith(I, LHS);
3334 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3335 return ReplaceInstUsesWith(I, RHS);
3336 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3337 break;
3338 case ICmpInst::ICMP_NE:
3339 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3340 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3341 break; // (X u> 13 & X != 15) -> no change
3342 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3343 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3344 true, I);
3345 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3346 break;
3347 }
3348 break;
3349 case ICmpInst::ICMP_SGT:
3350 switch (RHSCC) {
3351 default: assert(0 && "Unknown integer condition code!");
3352 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3353 return ReplaceInstUsesWith(I, LHS);
3354 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3355 return ReplaceInstUsesWith(I, RHS);
3356 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3357 break;
3358 case ICmpInst::ICMP_NE:
3359 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3360 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3361 break; // (X s> 13 & X != 15) -> no change
3362 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3363 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3364 true, I);
3365 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3366 break;
3367 }
3368 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003369 }
3370 }
3371 }
3372
Chris Lattner3af10532006-05-05 06:39:07 +00003373 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003374 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3375 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3376 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3377 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003378 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003379 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003380 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3381 I.getType(), TD) &&
3382 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3383 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003384 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3385 Op1C->getOperand(0),
3386 I.getName());
3387 InsertNewInstBefore(NewOp, I);
3388 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3389 }
Chris Lattner3af10532006-05-05 06:39:07 +00003390 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003391
3392 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003393 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3394 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3395 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003396 SI0->getOperand(1) == SI1->getOperand(1) &&
3397 (SI0->hasOneUse() || SI1->hasOneUse())) {
3398 Instruction *NewOp =
3399 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3400 SI1->getOperand(0),
3401 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003402 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3403 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003404 }
Chris Lattner3af10532006-05-05 06:39:07 +00003405 }
3406
Chris Lattner113f4f42002-06-25 16:13:24 +00003407 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003408}
3409
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003410/// CollectBSwapParts - Look to see if the specified value defines a single byte
3411/// in the result. If it does, and if the specified byte hasn't been filled in
3412/// yet, fill it in and return false.
3413static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3414 Instruction *I = dyn_cast<Instruction>(V);
3415 if (I == 0) return true;
3416
3417 // If this is an or instruction, it is an inner node of the bswap.
3418 if (I->getOpcode() == Instruction::Or)
3419 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3420 CollectBSwapParts(I->getOperand(1), ByteValues);
3421
3422 // If this is a shift by a constant int, and it is "24", then its operand
3423 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00003424 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003425 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003426 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003427 8*(ByteValues.size()-1))
3428 return true;
3429
3430 unsigned DestNo;
3431 if (I->getOpcode() == Instruction::Shl) {
3432 // X << 24 defines the top byte with the lowest of the input bytes.
3433 DestNo = ByteValues.size()-1;
3434 } else {
3435 // X >>u 24 defines the low byte with the highest of the input bytes.
3436 DestNo = 0;
3437 }
3438
3439 // If the destination byte value is already defined, the values are or'd
3440 // together, which isn't a bswap (unless it's an or of the same bits).
3441 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3442 return true;
3443 ByteValues[DestNo] = I->getOperand(0);
3444 return false;
3445 }
3446
3447 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3448 // don't have this.
3449 Value *Shift = 0, *ShiftLHS = 0;
3450 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3451 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3452 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3453 return true;
3454 Instruction *SI = cast<Instruction>(Shift);
3455
3456 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003457 if (ShiftAmt->getZExtValue() & 7 ||
3458 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003459 return true;
3460
3461 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3462 unsigned DestByte;
3463 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003464 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003465 break;
3466 // Unknown mask for bswap.
3467 if (DestByte == ByteValues.size()) return true;
3468
Reid Spencere0fc4df2006-10-20 07:07:24 +00003469 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003470 unsigned SrcByte;
3471 if (SI->getOpcode() == Instruction::Shl)
3472 SrcByte = DestByte - ShiftBytes;
3473 else
3474 SrcByte = DestByte + ShiftBytes;
3475
3476 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3477 if (SrcByte != ByteValues.size()-DestByte-1)
3478 return true;
3479
3480 // If the destination byte value is already defined, the values are or'd
3481 // together, which isn't a bswap (unless it's an or of the same bits).
3482 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3483 return true;
3484 ByteValues[DestByte] = SI->getOperand(0);
3485 return false;
3486}
3487
3488/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3489/// If so, insert the new bswap intrinsic and return it.
3490Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Reid Spencer2341c222007-02-02 02:16:23 +00003491 // We cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00003492 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003493 return 0;
3494
3495 /// ByteValues - For each byte of the result, we keep track of which value
3496 /// defines each byte.
3497 std::vector<Value*> ByteValues;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00003498 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003499
3500 // Try to find all the pieces corresponding to the bswap.
3501 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3502 CollectBSwapParts(I.getOperand(1), ByteValues))
3503 return 0;
3504
3505 // Check to see if all of the bytes come from the same value.
3506 Value *V = ByteValues[0];
3507 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3508
3509 // Check to make sure that all of the bytes come from the same value.
3510 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3511 if (ByteValues[i] != V)
3512 return 0;
3513
3514 // If they do then *success* we can turn this into a bswap. Figure out what
3515 // bswap to make it into.
3516 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003517 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00003518 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003519 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00003520 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003521 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00003522 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003523 FnName = "llvm.bswap.i64";
3524 else
3525 assert(0 && "Unknown integer type!");
Chris Lattnerfbc524f2007-01-07 06:58:05 +00003526 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003527 return new CallInst(F, V);
3528}
3529
3530
Chris Lattner113f4f42002-06-25 16:13:24 +00003531Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003532 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003533 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003534
Chris Lattner81a7a232004-10-16 18:11:37 +00003535 if (isa<UndefValue>(Op1))
3536 return ReplaceInstUsesWith(I, // X | undef -> -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003537 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003538
Chris Lattner5b2edb12006-02-12 08:02:11 +00003539 // or X, X = X
3540 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003541 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003542
Chris Lattner5b2edb12006-02-12 08:02:11 +00003543 // See if we can simplify any instructions used by the instruction whose sole
3544 // purpose is to compute bits we don't care about.
3545 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003546 if (!isa<PackedType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00003547 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003548 KnownZero, KnownOne))
3549 return &I;
3550
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003551 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003552 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003553 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003554 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3555 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003556 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3557 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003558 InsertNewInstBefore(Or, I);
3559 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3560 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003561
Chris Lattnerd4252a72004-07-30 07:50:03 +00003562 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3563 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3564 std::string Op0Name = Op0->getName(); Op0->setName("");
3565 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3566 InsertNewInstBefore(Or, I);
3567 return BinaryOperator::createXor(Or,
3568 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003569 }
Chris Lattner183b3362004-04-09 19:05:30 +00003570
3571 // Try to fold constant and into select arguments.
3572 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003573 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003574 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003575 if (isa<PHINode>(Op0))
3576 if (Instruction *NV = FoldOpIntoPhi(I))
3577 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003578 }
3579
Chris Lattner330628a2006-01-06 17:59:59 +00003580 Value *A = 0, *B = 0;
3581 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003582
3583 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3584 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3585 return ReplaceInstUsesWith(I, Op1);
3586 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3587 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3588 return ReplaceInstUsesWith(I, Op0);
3589
Chris Lattnerb7845d62006-07-10 20:25:24 +00003590 // (A | B) | C and A | (B | C) -> bswap if possible.
3591 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003592 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003593 match(Op1, m_Or(m_Value(), m_Value())) ||
3594 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3595 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003596 if (Instruction *BSwap = MatchBSwap(I))
3597 return BSwap;
3598 }
3599
Chris Lattnerb62f5082005-05-09 04:58:36 +00003600 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3601 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003602 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003603 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3604 Op0->setName("");
3605 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3606 }
3607
3608 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3609 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003610 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003611 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3612 Op0->setName("");
3613 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3614 }
3615
Chris Lattner15212982005-09-18 03:42:07 +00003616 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003617 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003618 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3619
3620 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3621 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3622
3623
Chris Lattner01f56c62005-09-18 06:02:59 +00003624 // If we have: ((V + N) & C1) | (V & C2)
3625 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3626 // replace with V+N.
3627 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003628 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003629 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003630 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3631 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003632 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003633 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003634 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003635 return ReplaceInstUsesWith(I, A);
3636 }
3637 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003638 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003639 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3640 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003641 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003642 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003643 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003644 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003645 }
3646 }
3647 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003648
3649 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003650 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3651 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3652 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003653 SI0->getOperand(1) == SI1->getOperand(1) &&
3654 (SI0->hasOneUse() || SI1->hasOneUse())) {
3655 Instruction *NewOp =
3656 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3657 SI1->getOperand(0),
3658 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003659 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3660 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003661 }
3662 }
Chris Lattner812aab72003-08-12 19:11:07 +00003663
Chris Lattnerd4252a72004-07-30 07:50:03 +00003664 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3665 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003666 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003667 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003668 } else {
3669 A = 0;
3670 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003671 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003672 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3673 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003674 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003675 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003676
Misha Brukman9c003d82004-07-30 12:50:08 +00003677 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003678 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3679 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3680 I.getName()+".demorgan"), I);
3681 return BinaryOperator::createNot(And);
3682 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003683 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003684
Reid Spencer266e42b2006-12-23 06:05:41 +00003685 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3686 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3687 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003688 return R;
3689
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003690 Value *LHSVal, *RHSVal;
3691 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003692 ICmpInst::Predicate LHSCC, RHSCC;
3693 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3694 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3695 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3696 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3697 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3698 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3699 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3700 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003701 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003702 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3703 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3704 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3705 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003706 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003707 std::swap(LHS, RHS);
3708 std::swap(LHSCst, RHSCst);
3709 std::swap(LHSCC, RHSCC);
3710 }
3711
Reid Spencer266e42b2006-12-23 06:05:41 +00003712 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003713 // comparing a value against two constants and or'ing the result
3714 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003715 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3716 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003717 // equal.
3718 assert(LHSCst != RHSCst && "Compares not folded above?");
3719
3720 switch (LHSCC) {
3721 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003722 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003723 switch (RHSCC) {
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 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3727 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3728 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3729 LHSVal->getName()+".off");
3730 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003731 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003732 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003733 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003734 break; // (X == 13 | X == 15) -> no change
3735 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3736 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003737 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003738 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3739 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3740 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003741 return ReplaceInstUsesWith(I, RHS);
3742 }
3743 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003744 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003745 switch (RHSCC) {
3746 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003747 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3748 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3749 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003750 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003751 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3752 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3753 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003754 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003755 }
3756 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003757 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003758 switch (RHSCC) {
3759 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003760 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003761 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003762 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3763 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3764 false, I);
3765 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3766 break;
3767 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3768 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003769 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003770 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3771 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003772 }
3773 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003774 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003775 switch (RHSCC) {
3776 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003777 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3778 break;
3779 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3780 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3781 false, I);
3782 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3783 break;
3784 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3785 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3786 return ReplaceInstUsesWith(I, RHS);
3787 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3788 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003789 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003790 break;
3791 case ICmpInst::ICMP_UGT:
3792 switch (RHSCC) {
3793 default: assert(0 && "Unknown integer condition code!");
3794 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3795 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3796 return ReplaceInstUsesWith(I, LHS);
3797 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3798 break;
3799 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3800 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003801 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003802 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3803 break;
3804 }
3805 break;
3806 case ICmpInst::ICMP_SGT:
3807 switch (RHSCC) {
3808 default: assert(0 && "Unknown integer condition code!");
3809 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3810 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3811 return ReplaceInstUsesWith(I, LHS);
3812 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3813 break;
3814 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3815 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003816 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003817 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3818 break;
3819 }
3820 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003821 }
3822 }
3823 }
Chris Lattner3af10532006-05-05 06:39:07 +00003824
3825 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003826 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003827 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003828 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3829 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003830 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003831 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003832 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3833 I.getType(), TD) &&
3834 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3835 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003836 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3837 Op1C->getOperand(0),
3838 I.getName());
3839 InsertNewInstBefore(NewOp, I);
3840 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3841 }
Chris Lattner3af10532006-05-05 06:39:07 +00003842 }
Chris Lattner3af10532006-05-05 06:39:07 +00003843
Chris Lattner15212982005-09-18 03:42:07 +00003844
Chris Lattner113f4f42002-06-25 16:13:24 +00003845 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003846}
3847
Chris Lattnerc2076352004-02-16 01:20:27 +00003848// XorSelf - Implements: X ^ X --> 0
3849struct XorSelf {
3850 Value *RHS;
3851 XorSelf(Value *rhs) : RHS(rhs) {}
3852 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3853 Instruction *apply(BinaryOperator &Xor) const {
3854 return &Xor;
3855 }
3856};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003857
3858
Chris Lattner113f4f42002-06-25 16:13:24 +00003859Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003860 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003861 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003862
Chris Lattner81a7a232004-10-16 18:11:37 +00003863 if (isa<UndefValue>(Op1))
3864 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3865
Chris Lattnerc2076352004-02-16 01:20:27 +00003866 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3867 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3868 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003869 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003870 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003871
3872 // See if we can simplify any instructions used by the instruction whose sole
3873 // purpose is to compute bits we don't care about.
3874 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003875 if (!isa<PackedType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00003876 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003877 KnownZero, KnownOne))
3878 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003879
Zhou Sheng75b871f2007-01-11 12:24:14 +00003880 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003881 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3882 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00003883 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00003884 return new ICmpInst(ICI->getInversePredicate(),
3885 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003886
Reid Spencer266e42b2006-12-23 06:05:41 +00003887 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00003888 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003889 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3890 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003891 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3892 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003893 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003894 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003895 }
Chris Lattner023a4832004-06-18 06:07:51 +00003896
3897 // ~(~X & Y) --> (X | ~Y)
3898 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3899 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3900 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3901 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003902 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003903 Op0I->getOperand(1)->getName()+".not");
3904 InsertNewInstBefore(NotY, I);
3905 return BinaryOperator::createOr(Op0NotVal, NotY);
3906 }
3907 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003908
Chris Lattner97638592003-07-23 21:37:07 +00003909 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003910 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003911 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003912 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003913 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3914 return BinaryOperator::createSub(
3915 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003916 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003917 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003918 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003919 } else if (Op0I->getOpcode() == Instruction::Or) {
3920 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3921 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3922 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3923 // Anything in both C1 and C2 is known to be zero, remove it from
3924 // NewRHS.
3925 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3926 NewRHS = ConstantExpr::getAnd(NewRHS,
3927 ConstantExpr::getNot(CommonBits));
3928 WorkList.push_back(Op0I);
3929 I.setOperand(0, Op0I->getOperand(0));
3930 I.setOperand(1, NewRHS);
3931 return &I;
3932 }
Chris Lattner97638592003-07-23 21:37:07 +00003933 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003934 }
Chris Lattner183b3362004-04-09 19:05:30 +00003935
3936 // Try to fold constant and into select arguments.
3937 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003938 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003939 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003940 if (isa<PHINode>(Op0))
3941 if (Instruction *NV = FoldOpIntoPhi(I))
3942 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003943 }
3944
Chris Lattnerbb74e222003-03-10 23:06:50 +00003945 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003946 if (X == Op1)
3947 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003948 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003949
Chris Lattnerbb74e222003-03-10 23:06:50 +00003950 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003951 if (X == Op0)
3952 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003953 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003954
Chris Lattnerdcd07922006-04-01 08:03:55 +00003955 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003956 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003957 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003958 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003959 I.swapOperands();
3960 std::swap(Op0, Op1);
3961 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003962 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003963 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003964 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003965 } else if (Op1I->getOpcode() == Instruction::Xor) {
3966 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3967 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3968 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3969 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003970 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3971 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3972 Op1I->swapOperands();
3973 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3974 I.swapOperands(); // Simplified below.
3975 std::swap(Op0, Op1);
3976 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003977 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003978
Chris Lattnerdcd07922006-04-01 08:03:55 +00003979 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003980 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003981 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003982 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003983 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003984 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3985 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003986 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003987 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003988 } else if (Op0I->getOpcode() == Instruction::Xor) {
3989 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3990 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3991 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3992 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003993 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3994 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3995 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003996 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3997 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003998 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3999 InsertNewInstBefore(N, I);
4000 return BinaryOperator::createAnd(N, Op1);
4001 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004002 }
4003
Reid Spencer266e42b2006-12-23 06:05:41 +00004004 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4005 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4006 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004007 return R;
4008
Chris Lattner3af10532006-05-05 06:39:07 +00004009 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004010 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004011 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004012 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4013 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004014 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004015 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004016 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4017 I.getType(), TD) &&
4018 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4019 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004020 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4021 Op1C->getOperand(0),
4022 I.getName());
4023 InsertNewInstBefore(NewOp, I);
4024 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4025 }
Chris Lattner3af10532006-05-05 06:39:07 +00004026 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004027
4028 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004029 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4030 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4031 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004032 SI0->getOperand(1) == SI1->getOperand(1) &&
4033 (SI0->hasOneUse() || SI1->hasOneUse())) {
4034 Instruction *NewOp =
4035 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4036 SI1->getOperand(0),
4037 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00004038 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4039 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004040 }
4041 }
Chris Lattner3af10532006-05-05 06:39:07 +00004042
Chris Lattner113f4f42002-06-25 16:13:24 +00004043 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004044}
4045
Chris Lattner6862fbd2004-09-29 17:40:11 +00004046static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004047 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004048}
4049
4050/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4051/// overflowed for this type.
4052static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4053 ConstantInt *In2) {
4054 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4055
Reid Spencerc635f472006-12-31 05:48:39 +00004056 return cast<ConstantInt>(Result)->getZExtValue() <
4057 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004058}
4059
Chris Lattner0798af32005-01-13 20:14:25 +00004060/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4061/// code necessary to compute the offset from the base pointer (without adding
4062/// in the base pointer). Return the result as a signed integer of intptr size.
4063static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4064 TargetData &TD = IC.getTargetData();
4065 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004066 const Type *IntPtrTy = TD.getIntPtrType();
4067 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004068
4069 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004070 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004071
Chris Lattner0798af32005-01-13 20:14:25 +00004072 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4073 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004074 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004075 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004076 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4077 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004078 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004079 Scale = ConstantExpr::getMul(OpC, Scale);
4080 if (Constant *RC = dyn_cast<Constant>(Result))
4081 Result = ConstantExpr::getAdd(RC, Scale);
4082 else {
4083 // Emit an add instruction.
4084 Result = IC.InsertNewInstBefore(
4085 BinaryOperator::createAdd(Result, Scale,
4086 GEP->getName()+".offs"), I);
4087 }
4088 }
4089 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004090 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004091 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004092 Op->getName()+".c"), I);
4093 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004094 // We'll let instcombine(mul) convert this to a shl if possible.
4095 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4096 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004097
4098 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004099 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004100 GEP->getName()+".offs"), I);
4101 }
4102 }
4103 return Result;
4104}
4105
Reid Spencer266e42b2006-12-23 06:05:41 +00004106/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004107/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004108Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4109 ICmpInst::Predicate Cond,
4110 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004111 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004112
4113 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4114 if (isa<PointerType>(CI->getOperand(0)->getType()))
4115 RHS = CI->getOperand(0);
4116
Chris Lattner0798af32005-01-13 20:14:25 +00004117 Value *PtrBase = GEPLHS->getOperand(0);
4118 if (PtrBase == RHS) {
4119 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004120 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4121 // each index is zero or not.
4122 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004123 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004124 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4125 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004126 bool EmitIt = true;
4127 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4128 if (isa<UndefValue>(C)) // undef index -> undef.
4129 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4130 if (C->isNullValue())
4131 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004132 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4133 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004134 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004135 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004136 ConstantInt::get(Type::Int1Ty,
4137 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004138 }
4139
4140 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004141 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004142 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004143 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4144 if (InVal == 0)
4145 InVal = Comp;
4146 else {
4147 InVal = InsertNewInstBefore(InVal, I);
4148 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004149 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004150 InVal = BinaryOperator::createOr(InVal, Comp);
4151 else // True if all are equal
4152 InVal = BinaryOperator::createAnd(InVal, Comp);
4153 }
4154 }
4155 }
4156
4157 if (InVal)
4158 return InVal;
4159 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004160 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004161 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4162 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004163 }
Chris Lattner0798af32005-01-13 20:14:25 +00004164
Reid Spencer266e42b2006-12-23 06:05:41 +00004165 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004166 // the result to fold to a constant!
4167 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4168 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4169 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004170 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4171 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004172 }
4173 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004174 // If the base pointers are different, but the indices are the same, just
4175 // compare the base pointer.
4176 if (PtrBase != GEPRHS->getOperand(0)) {
4177 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004178 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004179 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004180 if (IndicesTheSame)
4181 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4182 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4183 IndicesTheSame = false;
4184 break;
4185 }
4186
4187 // If all indices are the same, just compare the base pointers.
4188 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004189 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4190 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004191
4192 // Otherwise, the base pointers are different and the indices are
4193 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004194 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004195 }
Chris Lattner0798af32005-01-13 20:14:25 +00004196
Chris Lattner81e84172005-01-13 22:25:21 +00004197 // If one of the GEPs has all zero indices, recurse.
4198 bool AllZeros = true;
4199 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4200 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4201 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4202 AllZeros = false;
4203 break;
4204 }
4205 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004206 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4207 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004208
4209 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004210 AllZeros = true;
4211 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4212 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4213 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4214 AllZeros = false;
4215 break;
4216 }
4217 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004218 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004219
Chris Lattner4fa89822005-01-14 00:20:05 +00004220 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4221 // If the GEPs only differ by one index, compare it.
4222 unsigned NumDifferences = 0; // Keep track of # differences.
4223 unsigned DiffOperand = 0; // The operand that differs.
4224 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4225 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004226 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4227 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004228 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004229 NumDifferences = 2;
4230 break;
4231 } else {
4232 if (NumDifferences++) break;
4233 DiffOperand = i;
4234 }
4235 }
4236
4237 if (NumDifferences == 0) // SAME GEP?
4238 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004239 ConstantInt::get(Type::Int1Ty,
4240 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004241 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004242 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4243 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004244 // Make sure we do a signed comparison here.
4245 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004246 }
4247 }
4248
Reid Spencer266e42b2006-12-23 06:05:41 +00004249 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004250 // the result to fold to a constant!
4251 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4252 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4253 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4254 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4255 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004256 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004257 }
4258 }
4259 return 0;
4260}
4261
Reid Spencer266e42b2006-12-23 06:05:41 +00004262Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4263 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004264 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004265
Chris Lattner6ee923f2007-01-14 19:42:17 +00004266 // Fold trivial predicates.
4267 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4268 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4269 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4270 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4271
4272 // Simplify 'fcmp pred X, X'
4273 if (Op0 == Op1) {
4274 switch (I.getPredicate()) {
4275 default: assert(0 && "Unknown predicate!");
4276 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4277 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4278 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4279 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4280 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4281 case FCmpInst::FCMP_OLT: // True if ordered and less than
4282 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4283 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4284
4285 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4286 case FCmpInst::FCMP_ULT: // True if unordered or less than
4287 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4288 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4289 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4290 I.setPredicate(FCmpInst::FCMP_UNO);
4291 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4292 return &I;
4293
4294 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4295 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4296 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4297 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4298 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4299 I.setPredicate(FCmpInst::FCMP_ORD);
4300 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4301 return &I;
4302 }
4303 }
4304
Reid Spencer266e42b2006-12-23 06:05:41 +00004305 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004306 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004307
Reid Spencer266e42b2006-12-23 06:05:41 +00004308 // Handle fcmp with constant RHS
4309 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4310 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4311 switch (LHSI->getOpcode()) {
4312 case Instruction::PHI:
4313 if (Instruction *NV = FoldOpIntoPhi(I))
4314 return NV;
4315 break;
4316 case Instruction::Select:
4317 // If either operand of the select is a constant, we can fold the
4318 // comparison into the select arms, which will cause one to be
4319 // constant folded and the select turned into a bitwise or.
4320 Value *Op1 = 0, *Op2 = 0;
4321 if (LHSI->hasOneUse()) {
4322 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4323 // Fold the known value into the constant operand.
4324 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4325 // Insert a new FCmp of the other select operand.
4326 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4327 LHSI->getOperand(2), RHSC,
4328 I.getName()), I);
4329 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4330 // Fold the known value into the constant operand.
4331 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4332 // Insert a new FCmp of the other select operand.
4333 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4334 LHSI->getOperand(1), RHSC,
4335 I.getName()), I);
4336 }
4337 }
4338
4339 if (Op1)
4340 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4341 break;
4342 }
4343 }
4344
4345 return Changed ? &I : 0;
4346}
4347
4348Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4349 bool Changed = SimplifyCompare(I);
4350 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4351 const Type *Ty = Op0->getType();
4352
4353 // icmp X, X
4354 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004355 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4356 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004357
4358 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004359 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004360
4361 // icmp of GlobalValues can never equal each other as long as they aren't
4362 // external weak linkage type.
4363 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4364 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4365 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004366 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4367 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004368
4369 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004370 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004371 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4372 isa<ConstantPointerNull>(Op0)) &&
4373 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004374 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004375 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4376 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004377
Reid Spencer266e42b2006-12-23 06:05:41 +00004378 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004379 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004380 switch (I.getPredicate()) {
4381 default: assert(0 && "Invalid icmp instruction!");
4382 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004383 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004384 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004385 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004386 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004387 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004388 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004389
Reid Spencer266e42b2006-12-23 06:05:41 +00004390 case ICmpInst::ICMP_UGT:
4391 case ICmpInst::ICMP_SGT:
4392 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004393 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004394 case ICmpInst::ICMP_ULT:
4395 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004396 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4397 InsertNewInstBefore(Not, I);
4398 return BinaryOperator::createAnd(Not, Op1);
4399 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004400 case ICmpInst::ICMP_UGE:
4401 case ICmpInst::ICMP_SGE:
4402 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004403 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004404 case ICmpInst::ICMP_ULE:
4405 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004406 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4407 InsertNewInstBefore(Not, I);
4408 return BinaryOperator::createOr(Not, Op1);
4409 }
4410 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004411 }
4412
Chris Lattner2dd01742004-06-09 04:24:29 +00004413 // See if we are doing a comparison between a constant and an instruction that
4414 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004415 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004416 switch (I.getPredicate()) {
4417 default: break;
4418 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4419 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004420 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004421 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4422 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4423 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4424 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4425 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004426
Reid Spencer266e42b2006-12-23 06:05:41 +00004427 case ICmpInst::ICMP_SLT:
4428 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004429 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004430 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4431 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4432 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4433 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4434 break;
4435
4436 case ICmpInst::ICMP_UGT:
4437 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004438 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004439 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4440 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4441 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4442 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4443 break;
4444
4445 case ICmpInst::ICMP_SGT:
4446 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004447 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004448 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4449 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4450 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4451 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4452 break;
4453
4454 case ICmpInst::ICMP_ULE:
4455 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004456 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004457 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4458 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4459 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4460 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4461 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004462
Reid Spencer266e42b2006-12-23 06:05:41 +00004463 case ICmpInst::ICMP_SLE:
4464 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004465 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004466 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4467 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4468 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4469 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4470 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004471
Reid Spencer266e42b2006-12-23 06:05:41 +00004472 case ICmpInst::ICMP_UGE:
4473 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004474 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004475 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4476 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4477 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4478 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4479 break;
4480
4481 case ICmpInst::ICMP_SGE:
4482 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004483 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004484 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4485 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4486 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4487 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4488 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004489 }
4490
Reid Spencer266e42b2006-12-23 06:05:41 +00004491 // If we still have a icmp le or icmp ge instruction, turn it into the
4492 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004493 // already been handled above, this requires little checking.
4494 //
Reid Spencer266e42b2006-12-23 06:05:41 +00004495 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4496 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4497 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4498 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4499 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4500 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4501 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4502 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00004503
4504 // See if we can fold the comparison based on bits known to be zero or one
4505 // in the input.
4506 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00004507 if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
Chris Lattneree0f2802006-02-12 02:07:56 +00004508 KnownZero, KnownOne, 0))
4509 return &I;
4510
4511 // Given the known and unknown bits, compute a range that the LHS could be
4512 // in.
4513 if (KnownOne | KnownZero) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004514 // Compute the Min, Max and RHS values based on the known bits. For the
4515 // EQ and NE we use unsigned values.
Reid Spencer910f23f2006-12-23 19:17:57 +00004516 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4517 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00004518 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4519 SRHSVal = CI->getSExtValue();
4520 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4521 SMax);
4522 } else {
4523 URHSVal = CI->getZExtValue();
4524 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4525 UMax);
4526 }
4527 switch (I.getPredicate()) { // LE/GE have been folded already.
4528 default: assert(0 && "Unknown icmp opcode!");
4529 case ICmpInst::ICMP_EQ:
4530 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004531 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004532 break;
4533 case ICmpInst::ICMP_NE:
4534 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004535 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004536 break;
4537 case ICmpInst::ICMP_ULT:
4538 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004539 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004540 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004541 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004542 break;
4543 case ICmpInst::ICMP_UGT:
4544 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004545 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004546 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004547 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004548 break;
4549 case ICmpInst::ICMP_SLT:
4550 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004551 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004552 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004553 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004554 break;
4555 case ICmpInst::ICMP_SGT:
4556 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004557 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004558 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004559 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004560 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004561 }
4562 }
4563
Reid Spencer266e42b2006-12-23 06:05:41 +00004564 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004565 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004566 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004567 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004568 switch (LHSI->getOpcode()) {
4569 case Instruction::And:
4570 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4571 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004572 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4573
Reid Spencer266e42b2006-12-23 06:05:41 +00004574 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004575 // and/compare to be the input width without changing the value
4576 // produced, eliminating a cast.
4577 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4578 // We can do this transformation if either the AND constant does not
4579 // have its sign bit set or if it is an equality comparison.
4580 // Extending a relational comparison when we're checking the sign
4581 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004582 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004583 (I.isEquality() ||
4584 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4585 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4586 ConstantInt *NewCST;
4587 ConstantInt *NewCI;
Reid Spencerc635f472006-12-31 05:48:39 +00004588 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4589 AndCST->getZExtValue());
4590 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4591 CI->getZExtValue());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004592 Instruction *NewAnd =
4593 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4594 LHSI->getName());
4595 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004596 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004597 }
4598 }
4599
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004600 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4601 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4602 // happens a LOT in code produced by the C front-end, for bitfield
4603 // access.
Reid Spencer2341c222007-02-02 02:16:23 +00004604 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4605 if (Shift && !Shift->isShift())
4606 Shift = 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004607
4608 // Check to see if there is a noop-cast between the shift and the and.
4609 if (!Shift) {
4610 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
Reid Spencer2341c222007-02-02 02:16:23 +00004611 if (CI->getOpcode() == Instruction::BitCast) {
4612 Shift = dyn_cast<BinaryOperator>(CI->getOperand(0));
4613 if (Shift && !Shift->isShift())
4614 Shift = 0;
4615 }
Chris Lattneree0f2802006-02-12 02:07:56 +00004616 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004617
Reid Spencere0fc4df2006-10-20 07:07:24 +00004618 ConstantInt *ShAmt;
4619 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004620 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4621 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004622
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004623 // We can fold this as long as we can't shift unknown bits
4624 // into the mask. This can only happen with signed shift
4625 // rights, as they sign-extend.
4626 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004627 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004628 if (!CanFold) {
4629 // To test for the bad case of the signed shr, see if any
4630 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004631 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004632 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4633
Reid Spencer2341c222007-02-02 02:16:23 +00004634 Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004635 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004636 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4637 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004638 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4639 CanFold = true;
4640 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004641
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004642 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004643 Constant *NewCst;
4644 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004645 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004646 else
4647 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004648
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004649 // Check to see if we are shifting out any of the bits being
4650 // compared.
4651 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4652 // If we shifted bits out, the fold is not going to work out.
4653 // As a special case, check to see if this means that the
4654 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004655 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004656 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004657 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004658 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004659 } else {
4660 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004661 Constant *NewAndCST;
4662 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004663 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004664 else
4665 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4666 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00004667 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004668 WorkList.push_back(Shift); // Shift is dead.
4669 AddUsesToWorkList(I);
4670 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004671 }
4672 }
Chris Lattner35167c32004-06-09 07:59:58 +00004673 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004674
4675 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4676 // preferable because it allows the C<<Y expression to be hoisted out
4677 // of a loop if Y is invariant and X is not.
4678 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004679 I.isEquality() && !Shift->isArithmeticShift() &&
4680 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004681 // Compute C << Y.
4682 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004683 if (Shift->getOpcode() == Instruction::LShr) {
Reid Spencer2341c222007-02-02 02:16:23 +00004684 NS = BinaryOperator::create(Instruction::Shl, AndCST,
4685 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004686 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004687 // Insert a logical shift.
Reid Spencer2341c222007-02-02 02:16:23 +00004688 NS = BinaryOperator::create(Instruction::LShr, AndCST,
4689 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004690 }
4691 InsertNewInstBefore(cast<Instruction>(NS), I);
4692
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004693 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00004694 Instruction *NewAnd = BinaryOperator::createAnd(
4695 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004696 InsertNewInstBefore(NewAnd, I);
4697
4698 I.setOperand(0, NewAnd);
4699 return &I;
4700 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004701 }
4702 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004703
Reid Spencer266e42b2006-12-23 06:05:41 +00004704 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004705 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004706 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004707 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4708
4709 // Check that the shift amount is in range. If not, don't perform
4710 // undefined shifts. When the shift is visited it will be
4711 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004712 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004713 break;
4714
Chris Lattner272d5ca2004-09-28 18:22:15 +00004715 // If we are comparing against bits always shifted out, the
4716 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004717 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004718 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004719 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004720 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004721 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004722 return ReplaceInstUsesWith(I, Cst);
4723 }
4724
4725 if (LHSI->hasOneUse()) {
4726 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004727 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004728 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc635f472006-12-31 05:48:39 +00004729 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004730
Chris Lattner272d5ca2004-09-28 18:22:15 +00004731 Instruction *AndI =
4732 BinaryOperator::createAnd(LHSI->getOperand(0),
4733 Mask, LHSI->getName()+".mask");
4734 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004735 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004736 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004737 }
4738 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004739 }
4740 break;
4741
Reid Spencer266e42b2006-12-23 06:05:41 +00004742 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004743 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004744 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004745 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004746 // Check that the shift amount is in range. If not, don't perform
4747 // undefined shifts. When the shift is visited it will be
4748 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004749 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004750 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004751 break;
4752
Chris Lattner1023b872004-09-27 16:18:50 +00004753 // If we are comparing against bits always shifted out, the
4754 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004755 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00004756 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00004757 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4758 ShAmt);
4759 else
4760 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4761 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004762
Chris Lattner1023b872004-09-27 16:18:50 +00004763 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004764 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004765 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004766 return ReplaceInstUsesWith(I, Cst);
4767 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004768
Chris Lattner1023b872004-09-27 16:18:50 +00004769 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004770 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004771
Chris Lattner1023b872004-09-27 16:18:50 +00004772 // Otherwise strength reduce the shift into an and.
4773 uint64_t Val = ~0ULL; // All ones.
4774 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc635f472006-12-31 05:48:39 +00004775 Val &= ~0ULL >> (64-TypeBits);
4776 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004777
Chris Lattner1023b872004-09-27 16:18:50 +00004778 Instruction *AndI =
4779 BinaryOperator::createAnd(LHSI->getOperand(0),
4780 Mask, LHSI->getName()+".mask");
4781 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004782 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004783 ConstantExpr::getShl(CI, ShAmt));
4784 }
Chris Lattner1023b872004-09-27 16:18:50 +00004785 }
4786 }
4787 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004788
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004789 case Instruction::SDiv:
4790 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004791 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004792 // Fold this div into the comparison, producing a range check.
4793 // Determine, based on the divide type, what the range is being
4794 // checked. If there is an overflow on the low or high side, remember
4795 // it, otherwise compute the range [low, hi) bounding the new value.
4796 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004797 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004798 // FIXME: If the operand types don't match the type of the divide
4799 // then don't attempt this transform. The code below doesn't have the
4800 // logic to deal with a signed divide and an unsigned compare (and
4801 // vice versa). This is because (x /s C1) <s C2 produces different
4802 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4803 // (x /u C1) <u C2. Simply casting the operands and result won't
4804 // work. :( The if statement below tests that condition and bails
4805 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004806 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4807 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004808 break;
4809
4810 // Initialize the variables that will indicate the nature of the
4811 // range check.
4812 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004813 ConstantInt *LoBound = 0, *HiBound = 0;
4814
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004815 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4816 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4817 // C2 (CI). By solving for X we can turn this into a range check
4818 // instead of computing a divide.
4819 ConstantInt *Prod =
4820 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004821
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004822 // Determine if the product overflows by seeing if the product is
4823 // not equal to the divide. Make sure we do the same kind of divide
4824 // as in the LHS instruction that we're folding.
4825 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00004826 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004827 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4828
Reid Spencer266e42b2006-12-23 06:05:41 +00004829 // Get the ICmp opcode
4830 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004831
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004832 if (DivRHS->isNullValue()) {
4833 // Don't hack on divide by zeros!
Reid Spencer266e42b2006-12-23 06:05:41 +00004834 } else if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004835 LoBound = Prod;
4836 LoOverflow = ProdOV;
4837 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004838 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004839 if (CI->isNullValue()) { // (X / pos) op 0
4840 // Can't overflow.
4841 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4842 HiBound = DivRHS;
4843 } else if (isPositive(CI)) { // (X / pos) op pos
4844 LoBound = Prod;
4845 LoOverflow = ProdOV;
4846 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4847 } else { // (X / pos) op neg
4848 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4849 LoOverflow = AddWithOverflow(LoBound, Prod,
4850 cast<ConstantInt>(DivRHSH));
4851 HiBound = Prod;
4852 HiOverflow = ProdOV;
4853 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004854 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004855 if (CI->isNullValue()) { // (X / neg) op 0
4856 LoBound = AddOne(DivRHS);
4857 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004858 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004859 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004860 } else if (isPositive(CI)) { // (X / neg) op pos
4861 HiOverflow = LoOverflow = ProdOV;
4862 if (!LoOverflow)
4863 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4864 HiBound = AddOne(Prod);
4865 } else { // (X / neg) op neg
4866 LoBound = Prod;
4867 LoOverflow = HiOverflow = ProdOV;
4868 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4869 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004870
Chris Lattnera92af962004-10-11 19:40:04 +00004871 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00004872 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004873 }
4874
4875 if (LoBound) {
4876 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004877 switch (predicate) {
4878 default: assert(0 && "Unhandled icmp opcode!");
4879 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004880 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004881 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004882 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004883 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4884 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004885 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004886 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4887 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004888 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004889 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4890 true, I);
4891 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004892 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004893 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004894 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004895 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4896 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004897 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004898 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4899 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004900 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004901 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4902 false, I);
4903 case ICmpInst::ICMP_ULT:
4904 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004905 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004906 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004907 return new ICmpInst(predicate, X, LoBound);
4908 case ICmpInst::ICMP_UGT:
4909 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004910 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004911 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004912 if (predicate == ICmpInst::ICMP_UGT)
4913 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4914 else
4915 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004916 }
4917 }
4918 }
4919 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004920 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004921
Reid Spencer266e42b2006-12-23 06:05:41 +00004922 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004923 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004924 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004925
Reid Spencere0fc4df2006-10-20 07:07:24 +00004926 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4927 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004928 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4929 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004930 case Instruction::SRem:
4931 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4932 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4933 BO->hasOneUse()) {
4934 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4935 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004936 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4937 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004938 return new ICmpInst(I.getPredicate(), NewRem,
4939 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004940 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004941 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004942 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004943 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004944 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4945 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004946 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004947 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4948 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004949 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004950 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4951 // efficiently invertible, or if the add has just this one use.
4952 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004953
Chris Lattnerc992add2003-08-13 05:33:12 +00004954 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004955 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00004956 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004957 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004958 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004959 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4960 BO->setName("");
4961 InsertNewInstBefore(Neg, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004962 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00004963 }
4964 }
4965 break;
4966 case Instruction::Xor:
4967 // For the xor case, we can xor two constants together, eliminating
4968 // the explicit xor.
4969 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00004970 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4971 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004972
4973 // FALLTHROUGH
4974 case Instruction::Sub:
4975 // Replace (([sub|xor] A, B) != 0) with (A != B)
4976 if (CI->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00004977 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4978 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00004979 break;
4980
4981 case Instruction::Or:
4982 // If bits are being or'd in that are not present in the constant we
4983 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004984 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004985 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004986 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00004987 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4988 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004989 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004990 break;
4991
4992 case Instruction::And:
4993 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004994 // If bits are being compared against that are and'd out, then the
4995 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004996 if (!ConstantExpr::getAnd(CI,
4997 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00004998 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4999 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00005000
Chris Lattner35167c32004-06-09 07:59:58 +00005001 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00005002 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00005003 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5004 ICmpInst::ICMP_NE, Op0,
5005 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00005006
Reid Spencer266e42b2006-12-23 06:05:41 +00005007 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00005008 if (isSignBit(BOC)) {
5009 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005010 Constant *Zero = Constant::getNullValue(X->getType());
5011 ICmpInst::Predicate pred = isICMP_NE ?
5012 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5013 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005014 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005015
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005016 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005017 if (CI->isNullValue() && isHighOnes(BOC)) {
5018 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005019 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005020 ICmpInst::Predicate pred = isICMP_NE ?
5021 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5022 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005023 }
5024
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005025 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005026 default: break;
5027 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005028 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5029 // Handle set{eq|ne} <intrinsic>, intcst.
5030 switch (II->getIntrinsicID()) {
5031 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005032 case Intrinsic::bswap_i16:
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::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005037 ByteSwap_16(CI->getZExtValue())));
5038 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005039 case Intrinsic::bswap_i32:
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::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005044 ByteSwap_32(CI->getZExtValue())));
5045 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005046 case Intrinsic::bswap_i64:
5047 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005048 WorkList.push_back(II); // Dead?
5049 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005050 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005051 ByteSwap_64(CI->getZExtValue())));
5052 return &I;
5053 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005054 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005055 } else { // Not a ICMP_EQ/ICMP_NE
5056 // If the LHS is a cast from an integral value of the same size, then
5057 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005058 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5059 Value *CastOp = Cast->getOperand(0);
5060 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005061 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner03c49532007-01-15 02:27:26 +00005062 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005063 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005064 // If this is an unsigned comparison, try to make the comparison use
5065 // smaller constant values.
5066 switch (I.getPredicate()) {
5067 default: break;
5068 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5069 ConstantInt *CUI = cast<ConstantInt>(CI);
5070 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5071 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5072 ConstantInt::get(SrcTy, -1));
5073 break;
5074 }
5075 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5076 ConstantInt *CUI = cast<ConstantInt>(CI);
5077 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5078 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5079 Constant::getNullValue(SrcTy));
5080 break;
5081 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005082 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005083
Chris Lattner2b55ea32004-02-23 07:16:20 +00005084 }
5085 }
Chris Lattnere967b342003-06-04 05:10:11 +00005086 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005087 }
5088
Reid Spencer266e42b2006-12-23 06:05:41 +00005089 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005090 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5091 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5092 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005093 case Instruction::GetElementPtr:
5094 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005095 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005096 bool isAllZeros = true;
5097 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5098 if (!isa<Constant>(LHSI->getOperand(i)) ||
5099 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5100 isAllZeros = false;
5101 break;
5102 }
5103 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005104 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005105 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5106 }
5107 break;
5108
Chris Lattner77c32c32005-04-23 15:31:55 +00005109 case Instruction::PHI:
5110 if (Instruction *NV = FoldOpIntoPhi(I))
5111 return NV;
5112 break;
5113 case Instruction::Select:
5114 // If either operand of the select is a constant, we can fold the
5115 // comparison into the select arms, which will cause one to be
5116 // constant folded and the select turned into a bitwise or.
5117 Value *Op1 = 0, *Op2 = 0;
5118 if (LHSI->hasOneUse()) {
5119 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5120 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005121 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5122 // Insert a new ICmp of the other select operand.
5123 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5124 LHSI->getOperand(2), RHSC,
5125 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005126 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5127 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005128 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5129 // Insert a new ICmp of the other select operand.
5130 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5131 LHSI->getOperand(1), RHSC,
5132 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005133 }
5134 }
Jeff Cohen82639852005-04-23 21:38:35 +00005135
Chris Lattner77c32c32005-04-23 15:31:55 +00005136 if (Op1)
5137 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5138 break;
5139 }
5140 }
5141
Reid Spencer266e42b2006-12-23 06:05:41 +00005142 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005143 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005144 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005145 return NI;
5146 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005147 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5148 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005149 return NI;
5150
Reid Spencer266e42b2006-12-23 06:05:41 +00005151 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005152 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5153 // now.
5154 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5155 if (isa<PointerType>(Op0->getType()) &&
5156 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005157 // We keep moving the cast from the left operand over to the right
5158 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005159 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005160
Chris Lattner64d87b02007-01-06 01:45:59 +00005161 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5162 // so eliminate it as well.
5163 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5164 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005165
Chris Lattner16930792003-11-03 04:25:02 +00005166 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005167 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005168 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005169 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005170 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005171 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005172 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005173 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005174 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005175 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005176 }
5177
5178 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005179 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005180 // This comes up when you have code like
5181 // int X = A < B;
5182 // if (X) ...
5183 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005184 // with a constant or another cast from the same type.
5185 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005186 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005187 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005188 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005189
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005190 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005191 Value *A, *B, *C, *D;
5192 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5193 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5194 Value *OtherVal = A == Op1 ? B : A;
5195 return new ICmpInst(I.getPredicate(), OtherVal,
5196 Constant::getNullValue(A->getType()));
5197 }
5198
5199 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5200 // A^c1 == C^c2 --> A == C^(c1^c2)
5201 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5202 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5203 if (Op1->hasOneUse()) {
5204 Constant *NC = ConstantExpr::getXor(C1, C2);
5205 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5206 return new ICmpInst(I.getPredicate(), A,
5207 InsertNewInstBefore(Xor, I));
5208 }
5209
5210 // A^B == A^D -> B == D
5211 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5212 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5213 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5214 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5215 }
5216 }
5217
5218 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5219 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005220 // A == (A^B) -> B == 0
5221 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005222 return new ICmpInst(I.getPredicate(), OtherVal,
5223 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005224 }
5225 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005226 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005227 return new ICmpInst(I.getPredicate(), B,
5228 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005229 }
5230 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005231 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005232 return new ICmpInst(I.getPredicate(), B,
5233 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005234 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005235
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005236 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5237 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5238 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5239 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5240 Value *X = 0, *Y = 0, *Z = 0;
5241
5242 if (A == C) {
5243 X = B; Y = D; Z = A;
5244 } else if (A == D) {
5245 X = B; Y = C; Z = A;
5246 } else if (B == C) {
5247 X = A; Y = D; Z = B;
5248 } else if (B == D) {
5249 X = A; Y = C; Z = B;
5250 }
5251
5252 if (X) { // Build (X^Y) & Z
5253 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5254 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5255 I.setOperand(0, Op1);
5256 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5257 return &I;
5258 }
5259 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005260 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005261 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005262}
5263
Reid Spencer266e42b2006-12-23 06:05:41 +00005264// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005265// We only handle extending casts so far.
5266//
Reid Spencer266e42b2006-12-23 06:05:41 +00005267Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5268 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005269 Value *LHSCIOp = LHSCI->getOperand(0);
5270 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005271 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005272 Value *RHSCIOp;
5273
Reid Spencer266e42b2006-12-23 06:05:41 +00005274 // We only handle extension cast instructions, so far. Enforce this.
5275 if (LHSCI->getOpcode() != Instruction::ZExt &&
5276 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005277 return 0;
5278
Reid Spencer266e42b2006-12-23 06:05:41 +00005279 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5280 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005281
Reid Spencer266e42b2006-12-23 06:05:41 +00005282 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005283 // Not an extension from the same type?
5284 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005285 if (RHSCIOp->getType() != LHSCIOp->getType())
5286 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005287
5288 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5289 // and the other is a zext), then we can't handle this.
5290 if (CI->getOpcode() != LHSCI->getOpcode())
5291 return 0;
5292
5293 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5294 // then we can't handle this.
5295 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5296 return 0;
5297
5298 // Okay, just insert a compare of the reduced operands now!
5299 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005300 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005301
Reid Spencer266e42b2006-12-23 06:05:41 +00005302 // If we aren't dealing with a constant on the RHS, exit early
5303 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5304 if (!CI)
5305 return 0;
5306
5307 // Compute the constant that would happen if we truncated to SrcTy then
5308 // reextended to DestTy.
5309 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5310 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5311
5312 // If the re-extended constant didn't change...
5313 if (Res2 == CI) {
5314 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5315 // For example, we might have:
5316 // %A = sext short %X to uint
5317 // %B = icmp ugt uint %A, 1330
5318 // It is incorrect to transform this into
5319 // %B = icmp ugt short %X, 1330
5320 // because %A may have negative value.
5321 //
5322 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5323 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005324 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005325 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5326 else
5327 return 0;
5328 }
5329
5330 // The re-extended constant changed so the constant cannot be represented
5331 // in the shorter type. Consequently, we cannot emit a simple comparison.
5332
5333 // First, handle some easy cases. We know the result cannot be equal at this
5334 // point so handle the ICI.isEquality() cases
5335 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005336 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005337 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005338 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005339
5340 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5341 // should have been folded away previously and not enter in here.
5342 Value *Result;
5343 if (isSignedCmp) {
5344 // We're performing a signed comparison.
5345 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005346 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005347 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005348 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005349 } else {
5350 // We're performing an unsigned comparison.
5351 if (isSignedExt) {
5352 // We're performing an unsigned comp with a sign extended value.
5353 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005354 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005355 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5356 NegOne, ICI.getName()), ICI);
5357 } else {
5358 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005359 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005360 }
5361 }
5362
5363 // Finally, return the value computed.
5364 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5365 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5366 return ReplaceInstUsesWith(ICI, Result);
5367 } else {
5368 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5369 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5370 "ICmp should be folded!");
5371 if (Constant *CI = dyn_cast<Constant>(Result))
5372 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5373 else
5374 return BinaryOperator::createNot(Result);
5375 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005376}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005377
Reid Spencer2341c222007-02-02 02:16:23 +00005378Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5379 return commonShiftTransforms(I);
5380}
5381
5382Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5383 return commonShiftTransforms(I);
5384}
5385
5386Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5387 return commonShiftTransforms(I);
5388}
5389
5390Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5391 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00005392 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005393
5394 // shl X, 0 == X and shr X, 0 == X
5395 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00005396 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005397 Op0 == Constant::getNullValue(Op0->getType()))
5398 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005399
Reid Spencer266e42b2006-12-23 06:05:41 +00005400 if (isa<UndefValue>(Op0)) {
5401 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005402 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005403 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005404 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5405 }
5406 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005407 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5408 return ReplaceInstUsesWith(I, Op0);
5409 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005410 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005411 }
5412
Chris Lattnerd4dee402006-11-10 23:38:52 +00005413 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5414 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005415 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005416 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005417 return ReplaceInstUsesWith(I, CSI);
5418
Chris Lattner183b3362004-04-09 19:05:30 +00005419 // Try to fold constant and into select arguments.
5420 if (isa<Constant>(Op0))
5421 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005422 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005423 return R;
5424
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005425 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005426 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005427 if (MaskedValueIsZero(Op0,
5428 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencer2341c222007-02-02 02:16:23 +00005429 return BinaryOperator::create(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005430 }
5431 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005432
Reid Spencere0fc4df2006-10-20 07:07:24 +00005433 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005434 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5435 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005436 return 0;
5437}
5438
Reid Spencere0fc4df2006-10-20 07:07:24 +00005439Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00005440 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005441 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5442 bool isSignedShift = I.getOpcode() == Instruction::AShr;
Chris Lattnerb3309392006-01-06 07:22:22 +00005443 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005444
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005445 // See if we can simplify any instructions used by the instruction whose sole
5446 // purpose is to compute bits we don't care about.
5447 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00005448 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005449 KnownZero, KnownOne))
5450 return &I;
5451
Chris Lattner14553932006-01-06 07:12:35 +00005452 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5453 // of a signed value.
5454 //
5455 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005456 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005457 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00005458 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5459 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005460 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005461 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005462 }
Chris Lattner14553932006-01-06 07:12:35 +00005463 }
5464
5465 // ((X*C1) << C2) == (X * (C1 << C2))
5466 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5467 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5468 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5469 return BinaryOperator::createMul(BO->getOperand(0),
5470 ConstantExpr::getShl(BOOp, Op1));
5471
5472 // Try to fold constant and into select arguments.
5473 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5474 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5475 return R;
5476 if (isa<PHINode>(Op0))
5477 if (Instruction *NV = FoldOpIntoPhi(I))
5478 return NV;
5479
5480 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005481 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5482 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5483 Value *V1, *V2;
5484 ConstantInt *CC;
5485 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005486 default: break;
5487 case Instruction::Add:
5488 case Instruction::And:
5489 case Instruction::Or:
5490 case Instruction::Xor:
5491 // These operators commute.
5492 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005493 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5494 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005495 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer2341c222007-02-02 02:16:23 +00005496 Instruction *YS = BinaryOperator::create(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005497 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005498 Op0BO->getName());
5499 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005500 Instruction *X =
5501 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5502 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005503 InsertNewInstBefore(X, I); // (X + (Y << C))
5504 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005505 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005506 return BinaryOperator::createAnd(X, C2);
5507 }
Chris Lattner14553932006-01-06 07:12:35 +00005508
Chris Lattner797dee72005-09-18 06:30:59 +00005509 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5510 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Reid Spencer2341c222007-02-02 02:16:23 +00005511 match(Op0BO->getOperand(1), m_And(m_Shr(m_Value(V1), m_Value(V2)),
5512 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005513 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Reid Spencer2341c222007-02-02 02:16:23 +00005514 Instruction *YS = BinaryOperator::create(Instruction::Shl,
5515 Op0BO->getOperand(0), Op1,
5516 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005517 InsertNewInstBefore(YS, I); // (Y << C)
5518 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005519 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005520 V1->getName()+".mask");
5521 InsertNewInstBefore(XM, I); // X & (CC << C)
5522
5523 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5524 }
Chris Lattner14553932006-01-06 07:12:35 +00005525
Chris Lattner797dee72005-09-18 06:30:59 +00005526 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005527 case Instruction::Sub:
5528 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005529 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5530 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005531 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer2341c222007-02-02 02:16:23 +00005532 Instruction *YS = BinaryOperator::create(Instruction::Shl,
5533 Op0BO->getOperand(1), Op1,
5534 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005535 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005536 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005537 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005538 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005539 InsertNewInstBefore(X, I); // (X + (Y << C))
5540 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005541 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005542 return BinaryOperator::createAnd(X, C2);
5543 }
Chris Lattner14553932006-01-06 07:12:35 +00005544
Chris Lattner1df0e982006-05-31 21:14:00 +00005545 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005546 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5547 match(Op0BO->getOperand(0),
5548 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005549 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005550 cast<BinaryOperator>(Op0BO->getOperand(0))
5551 ->getOperand(0)->hasOneUse()) {
Reid Spencer2341c222007-02-02 02:16:23 +00005552 Instruction *YS = BinaryOperator::create(Instruction::Shl,
5553 Op0BO->getOperand(1), Op1,
5554 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005555 InsertNewInstBefore(YS, I); // (Y << C)
5556 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005557 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005558 V1->getName()+".mask");
5559 InsertNewInstBefore(XM, I); // X & (CC << C)
5560
Chris Lattner1df0e982006-05-31 21:14:00 +00005561 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005562 }
Chris Lattner14553932006-01-06 07:12:35 +00005563
Chris Lattner27cb9db2005-09-18 05:12:10 +00005564 break;
Chris Lattner14553932006-01-06 07:12:35 +00005565 }
5566
5567
5568 // If the operand is an bitwise operator with a constant RHS, and the
5569 // shift is the only use, we can pull it out of the shift.
5570 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5571 bool isValid = true; // Valid only for And, Or, Xor
5572 bool highBitSet = false; // Transform if high bit of constant set?
5573
5574 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005575 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005576 case Instruction::Add:
5577 isValid = isLeftShift;
5578 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005579 case Instruction::Or:
5580 case Instruction::Xor:
5581 highBitSet = false;
5582 break;
5583 case Instruction::And:
5584 highBitSet = true;
5585 break;
Chris Lattner14553932006-01-06 07:12:35 +00005586 }
5587
5588 // If this is a signed shift right, and the high bit is modified
5589 // by the logical operation, do not perform the transformation.
5590 // The highBitSet boolean indicates the value of the high bit of
5591 // the constant which would cause it to be modified for this
5592 // operation.
5593 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005594 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005595 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005596 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5597 }
5598
5599 if (isValid) {
5600 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5601
5602 Instruction *NewShift =
Reid Spencer2341c222007-02-02 02:16:23 +00005603 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1,
5604 Op0BO->getName());
Chris Lattner14553932006-01-06 07:12:35 +00005605 Op0BO->setName("");
5606 InsertNewInstBefore(NewShift, I);
5607
5608 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5609 NewRHS);
5610 }
5611 }
5612 }
5613 }
5614
Chris Lattnereb372a02006-01-06 07:52:12 +00005615 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00005616 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5617 if (ShiftOp && !ShiftOp->isShift())
5618 ShiftOp = 0;
5619 if (!ShiftOp)
5620 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0))
5621 // If this is a noop-integer cast of a shift instruction, use the shift.
5622 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(CI->getOperand(0)))
5623 if (SI->isShift())
5624 ShiftOp = SI;
Chris Lattnereb372a02006-01-06 07:52:12 +00005625
Reid Spencere0fc4df2006-10-20 07:07:24 +00005626 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005627 // Find the operands and properties of the input shift. Note that the
5628 // signedness of the input shift may differ from the current shift if there
5629 // is a noop cast between the two.
Reid Spencer266e42b2006-12-23 06:05:41 +00005630 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5631 bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005632 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005633
Reid Spencere0fc4df2006-10-20 07:07:24 +00005634 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005635
Reid Spencere0fc4df2006-10-20 07:07:24 +00005636 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5637 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005638
5639 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5640 if (isLeftShift == isShiftOfLeftShift) {
5641 // Do not fold these shifts if the first one is signed and the second one
5642 // is unsigned and this is a right shift. Further, don't do any folding
5643 // on them.
5644 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5645 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005646
Chris Lattnereb372a02006-01-06 07:52:12 +00005647 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5648 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5649 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005650
Chris Lattnereb372a02006-01-06 07:52:12 +00005651 Value *Op = ShiftOp->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00005652 BinaryOperator *ShiftResult =
5653 BinaryOperator::create(I.getOpcode(), Op,
5654 ConstantInt::get(Op->getType(), Amt));
Reid Spencerfdff9382006-11-08 06:47:33 +00005655 if (I.getType() == ShiftResult->getType())
5656 return ShiftResult;
5657 InsertNewInstBefore(ShiftResult, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005658 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005659 }
5660
5661 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5662 // signed types, we can only support the (A >> c1) << c2 configuration,
5663 // because it can not turn an arbitrary bit of A into a sign bit.
5664 if (isUnsignedShift || isLeftShift) {
5665 // Calculate bitmask for what gets shifted off the edge.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005666 Constant *C = ConstantInt::getAllOnesValue(I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005667 if (isLeftShift)
5668 C = ConstantExpr::getShl(C, ShiftAmt1C);
5669 else
Reid Spencerfdff9382006-11-08 06:47:33 +00005670 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005671
5672 Value *Op = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005673
5674 Instruction *Mask =
5675 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5676 InsertNewInstBefore(Mask, I);
5677
5678 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005679 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005680 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005681 } else if (ShiftAmt1 < ShiftAmt2) {
Reid Spencer2341c222007-02-02 02:16:23 +00005682 return BinaryOperator::create(I.getOpcode(), Mask,
5683 ConstantInt::get(Mask->getType(),
5684 ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005685 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5686 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencer2341c222007-02-02 02:16:23 +00005687 return BinaryOperator::create(Instruction::LShr, Mask,
5688 ConstantInt::get(Mask->getType(),
5689 ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005690 } else {
Reid Spencer2341c222007-02-02 02:16:23 +00005691 return BinaryOperator::create(ShiftOp->getOpcode(), Mask,
5692 ConstantInt::get(Mask->getType(),
5693 ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005694 }
5695 } else {
5696 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005697 Instruction *Shift =
Reid Spencer2341c222007-02-02 02:16:23 +00005698 BinaryOperator::create(ShiftOp->getOpcode(), Mask,
5699 ConstantInt::get(Mask->getType(),
5700 ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005701 InsertNewInstBefore(Shift, I);
5702
Zhou Sheng75b871f2007-01-11 12:24:14 +00005703 C = ConstantInt::getAllOnesValue(Shift->getType());
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005704 C = ConstantExpr::getShl(C, Op1);
Reid Spencer2a499b02006-12-13 17:19:09 +00005705 return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
Chris Lattnereb372a02006-01-06 07:52:12 +00005706 }
5707 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005708 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005709 // this case, C1 == C2 and C1 is 8, 16, or 32.
5710 if (ShiftAmt1 == ShiftAmt2) {
5711 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005712 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Reid Spencerc635f472006-12-31 05:48:39 +00005713 case 8 : SExtType = Type::Int8Ty; break;
5714 case 16: SExtType = Type::Int16Ty; break;
5715 case 32: SExtType = Type::Int32Ty; break;
Chris Lattnereb372a02006-01-06 07:52:12 +00005716 }
5717
5718 if (SExtType) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005719 Instruction *NewTrunc =
5720 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
Chris Lattnereb372a02006-01-06 07:52:12 +00005721 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005722 return new SExtInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005723 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005724 }
Chris Lattner86102b82005-01-01 16:22:27 +00005725 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005726 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005727 return 0;
5728}
5729
Chris Lattner48a44f72002-05-02 17:06:02 +00005730
Chris Lattner8f663e82005-10-29 04:36:15 +00005731/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5732/// expression. If so, decompose it, returning some value X, such that Val is
5733/// X*Scale+Offset.
5734///
5735static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5736 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00005737 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005738 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00005739 Offset = CI->getZExtValue();
5740 Scale = 1;
5741 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00005742 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5743 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005744 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00005745 if (I->getOpcode() == Instruction::Shl) {
5746 // This is a value scaled by '1 << the shift amt'.
5747 Scale = 1U << CUI->getZExtValue();
5748 Offset = 0;
5749 return I->getOperand(0);
5750 } else if (I->getOpcode() == Instruction::Mul) {
5751 // This value is scaled by 'CUI'.
5752 Scale = CUI->getZExtValue();
5753 Offset = 0;
5754 return I->getOperand(0);
5755 } else if (I->getOpcode() == Instruction::Add) {
5756 // We have X+C. Check to see if we really have (X*C2)+C1,
5757 // where C1 is divisible by C2.
5758 unsigned SubScale;
5759 Value *SubVal =
5760 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5761 Offset += CUI->getZExtValue();
5762 if (SubScale > 1 && (Offset % SubScale == 0)) {
5763 Scale = SubScale;
5764 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00005765 }
5766 }
5767 }
5768 }
5769 }
5770
5771 // Otherwise, we can't look past this.
5772 Scale = 1;
5773 Offset = 0;
5774 return Val;
5775}
5776
5777
Chris Lattner216be912005-10-24 06:03:58 +00005778/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5779/// try to eliminate the cast by moving the type information into the alloc.
5780Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5781 AllocationInst &AI) {
5782 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005783 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005784
Chris Lattnerac87beb2005-10-24 06:22:12 +00005785 // Remove any uses of AI that are dead.
5786 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5787 std::vector<Instruction*> DeadUsers;
5788 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5789 Instruction *User = cast<Instruction>(*UI++);
5790 if (isInstructionTriviallyDead(User)) {
5791 while (UI != E && *UI == User)
5792 ++UI; // If this instruction uses AI more than once, don't break UI.
5793
5794 // Add operands to the worklist.
5795 AddUsesToWorkList(*User);
5796 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005797 DOUT << "IC: DCE: " << *User;
Chris Lattnerac87beb2005-10-24 06:22:12 +00005798
5799 User->eraseFromParent();
5800 removeFromWorkList(User);
5801 }
5802 }
5803
Chris Lattner216be912005-10-24 06:03:58 +00005804 // Get the type really allocated and the type casted to.
5805 const Type *AllocElTy = AI.getAllocatedType();
5806 const Type *CastElTy = PTy->getElementType();
5807 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005808
Chris Lattner50ee0e42007-01-20 22:35:55 +00005809 unsigned AllocElTyAlign = TD->getTypeAlignmentABI(AllocElTy);
5810 unsigned CastElTyAlign = TD->getTypeAlignmentABI(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005811 if (CastElTyAlign < AllocElTyAlign) return 0;
5812
Chris Lattner46705b22005-10-24 06:35:18 +00005813 // If the allocation has multiple uses, only promote it if we are strictly
5814 // increasing the alignment of the resultant allocation. If we keep it the
5815 // same, we open the door to infinite loops of various kinds.
5816 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5817
Chris Lattner216be912005-10-24 06:03:58 +00005818 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5819 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005820 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005821
Chris Lattner8270c332005-10-29 03:19:53 +00005822 // See if we can satisfy the modulus by pulling a scale out of the array
5823 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005824 unsigned ArraySizeScale, ArrayOffset;
5825 Value *NumElements = // See if the array size is a decomposable linear expr.
5826 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5827
Chris Lattner8270c332005-10-29 03:19:53 +00005828 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5829 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005830 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5831 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005832
Chris Lattner8270c332005-10-29 03:19:53 +00005833 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5834 Value *Amt = 0;
5835 if (Scale == 1) {
5836 Amt = NumElements;
5837 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005838 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00005839 Amt = ConstantInt::get(Type::Int32Ty, Scale);
5840 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00005841 Amt = ConstantExpr::getMul(
5842 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5843 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005844 else if (Scale != 1) {
5845 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5846 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005847 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005848 }
5849
Chris Lattner8f663e82005-10-29 04:36:15 +00005850 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00005851 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005852 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5853 Amt = InsertNewInstBefore(Tmp, AI);
5854 }
5855
Chris Lattner216be912005-10-24 06:03:58 +00005856 std::string Name = AI.getName(); AI.setName("");
5857 AllocationInst *New;
5858 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005859 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005860 else
Nate Begeman848622f2005-11-05 09:21:28 +00005861 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005862 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005863
5864 // If the allocation has multiple uses, insert a cast and change all things
5865 // that used it to use the new cast. This will also hack on CI, but it will
5866 // die soon.
5867 if (!AI.hasOneUse()) {
5868 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005869 // New is the allocation instruction, pointer typed. AI is the original
5870 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5871 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00005872 InsertNewInstBefore(NewCast, AI);
5873 AI.replaceAllUsesWith(NewCast);
5874 }
Chris Lattner216be912005-10-24 06:03:58 +00005875 return ReplaceInstUsesWith(CI, New);
5876}
5877
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005878/// CanEvaluateInDifferentType - Return true if we can take the specified value
5879/// and return it without inserting any new casts. This is used by code that
5880/// tries to decide whether promoting or shrinking integer operations to wider
5881/// or smaller types will allow us to eliminate a truncate or extend.
5882static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5883 int &NumCastsRemoved) {
5884 if (isa<Constant>(V)) return true;
5885
5886 Instruction *I = dyn_cast<Instruction>(V);
5887 if (!I || !I->hasOneUse()) return false;
5888
5889 switch (I->getOpcode()) {
5890 case Instruction::And:
5891 case Instruction::Or:
5892 case Instruction::Xor:
5893 // These operators can all arbitrarily be extended or truncated.
5894 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5895 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattner960acb02006-11-29 07:18:39 +00005896 case Instruction::AShr:
5897 case Instruction::LShr:
5898 case Instruction::Shl:
5899 // If this is just a bitcast changing the sign of the operation, we can
5900 // convert if the operand can be converted.
5901 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5902 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5903 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005904 case Instruction::Trunc:
5905 case Instruction::ZExt:
5906 case Instruction::SExt:
5907 case Instruction::BitCast:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005908 // If this is a cast from the destination type, we can trivially eliminate
5909 // it, and this will remove a cast overall.
5910 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005911 // If the first operand is itself a cast, and is eliminable, do not count
5912 // this as an eliminable cast. We would prefer to eliminate those two
5913 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005914 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005915 return true;
5916
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005917 ++NumCastsRemoved;
5918 return true;
5919 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005920 break;
5921 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005922 // TODO: Can handle more cases here.
5923 break;
5924 }
5925
5926 return false;
5927}
5928
5929/// EvaluateInDifferentType - Given an expression that
5930/// CanEvaluateInDifferentType returns true for, actually insert the code to
5931/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00005932Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
5933 bool isSigned ) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005934 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00005935 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005936
5937 // Otherwise, it must be an instruction.
5938 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005939 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005940 switch (I->getOpcode()) {
5941 case Instruction::And:
5942 case Instruction::Or:
5943 case Instruction::Xor: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005944 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5945 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005946 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5947 LHS, RHS, I->getName());
5948 break;
5949 }
Chris Lattner960acb02006-11-29 07:18:39 +00005950 case Instruction::AShr:
5951 case Instruction::LShr:
5952 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005953 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Reid Spencer2341c222007-02-02 02:16:23 +00005954 Res = BinaryOperator::create(Instruction::BinaryOps(I->getOpcode()), LHS,
5955 I->getOperand(1), I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00005956 break;
5957 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005958 case Instruction::Trunc:
5959 case Instruction::ZExt:
5960 case Instruction::SExt:
5961 case Instruction::BitCast:
5962 // If the source type of the cast is the type we're trying for then we can
5963 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005964 if (I->getOperand(0)->getType() == Ty)
5965 return I->getOperand(0);
5966
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005967 // Some other kind of cast, which shouldn't happen, so just ..
5968 // FALL THROUGH
5969 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005970 // TODO: Can handle more cases here.
5971 assert(0 && "Unreachable!");
5972 break;
5973 }
5974
5975 return InsertNewInstBefore(Res, *I);
5976}
5977
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005978/// @brief Implement the transforms common to all CastInst visitors.
5979Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005980 Value *Src = CI.getOperand(0);
5981
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005982 // Casting undef to anything results in undef so might as just replace it and
5983 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00005984 if (isa<UndefValue>(Src)) // cast undef -> undef
5985 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5986
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005987 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5988 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00005989 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005990 if (Instruction::CastOps opc =
5991 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5992 // The first cast (CSrc) is eliminable so we need to fix up or replace
5993 // the second cast (CI). CSrc will then have a good chance of being dead.
5994 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00005995 }
5996 }
Chris Lattner03841652004-05-25 04:29:21 +00005997
Chris Lattnerd0d51602003-06-21 23:12:02 +00005998 // If casting the result of a getelementptr instruction with no offset, turn
5999 // this into a cast of the original pointer!
6000 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006001 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006002 bool AllZeroOperands = true;
6003 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6004 if (!isa<Constant>(GEP->getOperand(i)) ||
6005 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6006 AllZeroOperands = false;
6007 break;
6008 }
6009 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006010 // Changing the cast operand is usually not a good idea but it is safe
6011 // here because the pointer operand is being replaced with another
6012 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006013 CI.setOperand(0, GEP->getOperand(0));
6014 return &CI;
6015 }
6016 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006017
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006018 // If we are casting a malloc or alloca to a pointer to a type of the same
6019 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006020 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006021 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6022 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006023
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006024 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006025 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6026 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6027 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006028
6029 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006030 if (isa<PHINode>(Src))
6031 if (Instruction *NV = FoldOpIntoPhi(CI))
6032 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006033
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006034 return 0;
6035}
6036
6037/// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
6038/// integers. This function implements the common transforms for all those
6039/// cases.
6040/// @brief Implement the transforms common to CastInst with integer operands
6041Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6042 if (Instruction *Result = commonCastTransforms(CI))
6043 return Result;
6044
6045 Value *Src = CI.getOperand(0);
6046 const Type *SrcTy = Src->getType();
6047 const Type *DestTy = CI.getType();
6048 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6049 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6050
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006051 // See if we can simplify any instructions used by the LHS whose sole
6052 // purpose is to compute bits we don't care about.
6053 uint64_t KnownZero = 0, KnownOne = 0;
Reid Spencera94d3942007-01-19 21:13:56 +00006054 if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006055 KnownZero, KnownOne))
6056 return &CI;
6057
6058 // If the source isn't an instruction or has more than one use then we
6059 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006060 Instruction *SrcI = dyn_cast<Instruction>(Src);
6061 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006062 return 0;
6063
6064 // Attempt to propagate the cast into the instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006065 int NumCastsRemoved = 0;
6066 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6067 // If this cast is a truncate, evaluting in a different type always
6068 // eliminates the cast, so it is always a win. If this is a noop-cast
6069 // this just removes a noop cast which isn't pointful, but simplifies
6070 // the code. If this is a zero-extension, we need to do an AND to
6071 // maintain the clear top-part of the computation, so we require that
6072 // the input have eliminated at least one cast. If this is a sign
6073 // extension, we insert two new casts (to do the extension) so we
6074 // require that two casts have been eliminated.
6075 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6076 if (!DoXForm) {
6077 switch (CI.getOpcode()) {
6078 case Instruction::Trunc:
6079 DoXForm = true;
6080 break;
6081 case Instruction::ZExt:
6082 DoXForm = NumCastsRemoved >= 1;
6083 break;
6084 case Instruction::SExt:
6085 DoXForm = NumCastsRemoved >= 2;
6086 break;
6087 case Instruction::BitCast:
6088 DoXForm = false;
6089 break;
6090 default:
6091 // All the others use floating point so we shouldn't actually
6092 // get here because of the check above.
6093 assert(!"Unknown cast type .. unreachable");
6094 break;
6095 }
6096 }
6097
6098 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006099 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6100 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006101 assert(Res->getType() == DestTy);
6102 switch (CI.getOpcode()) {
6103 default: assert(0 && "Unknown cast type!");
6104 case Instruction::Trunc:
6105 case Instruction::BitCast:
6106 // Just replace this cast with the result.
6107 return ReplaceInstUsesWith(CI, Res);
6108 case Instruction::ZExt: {
6109 // We need to emit an AND to clear the high bits.
6110 assert(SrcBitSize < DestBitSize && "Not a zext?");
6111 Constant *C =
Reid Spencerc635f472006-12-31 05:48:39 +00006112 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006113 if (DestBitSize < 64)
6114 C = ConstantExpr::getTrunc(C, DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006115 return BinaryOperator::createAnd(Res, C);
6116 }
6117 case Instruction::SExt:
6118 // We need to emit a cast to truncate, then a cast to sext.
6119 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006120 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6121 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006122 }
6123 }
6124 }
6125
6126 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6127 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6128
6129 switch (SrcI->getOpcode()) {
6130 case Instruction::Add:
6131 case Instruction::Mul:
6132 case Instruction::And:
6133 case Instruction::Or:
6134 case Instruction::Xor:
6135 // If we are discarding information, or just changing the sign,
6136 // rewrite.
6137 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6138 // Don't insert two casts if they cannot be eliminated. We allow
6139 // two casts to be inserted if the sizes are the same. This could
6140 // only be converting signedness, which is a noop.
6141 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006142 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6143 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006144 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006145 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6146 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6147 return BinaryOperator::create(
6148 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006149 }
6150 }
6151
6152 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6153 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6154 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006155 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006156 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006157 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006158 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6159 }
6160 break;
6161 case Instruction::SDiv:
6162 case Instruction::UDiv:
6163 case Instruction::SRem:
6164 case Instruction::URem:
6165 // If we are just changing the sign, rewrite.
6166 if (DestBitSize == SrcBitSize) {
6167 // Don't insert two casts if they cannot be eliminated. We allow
6168 // two casts to be inserted if the sizes are the same. This could
6169 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006170 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6171 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006172 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6173 Op0, DestTy, SrcI);
6174 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6175 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006176 return BinaryOperator::create(
6177 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6178 }
6179 }
6180 break;
6181
6182 case Instruction::Shl:
6183 // Allow changing the sign of the source operand. Do not allow
6184 // changing the size of the shift, UNLESS the shift amount is a
6185 // constant. We must not change variable sized shifts to a smaller
6186 // size, because it is undefined to shift more bits out than exist
6187 // in the value.
6188 if (DestBitSize == SrcBitSize ||
6189 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006190 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6191 Instruction::BitCast : Instruction::Trunc);
6192 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00006193 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6194 return BinaryOperator::create(Instruction::Shl, Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006195 }
6196 break;
6197 case Instruction::AShr:
6198 // If this is a signed shr, and if all bits shifted in are about to be
6199 // truncated off, turn it into an unsigned shr to allow greater
6200 // simplifications.
6201 if (DestBitSize < SrcBitSize &&
6202 isa<ConstantInt>(Op1)) {
6203 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6204 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6205 // Insert the new logical shift right.
Reid Spencer2341c222007-02-02 02:16:23 +00006206 return BinaryOperator::create(Instruction::LShr, Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006207 }
6208 }
6209 break;
6210
Reid Spencer266e42b2006-12-23 06:05:41 +00006211 case Instruction::ICmp:
6212 // If we are just checking for a icmp eq of a single bit and casting it
6213 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006214 // cast to integer to avoid the comparison.
6215 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6216 uint64_t Op1CV = Op1C->getZExtValue();
6217 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6218 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6219 // cast (X == 1) to int --> X iff X has only the low bit set.
6220 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6221 // cast (X != 0) to int --> X iff X has only the low bit set.
6222 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6223 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6224 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6225 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6226 // If Op1C some other power of two, convert:
6227 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00006228 uint64_t TypeMask = Op1C->getType()->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006229 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006230
6231 // This only works for EQ and NE
6232 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6233 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6234 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006235
6236 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006237 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006238 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6239 // (X&4) == 2 --> false
6240 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00006241 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006242 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006243 return ReplaceInstUsesWith(CI, Res);
6244 }
6245
6246 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6247 Value *In = Op0;
6248 if (ShiftAmt) {
6249 // Perform a logical shr by shiftamt.
6250 // Insert the shift to put the result in the low bit.
6251 In = InsertNewInstBefore(
Reid Spencer2341c222007-02-02 02:16:23 +00006252 BinaryOperator::create(Instruction::LShr, In,
6253 ConstantInt::get(In->getType(), ShiftAmt),
6254 In->getName()+".lobit"), CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006255 }
6256
Reid Spencer266e42b2006-12-23 06:05:41 +00006257 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006258 Constant *One = ConstantInt::get(In->getType(), 1);
6259 In = BinaryOperator::createXor(In, One, "tmp");
6260 InsertNewInstBefore(cast<Instruction>(In), CI);
6261 }
6262
6263 if (CI.getType() == In->getType())
6264 return ReplaceInstUsesWith(CI, In);
6265 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006266 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006267 }
6268 }
6269 }
6270 break;
6271 }
6272 return 0;
6273}
6274
6275Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006276 if (Instruction *Result = commonIntCastTransforms(CI))
6277 return Result;
6278
6279 Value *Src = CI.getOperand(0);
6280 const Type *Ty = CI.getType();
6281 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6282
6283 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6284 switch (SrcI->getOpcode()) {
6285 default: break;
6286 case Instruction::LShr:
6287 // We can shrink lshr to something smaller if we know the bits shifted in
6288 // are already zeros.
6289 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6290 unsigned ShAmt = ShAmtV->getZExtValue();
6291
6292 // Get a mask for the bits shifting in.
6293 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006294 Value* SrcIOp0 = SrcI->getOperand(0);
6295 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006296 if (ShAmt >= DestBitWidth) // All zeros.
6297 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6298
6299 // Okay, we can shrink this. Truncate the input, then return a new
6300 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00006301 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6302 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6303 Ty, CI);
6304 return BinaryOperator::create(Instruction::LShr, V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00006305 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006306 } else { // This is a variable shr.
6307
6308 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6309 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6310 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006311 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006312 Value *One = ConstantInt::get(SrcI->getType(), 1);
6313
Reid Spencer2341c222007-02-02 02:16:23 +00006314 Value *V = InsertNewInstBefore(
6315 BinaryOperator::create(Instruction::Shl, One, SrcI->getOperand(1),
6316 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00006317 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6318 SrcI->getOperand(0),
6319 "tmp"), CI);
6320 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006321 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006322 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006323 }
6324 break;
6325 }
6326 }
6327
6328 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006329}
6330
6331Instruction *InstCombiner::visitZExt(CastInst &CI) {
6332 // If one of the common conversion will work ..
6333 if (Instruction *Result = commonIntCastTransforms(CI))
6334 return Result;
6335
6336 Value *Src = CI.getOperand(0);
6337
6338 // If this is a cast of a cast
6339 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006340 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6341 // types and if the sizes are just right we can convert this into a logical
6342 // 'and' which will be much cheaper than the pair of casts.
6343 if (isa<TruncInst>(CSrc)) {
6344 // Get the sizes of the types involved
6345 Value *A = CSrc->getOperand(0);
6346 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6347 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6348 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6349 // If we're actually extending zero bits and the trunc is a no-op
6350 if (MidSize < DstSize && SrcSize == DstSize) {
6351 // Replace both of the casts with an And of the type mask.
Reid Spencera94d3942007-01-19 21:13:56 +00006352 uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006353 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6354 Instruction *And =
6355 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6356 // Unfortunately, if the type changed, we need to cast it back.
6357 if (And->getType() != CI.getType()) {
6358 And->setName(CSrc->getName()+".mask");
6359 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006360 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006361 }
6362 return And;
6363 }
6364 }
6365 }
6366
6367 return 0;
6368}
6369
6370Instruction *InstCombiner::visitSExt(CastInst &CI) {
6371 return commonIntCastTransforms(CI);
6372}
6373
6374Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6375 return commonCastTransforms(CI);
6376}
6377
6378Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6379 return commonCastTransforms(CI);
6380}
6381
6382Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006383 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006384}
6385
6386Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006387 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006388}
6389
6390Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6391 return commonCastTransforms(CI);
6392}
6393
6394Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6395 return commonCastTransforms(CI);
6396}
6397
6398Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006399 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006400}
6401
6402Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6403 return commonCastTransforms(CI);
6404}
6405
6406Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6407
6408 // If the operands are integer typed then apply the integer transforms,
6409 // otherwise just apply the common ones.
6410 Value *Src = CI.getOperand(0);
6411 const Type *SrcTy = Src->getType();
6412 const Type *DestTy = CI.getType();
6413
Chris Lattner03c49532007-01-15 02:27:26 +00006414 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006415 if (Instruction *Result = commonIntCastTransforms(CI))
6416 return Result;
6417 } else {
6418 if (Instruction *Result = commonCastTransforms(CI))
6419 return Result;
6420 }
6421
6422
6423 // Get rid of casts from one type to the same type. These are useless and can
6424 // be replaced by the operand.
6425 if (DestTy == Src->getType())
6426 return ReplaceInstUsesWith(CI, Src);
6427
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006428 // If the source and destination are pointers, and this cast is equivalent to
6429 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6430 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006431 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6432 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6433 const Type *DstElTy = DstPTy->getElementType();
6434 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006435
Reid Spencerc635f472006-12-31 05:48:39 +00006436 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006437 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006438 while (SrcElTy != DstElTy &&
6439 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6440 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6441 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006442 ++NumZeros;
6443 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006444
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006445 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006446 if (SrcElTy == DstElTy) {
Chris Lattner416a8932007-01-31 20:08:52 +00006447 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6448 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006449 }
6450 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006451 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006452
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006453 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6454 if (SVI->hasOneUse()) {
6455 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6456 // a bitconvert to a vector with the same # elts.
6457 if (isa<PackedType>(DestTy) &&
6458 cast<PackedType>(DestTy)->getNumElements() ==
6459 SVI->getType()->getNumElements()) {
6460 CastInst *Tmp;
6461 // If either of the operands is a cast from CI.getType(), then
6462 // evaluating the shuffle in the casted destination's type will allow
6463 // us to eliminate at least one cast.
6464 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6465 Tmp->getOperand(0)->getType() == DestTy) ||
6466 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6467 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006468 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6469 SVI->getOperand(0), DestTy, &CI);
6470 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6471 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006472 // Return a new shuffle vector. Use the same element ID's, as we
6473 // know the vector types match #elts.
6474 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006475 }
6476 }
6477 }
6478 }
Chris Lattner260ab202002-04-18 17:39:14 +00006479 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006480}
6481
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006482/// GetSelectFoldableOperands - We want to turn code that looks like this:
6483/// %C = or %A, %B
6484/// %D = select %cond, %C, %A
6485/// into:
6486/// %C = select %cond, %B, 0
6487/// %D = or %A, %C
6488///
6489/// Assuming that the specified instruction is an operand to the select, return
6490/// a bitmask indicating which operands of this instruction are foldable if they
6491/// equal the other incoming value of the select.
6492///
6493static unsigned GetSelectFoldableOperands(Instruction *I) {
6494 switch (I->getOpcode()) {
6495 case Instruction::Add:
6496 case Instruction::Mul:
6497 case Instruction::And:
6498 case Instruction::Or:
6499 case Instruction::Xor:
6500 return 3; // Can fold through either operand.
6501 case Instruction::Sub: // Can only fold on the amount subtracted.
6502 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006503 case Instruction::LShr:
6504 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006505 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006506 default:
6507 return 0; // Cannot fold
6508 }
6509}
6510
6511/// GetSelectFoldableConstant - For the same transformation as the previous
6512/// function, return the identity constant that goes into the select.
6513static Constant *GetSelectFoldableConstant(Instruction *I) {
6514 switch (I->getOpcode()) {
6515 default: assert(0 && "This cannot happen!"); abort();
6516 case Instruction::Add:
6517 case Instruction::Sub:
6518 case Instruction::Or:
6519 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006520 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006521 case Instruction::LShr:
6522 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00006523 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006524 case Instruction::And:
6525 return ConstantInt::getAllOnesValue(I->getType());
6526 case Instruction::Mul:
6527 return ConstantInt::get(I->getType(), 1);
6528 }
6529}
6530
Chris Lattner411336f2005-01-19 21:50:18 +00006531/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6532/// have the same opcode and only one use each. Try to simplify this.
6533Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6534 Instruction *FI) {
6535 if (TI->getNumOperands() == 1) {
6536 // If this is a non-volatile load or a cast from the same type,
6537 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006538 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006539 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6540 return 0;
6541 } else {
6542 return 0; // unknown unary op.
6543 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006544
Chris Lattner411336f2005-01-19 21:50:18 +00006545 // Fold this by inserting a select from the input values.
6546 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6547 FI->getOperand(0), SI.getName()+".v");
6548 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006549 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6550 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006551 }
6552
Reid Spencer2341c222007-02-02 02:16:23 +00006553 // Only handle binary operators here.
6554 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006555 return 0;
6556
6557 // Figure out if the operations have any operands in common.
6558 Value *MatchOp, *OtherOpT, *OtherOpF;
6559 bool MatchIsOpZero;
6560 if (TI->getOperand(0) == FI->getOperand(0)) {
6561 MatchOp = TI->getOperand(0);
6562 OtherOpT = TI->getOperand(1);
6563 OtherOpF = FI->getOperand(1);
6564 MatchIsOpZero = true;
6565 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6566 MatchOp = TI->getOperand(1);
6567 OtherOpT = TI->getOperand(0);
6568 OtherOpF = FI->getOperand(0);
6569 MatchIsOpZero = false;
6570 } else if (!TI->isCommutative()) {
6571 return 0;
6572 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6573 MatchOp = TI->getOperand(0);
6574 OtherOpT = TI->getOperand(1);
6575 OtherOpF = FI->getOperand(0);
6576 MatchIsOpZero = true;
6577 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6578 MatchOp = TI->getOperand(1);
6579 OtherOpT = TI->getOperand(0);
6580 OtherOpF = FI->getOperand(1);
6581 MatchIsOpZero = true;
6582 } else {
6583 return 0;
6584 }
6585
6586 // If we reach here, they do have operations in common.
6587 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6588 OtherOpF, SI.getName()+".v");
6589 InsertNewInstBefore(NewSI, SI);
6590
6591 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6592 if (MatchIsOpZero)
6593 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6594 else
6595 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006596 }
Reid Spencer43c77d52006-12-23 18:58:04 +00006597
Reid Spencer2341c222007-02-02 02:16:23 +00006598 assert(TI->isShift() && "Should only have Shift here");
Reid Spencer43c77d52006-12-23 18:58:04 +00006599 if (MatchIsOpZero)
Reid Spencer2341c222007-02-02 02:16:23 +00006600 return BinaryOperator::create(Instruction::BinaryOps(TI->getOpcode()),
6601 MatchOp, NewSI);
Reid Spencer43c77d52006-12-23 18:58:04 +00006602 else
Reid Spencer2341c222007-02-02 02:16:23 +00006603 return BinaryOperator::create(Instruction::BinaryOps(TI->getOpcode()),
6604 NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006605}
6606
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006607Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006608 Value *CondVal = SI.getCondition();
6609 Value *TrueVal = SI.getTrueValue();
6610 Value *FalseVal = SI.getFalseValue();
6611
6612 // select true, X, Y -> X
6613 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006614 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006615 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006616
6617 // select C, X, X -> X
6618 if (TrueVal == FalseVal)
6619 return ReplaceInstUsesWith(SI, TrueVal);
6620
Chris Lattner81a7a232004-10-16 18:11:37 +00006621 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6622 return ReplaceInstUsesWith(SI, FalseVal);
6623 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6624 return ReplaceInstUsesWith(SI, TrueVal);
6625 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6626 if (isa<Constant>(TrueVal))
6627 return ReplaceInstUsesWith(SI, TrueVal);
6628 else
6629 return ReplaceInstUsesWith(SI, FalseVal);
6630 }
6631
Reid Spencer542964f2007-01-11 18:21:29 +00006632 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006633 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006634 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006635 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006636 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006637 } else {
6638 // Change: A = select B, false, C --> A = and !B, C
6639 Value *NotCond =
6640 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6641 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006642 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006643 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006644 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006645 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006646 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006647 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006648 } else {
6649 // Change: A = select B, C, true --> A = or !B, C
6650 Value *NotCond =
6651 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6652 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006653 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006654 }
6655 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00006656 }
Chris Lattner1c631e82004-04-08 04:43:23 +00006657
Chris Lattner183b3362004-04-09 19:05:30 +00006658 // Selecting between two integer constants?
6659 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6660 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6661 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006662 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006663 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006664 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006665 // select C, 0, 1 -> cast !C to int
6666 Value *NotCond =
6667 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006668 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006669 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006670 }
Chris Lattner35167c32004-06-09 07:59:58 +00006671
Reid Spencer266e42b2006-12-23 06:05:41 +00006672 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006673
Reid Spencer266e42b2006-12-23 06:05:41 +00006674 // (x <s 0) ? -1 : 0 -> ashr x, 31
6675 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattner380c7e92006-09-20 04:44:59 +00006676 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6677 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6678 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006679 if (IC->isSignedPredicate())
Chris Lattner380c7e92006-09-20 04:44:59 +00006680 CanXForm = CmpCst->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006681 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006682 else {
6683 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006684 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006685 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006686 }
6687
6688 if (CanXForm) {
6689 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006690 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006691 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006692 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00006693 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
6694 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
6695 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00006696 InsertNewInstBefore(SRA, SI);
6697
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006698 // Finally, convert to the type of the select RHS. We figure out
6699 // if this requires a SExt, Trunc or BitCast based on the sizes.
6700 Instruction::CastOps opc = Instruction::BitCast;
6701 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6702 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6703 if (SRASize < SISize)
6704 opc = Instruction::SExt;
6705 else if (SRASize > SISize)
6706 opc = Instruction::Trunc;
6707 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006708 }
6709 }
6710
6711
6712 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006713 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006714 // non-constant value, eliminate this whole mess. This corresponds to
6715 // cases like this: ((X & 27) ? 27 : 0)
6716 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006717 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006718 cast<Constant>(IC->getOperand(1))->isNullValue())
6719 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6720 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006721 isa<ConstantInt>(ICA->getOperand(1)) &&
6722 (ICA->getOperand(1) == TrueValC ||
6723 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006724 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6725 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006726 // know whether we have a icmp_ne or icmp_eq and whether the
6727 // true or false val is the zero.
Chris Lattner35167c32004-06-09 07:59:58 +00006728 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006729 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006730 Value *V = ICA;
6731 if (ShouldNotVal)
6732 V = InsertNewInstBefore(BinaryOperator::create(
6733 Instruction::Xor, V, ICA->getOperand(1)), SI);
6734 return ReplaceInstUsesWith(SI, V);
6735 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006736 }
Chris Lattner533bc492004-03-30 19:37:13 +00006737 }
Chris Lattner623fba12004-04-10 22:21:27 +00006738
6739 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006740 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6741 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006742 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006743 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006744 return ReplaceInstUsesWith(SI, FalseVal);
6745 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006746 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006747 return ReplaceInstUsesWith(SI, TrueVal);
6748 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6749
Reid Spencer266e42b2006-12-23 06:05:41 +00006750 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006751 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006752 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006753 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006754 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006755 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6756 return ReplaceInstUsesWith(SI, TrueVal);
6757 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6758 }
6759 }
6760
6761 // See if we are selecting two values based on a comparison of the two values.
6762 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6763 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6764 // Transform (X == Y) ? X : Y -> Y
6765 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6766 return ReplaceInstUsesWith(SI, FalseVal);
6767 // Transform (X != Y) ? X : Y -> X
6768 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6769 return ReplaceInstUsesWith(SI, TrueVal);
6770 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6771
6772 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6773 // Transform (X == Y) ? Y : X -> X
6774 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6775 return ReplaceInstUsesWith(SI, FalseVal);
6776 // Transform (X != Y) ? Y : X -> Y
6777 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006778 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006779 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6780 }
6781 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006782
Chris Lattnera04c9042005-01-13 22:52:24 +00006783 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6784 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6785 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006786 Instruction *AddOp = 0, *SubOp = 0;
6787
Chris Lattner411336f2005-01-19 21:50:18 +00006788 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6789 if (TI->getOpcode() == FI->getOpcode())
6790 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6791 return IV;
6792
6793 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6794 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006795 if (TI->getOpcode() == Instruction::Sub &&
6796 FI->getOpcode() == Instruction::Add) {
6797 AddOp = FI; SubOp = TI;
6798 } else if (FI->getOpcode() == Instruction::Sub &&
6799 TI->getOpcode() == Instruction::Add) {
6800 AddOp = TI; SubOp = FI;
6801 }
6802
6803 if (AddOp) {
6804 Value *OtherAddOp = 0;
6805 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6806 OtherAddOp = AddOp->getOperand(1);
6807 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6808 OtherAddOp = AddOp->getOperand(0);
6809 }
6810
6811 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006812 // So at this point we know we have (Y -> OtherAddOp):
6813 // select C, (add X, Y), (sub X, Z)
6814 Value *NegVal; // Compute -Z
6815 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6816 NegVal = ConstantExpr::getNeg(C);
6817 } else {
6818 NegVal = InsertNewInstBefore(
6819 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006820 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006821
6822 Value *NewTrueOp = OtherAddOp;
6823 Value *NewFalseOp = NegVal;
6824 if (AddOp != TI)
6825 std::swap(NewTrueOp, NewFalseOp);
6826 Instruction *NewSel =
6827 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6828
6829 NewSel = InsertNewInstBefore(NewSel, SI);
6830 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006831 }
6832 }
6833 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006834
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006835 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00006836 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006837 // See the comment above GetSelectFoldableOperands for a description of the
6838 // transformation we are doing here.
6839 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6840 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6841 !isa<Constant>(FalseVal))
6842 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6843 unsigned OpToFold = 0;
6844 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6845 OpToFold = 1;
6846 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6847 OpToFold = 2;
6848 }
6849
6850 if (OpToFold) {
6851 Constant *C = GetSelectFoldableConstant(TVI);
6852 std::string Name = TVI->getName(); TVI->setName("");
6853 Instruction *NewSel =
6854 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6855 Name);
6856 InsertNewInstBefore(NewSel, SI);
6857 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);
Reid Spencer2341c222007-02-02 02:16:23 +00006878 std::string Name = FVI->getName();
6879 FVI->setName("");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006880 Instruction *NewSel =
6881 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6882 Name);
6883 InsertNewInstBefore(NewSel, SI);
6884 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6885 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00006886 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006887 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006888 }
6889 }
6890 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006891
6892 if (BinaryOperator::isNot(CondVal)) {
6893 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6894 SI.setOperand(1, FalseVal);
6895 SI.setOperand(2, TrueVal);
6896 return &SI;
6897 }
6898
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006899 return 0;
6900}
6901
Chris Lattner82f2ef22006-03-06 20:18:44 +00006902/// GetKnownAlignment - If the specified pointer has an alignment that we can
6903/// determine, return it, otherwise return 0.
6904static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6905 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6906 unsigned Align = GV->getAlignment();
6907 if (Align == 0 && TD)
Chris Lattner50ee0e42007-01-20 22:35:55 +00006908 Align = TD->getTypeAlignmentPref(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00006909 return Align;
6910 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6911 unsigned Align = AI->getAlignment();
6912 if (Align == 0 && TD) {
6913 if (isa<AllocaInst>(AI))
Chris Lattner50ee0e42007-01-20 22:35:55 +00006914 Align = TD->getTypeAlignmentPref(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00006915 else if (isa<MallocInst>(AI)) {
6916 // Malloc returns maximally aligned memory.
Chris Lattner50ee0e42007-01-20 22:35:55 +00006917 Align = TD->getTypeAlignmentABI(AI->getType()->getElementType());
6918 Align =
6919 std::max(Align,
6920 (unsigned)TD->getTypeAlignmentABI(Type::DoubleTy));
6921 Align =
6922 std::max(Align,
6923 (unsigned)TD->getTypeAlignmentABI(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006924 }
6925 }
6926 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006927 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00006928 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006929 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00006930 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006931 if (isa<PointerType>(CI->getOperand(0)->getType()))
6932 return GetKnownAlignment(CI->getOperand(0), TD);
6933 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006934 } else if (isa<GetElementPtrInst>(V) ||
6935 (isa<ConstantExpr>(V) &&
6936 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6937 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006938 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6939 if (BaseAlignment == 0) return 0;
6940
6941 // If all indexes are zero, it is just the alignment of the base pointer.
6942 bool AllZeroOperands = true;
6943 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6944 if (!isa<Constant>(GEPI->getOperand(i)) ||
6945 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6946 AllZeroOperands = false;
6947 break;
6948 }
6949 if (AllZeroOperands)
6950 return BaseAlignment;
6951
6952 // Otherwise, if the base alignment is >= the alignment we expect for the
6953 // base pointer type, then we know that the resultant pointer is aligned at
6954 // least as much as its type requires.
6955 if (!TD) return 0;
6956
6957 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00006958 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
6959 if (TD->getTypeAlignmentABI(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006960 <= BaseAlignment) {
6961 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00006962 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
6963 return TD->getTypeAlignmentABI(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00006964 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006965 return 0;
6966 }
6967 return 0;
6968}
6969
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006970
Chris Lattnerc66b2232006-01-13 20:11:04 +00006971/// visitCallInst - CallInst simplification. This mostly only handles folding
6972/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6973/// the heavy lifting.
6974///
Chris Lattner970c33a2003-06-19 17:00:31 +00006975Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006976 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6977 if (!II) return visitCallSite(&CI);
6978
Chris Lattner51ea1272004-02-28 05:22:00 +00006979 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6980 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006981 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006982 bool Changed = false;
6983
6984 // memmove/cpy/set of zero bytes is a noop.
6985 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6986 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6987
Chris Lattner00648e12004-10-12 04:52:52 +00006988 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006989 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006990 // Replace the instruction with just byte operations. We would
6991 // transform other cases to loads/stores, but we don't know if
6992 // alignment is sufficient.
6993 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006994 }
6995
Chris Lattner00648e12004-10-12 04:52:52 +00006996 // If we have a memmove and the source operation is a constant global,
6997 // then the source and dest pointers can't alias, so we can change this
6998 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006999 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007000 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7001 if (GVSrc->isConstant()) {
7002 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007003 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007004 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00007005 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00007006 Name = "llvm.memcpy.i32";
7007 else
7008 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00007009 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007010 CI.getCalledFunction()->getFunctionType());
7011 CI.setOperand(0, MemCpy);
7012 Changed = true;
7013 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007014 }
Chris Lattner00648e12004-10-12 04:52:52 +00007015
Chris Lattner82f2ef22006-03-06 20:18:44 +00007016 // If we can determine a pointer alignment that is bigger than currently
7017 // set, update the alignment.
7018 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7019 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7020 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7021 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007022 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007023 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007024 Changed = true;
7025 }
7026 } else if (isa<MemSetInst>(MI)) {
7027 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007028 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007029 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007030 Changed = true;
7031 }
7032 }
7033
Chris Lattnerc66b2232006-01-13 20:11:04 +00007034 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007035 } else {
7036 switch (II->getIntrinsicID()) {
7037 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007038 case Intrinsic::ppc_altivec_lvx:
7039 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007040 case Intrinsic::x86_sse_loadu_ps:
7041 case Intrinsic::x86_sse2_loadu_pd:
7042 case Intrinsic::x86_sse2_loadu_dq:
7043 // Turn PPC lvx -> load if the pointer is known aligned.
7044 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007045 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007046 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007047 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007048 return new LoadInst(Ptr);
7049 }
7050 break;
7051 case Intrinsic::ppc_altivec_stvx:
7052 case Intrinsic::ppc_altivec_stvxl:
7053 // Turn stvx -> store if the pointer is known aligned.
7054 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007055 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007056 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7057 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007058 return new StoreInst(II->getOperand(1), Ptr);
7059 }
7060 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007061 case Intrinsic::x86_sse_storeu_ps:
7062 case Intrinsic::x86_sse2_storeu_pd:
7063 case Intrinsic::x86_sse2_storeu_dq:
7064 case Intrinsic::x86_sse2_storel_dq:
7065 // Turn X86 storeu -> store if the pointer is known aligned.
7066 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7067 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007068 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7069 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007070 return new StoreInst(II->getOperand(2), Ptr);
7071 }
7072 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007073
7074 case Intrinsic::x86_sse_cvttss2si: {
7075 // These intrinsics only demands the 0th element of its input vector. If
7076 // we can simplify the input based on that, do so now.
7077 uint64_t UndefElts;
7078 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7079 UndefElts)) {
7080 II->setOperand(1, V);
7081 return II;
7082 }
7083 break;
7084 }
7085
Chris Lattnere79d2492006-04-06 19:19:17 +00007086 case Intrinsic::ppc_altivec_vperm:
7087 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7088 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7089 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7090
7091 // Check that all of the elements are integer constants or undefs.
7092 bool AllEltsOk = true;
7093 for (unsigned i = 0; i != 16; ++i) {
7094 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7095 !isa<UndefValue>(Mask->getOperand(i))) {
7096 AllEltsOk = false;
7097 break;
7098 }
7099 }
7100
7101 if (AllEltsOk) {
7102 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007103 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7104 II->getOperand(1), Mask->getType(), CI);
7105 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7106 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007107 Value *Result = UndefValue::get(Op0->getType());
7108
7109 // Only extract each element once.
7110 Value *ExtractedElts[32];
7111 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7112
7113 for (unsigned i = 0; i != 16; ++i) {
7114 if (isa<UndefValue>(Mask->getOperand(i)))
7115 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007116 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007117 Idx &= 31; // Match the hardware behavior.
7118
7119 if (ExtractedElts[Idx] == 0) {
7120 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007121 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007122 InsertNewInstBefore(Elt, CI);
7123 ExtractedElts[Idx] = Elt;
7124 }
7125
7126 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007127 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007128 InsertNewInstBefore(cast<Instruction>(Result), CI);
7129 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007130 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007131 }
7132 }
7133 break;
7134
Chris Lattner503221f2006-01-13 21:28:09 +00007135 case Intrinsic::stackrestore: {
7136 // If the save is right next to the restore, remove the restore. This can
7137 // happen when variable allocas are DCE'd.
7138 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7139 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7140 BasicBlock::iterator BI = SS;
7141 if (&*++BI == II)
7142 return EraseInstFromFunction(CI);
7143 }
7144 }
7145
7146 // If the stack restore is in a return/unwind block and if there are no
7147 // allocas or calls between the restore and the return, nuke the restore.
7148 TerminatorInst *TI = II->getParent()->getTerminator();
7149 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7150 BasicBlock::iterator BI = II;
7151 bool CannotRemove = false;
7152 for (++BI; &*BI != TI; ++BI) {
7153 if (isa<AllocaInst>(BI) ||
7154 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7155 CannotRemove = true;
7156 break;
7157 }
7158 }
7159 if (!CannotRemove)
7160 return EraseInstFromFunction(CI);
7161 }
7162 break;
7163 }
7164 }
Chris Lattner00648e12004-10-12 04:52:52 +00007165 }
7166
Chris Lattnerc66b2232006-01-13 20:11:04 +00007167 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007168}
7169
7170// InvokeInst simplification
7171//
7172Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007173 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007174}
7175
Chris Lattneraec3d942003-10-07 22:32:43 +00007176// visitCallSite - Improvements for call and invoke instructions.
7177//
7178Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007179 bool Changed = false;
7180
7181 // If the callee is a constexpr cast of a function, attempt to move the cast
7182 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007183 if (transformConstExprCastCall(CS)) return 0;
7184
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007185 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007186
Chris Lattner61d9d812005-05-13 07:09:09 +00007187 if (Function *CalleeF = dyn_cast<Function>(Callee))
7188 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7189 Instruction *OldCall = CS.getInstruction();
7190 // If the call and callee calling conventions don't match, this call must
7191 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007192 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007193 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007194 if (!OldCall->use_empty())
7195 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7196 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7197 return EraseInstFromFunction(*OldCall);
7198 return 0;
7199 }
7200
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007201 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7202 // This instruction is not reachable, just remove it. We insert a store to
7203 // undef so that we know that this code is not reachable, despite the fact
7204 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007205 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007206 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007207 CS.getInstruction());
7208
7209 if (!CS.getInstruction()->use_empty())
7210 CS.getInstruction()->
7211 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7212
7213 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7214 // Don't break the CFG, insert a dummy cond branch.
7215 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007216 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007217 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007218 return EraseInstFromFunction(*CS.getInstruction());
7219 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007220
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007221 const PointerType *PTy = cast<PointerType>(Callee->getType());
7222 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7223 if (FTy->isVarArg()) {
7224 // See if we can optimize any arguments passed through the varargs area of
7225 // the call.
7226 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7227 E = CS.arg_end(); I != E; ++I)
7228 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7229 // If this cast does not effect the value passed through the varargs
7230 // area, we can eliminate the use of the cast.
7231 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007232 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007233 *I = Op;
7234 Changed = true;
7235 }
7236 }
7237 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007238
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007239 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007240}
7241
Chris Lattner970c33a2003-06-19 17:00:31 +00007242// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7243// attempt to move the cast to the arguments of the call/invoke.
7244//
7245bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7246 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7247 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007248 if (CE->getOpcode() != Instruction::BitCast ||
7249 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007250 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007251 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007252 Instruction *Caller = CS.getInstruction();
7253
7254 // Okay, this is a cast from a function to a different type. Unless doing so
7255 // would cause a type conversion of one of our arguments, change this call to
7256 // be a direct call with arguments casted to the appropriate types.
7257 //
7258 const FunctionType *FT = Callee->getFunctionType();
7259 const Type *OldRetTy = Caller->getType();
7260
Chris Lattner1f7942f2004-01-14 06:06:08 +00007261 // Check to see if we are changing the return type...
7262 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00007263 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007264 OldRetTy != FT->getReturnType() &&
7265 // Conversion is ok if changing from pointer to int of same size.
7266 !(isa<PointerType>(FT->getReturnType()) &&
7267 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007268 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007269
7270 // If the callsite is an invoke instruction, and the return value is used by
7271 // a PHI node in a successor, we cannot change the return type of the call
7272 // because there is no place to put the cast instruction (without breaking
7273 // the critical edge). Bail out in this case.
7274 if (!Caller->use_empty())
7275 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7276 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7277 UI != E; ++UI)
7278 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7279 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007280 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007281 return false;
7282 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007283
7284 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7285 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007286
Chris Lattner970c33a2003-06-19 17:00:31 +00007287 CallSite::arg_iterator AI = CS.arg_begin();
7288 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7289 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007290 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007291 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007292 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007293 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007294 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00007295 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007296 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7297 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7298 && c->getSExtValue() > 0);
Reid Spencer5301e7c2007-01-30 20:08:39 +00007299 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007300 }
7301
7302 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00007303 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00007304 return false; // Do not delete arguments unless we have a function body...
7305
7306 // Okay, we decided that this is a safe thing to do: go ahead and start
7307 // inserting cast instructions as necessary...
7308 std::vector<Value*> Args;
7309 Args.reserve(NumActualArgs);
7310
7311 AI = CS.arg_begin();
7312 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7313 const Type *ParamTy = FT->getParamType(i);
7314 if ((*AI)->getType() == ParamTy) {
7315 Args.push_back(*AI);
7316 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007317 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007318 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007319 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007320 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007321 }
7322 }
7323
7324 // If the function takes more arguments than the call was taking, add them
7325 // now...
7326 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7327 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7328
7329 // If we are removing arguments to the function, emit an obnoxious warning...
7330 if (FT->getNumParams() < NumActualArgs)
7331 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007332 cerr << "WARNING: While resolving call to function '"
7333 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007334 } else {
7335 // Add all of the arguments in their promoted form to the arg list...
7336 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7337 const Type *PTy = getPromotedType((*AI)->getType());
7338 if (PTy != (*AI)->getType()) {
7339 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007340 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7341 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007342 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007343 InsertNewInstBefore(Cast, *Caller);
7344 Args.push_back(Cast);
7345 } else {
7346 Args.push_back(*AI);
7347 }
7348 }
7349 }
7350
7351 if (FT->getReturnType() == Type::VoidTy)
7352 Caller->setName(""); // Void type should not have a name...
7353
7354 Instruction *NC;
7355 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007356 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00007357 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007358 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007359 } else {
7360 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007361 if (cast<CallInst>(Caller)->isTailCall())
7362 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007363 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007364 }
7365
7366 // Insert a cast of the return type as necessary...
7367 Value *NV = NC;
7368 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7369 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007370 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007371 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7372 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007373 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007374
7375 // If this is an invoke instruction, we should insert it after the first
7376 // non-phi, instruction in the normal successor block.
7377 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7378 BasicBlock::iterator I = II->getNormalDest()->begin();
7379 while (isa<PHINode>(I)) ++I;
7380 InsertNewInstBefore(NC, *I);
7381 } else {
7382 // Otherwise, it's a call, just insert cast right after the call instr
7383 InsertNewInstBefore(NC, *Caller);
7384 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007385 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007386 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007387 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007388 }
7389 }
7390
7391 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7392 Caller->replaceAllUsesWith(NV);
7393 Caller->getParent()->getInstList().erase(Caller);
7394 removeFromWorkList(Caller);
7395 return true;
7396}
7397
Chris Lattnercadac0c2006-11-01 04:51:18 +00007398/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7399/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7400/// and a single binop.
7401Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7402 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00007403 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7404 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007405 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007406 Value *LHSVal = FirstInst->getOperand(0);
7407 Value *RHSVal = FirstInst->getOperand(1);
7408
7409 const Type *LHSType = LHSVal->getType();
7410 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007411
7412 // Scan to see if all operands are the same opcode, all have one use, and all
7413 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007414 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007415 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007416 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007417 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007418 // types or GEP's with different index types.
7419 I->getOperand(0)->getType() != LHSType ||
7420 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007421 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007422
7423 // If they are CmpInst instructions, check their predicates
7424 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7425 if (cast<CmpInst>(I)->getPredicate() !=
7426 cast<CmpInst>(FirstInst)->getPredicate())
7427 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007428
7429 // Keep track of which operand needs a phi node.
7430 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7431 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007432 }
7433
Chris Lattner4f218d52006-11-08 19:42:28 +00007434 // Otherwise, this is safe to transform, determine if it is profitable.
7435
7436 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7437 // Indexes are often folded into load/store instructions, so we don't want to
7438 // hide them behind a phi.
7439 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7440 return 0;
7441
Chris Lattnercadac0c2006-11-01 04:51:18 +00007442 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007443 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007444 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007445 if (LHSVal == 0) {
7446 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7447 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7448 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007449 InsertNewInstBefore(NewLHS, PN);
7450 LHSVal = NewLHS;
7451 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007452
7453 if (RHSVal == 0) {
7454 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7455 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7456 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007457 InsertNewInstBefore(NewRHS, PN);
7458 RHSVal = NewRHS;
7459 }
7460
Chris Lattnercd62f112006-11-08 19:29:23 +00007461 // Add all operands to the new PHIs.
7462 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7463 if (NewLHS) {
7464 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7465 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7466 }
7467 if (NewRHS) {
7468 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7469 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7470 }
7471 }
7472
Chris Lattnercadac0c2006-11-01 04:51:18 +00007473 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007474 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007475 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7476 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7477 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007478 else {
7479 assert(isa<GetElementPtrInst>(FirstInst));
7480 return new GetElementPtrInst(LHSVal, RHSVal);
7481 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007482}
7483
Chris Lattner14f82c72006-11-01 07:13:54 +00007484/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7485/// of the block that defines it. This means that it must be obvious the value
7486/// of the load is not changed from the point of the load to the end of the
7487/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00007488///
7489/// Finally, it is safe, but not profitable, to sink a load targetting a
7490/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7491/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00007492static bool isSafeToSinkLoad(LoadInst *L) {
7493 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7494
7495 for (++BBI; BBI != E; ++BBI)
7496 if (BBI->mayWriteToMemory())
7497 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00007498
7499 // Check for non-address taken alloca. If not address-taken already, it isn't
7500 // profitable to do this xform.
7501 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7502 bool isAddressTaken = false;
7503 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7504 UI != E; ++UI) {
7505 if (isa<LoadInst>(UI)) continue;
7506 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7507 // If storing TO the alloca, then the address isn't taken.
7508 if (SI->getOperand(1) == AI) continue;
7509 }
7510 isAddressTaken = true;
7511 break;
7512 }
7513
7514 if (!isAddressTaken)
7515 return false;
7516 }
7517
Chris Lattner14f82c72006-11-01 07:13:54 +00007518 return true;
7519}
7520
Chris Lattner970c33a2003-06-19 17:00:31 +00007521
Chris Lattner7515cab2004-11-14 19:13:23 +00007522// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7523// operator and they all are only used by the PHI, PHI together their
7524// inputs, and do the operation once, to the result of the PHI.
7525Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7526 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7527
7528 // Scan the instruction, looking for input operations that can be folded away.
7529 // If all input operands to the phi are the same instruction (e.g. a cast from
7530 // the same type or "+42") we can pull the operation through the PHI, reducing
7531 // code size and simplifying code.
7532 Constant *ConstantOp = 0;
7533 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007534 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007535 if (isa<CastInst>(FirstInst)) {
7536 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00007537 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007538 // Can fold binop, compare or shift here if the RHS is a constant,
7539 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007540 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007541 if (ConstantOp == 0)
7542 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007543 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7544 isVolatile = LI->isVolatile();
7545 // We can't sink the load if the loaded value could be modified between the
7546 // load and the PHI.
7547 if (LI->getParent() != PN.getIncomingBlock(0) ||
7548 !isSafeToSinkLoad(LI))
7549 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007550 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007551 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007552 return FoldPHIArgBinOpIntoPHI(PN);
7553 // Can't handle general GEPs yet.
7554 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007555 } else {
7556 return 0; // Cannot fold this operation.
7557 }
7558
7559 // Check to see if all arguments are the same operation.
7560 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7561 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7562 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007563 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007564 return 0;
7565 if (CastSrcTy) {
7566 if (I->getOperand(0)->getType() != CastSrcTy)
7567 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007568 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007569 // We can't sink the load if the loaded value could be modified between
7570 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007571 if (LI->isVolatile() != isVolatile ||
7572 LI->getParent() != PN.getIncomingBlock(i) ||
7573 !isSafeToSinkLoad(LI))
7574 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007575 } else if (I->getOperand(1) != ConstantOp) {
7576 return 0;
7577 }
7578 }
7579
7580 // Okay, they are all the same operation. Create a new PHI node of the
7581 // correct type, and PHI together all of the LHS's of the instructions.
7582 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7583 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007584 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007585
7586 Value *InVal = FirstInst->getOperand(0);
7587 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007588
7589 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007590 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7591 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7592 if (NewInVal != InVal)
7593 InVal = 0;
7594 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7595 }
7596
7597 Value *PhiVal;
7598 if (InVal) {
7599 // The new PHI unions all of the same values together. This is really
7600 // common, so we handle it intelligently here for compile-time speed.
7601 PhiVal = InVal;
7602 delete NewPN;
7603 } else {
7604 InsertNewInstBefore(NewPN, PN);
7605 PhiVal = NewPN;
7606 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007607
Chris Lattner7515cab2004-11-14 19:13:23 +00007608 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007609 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7610 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007611 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007612 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007613 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007614 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007615 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7616 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7617 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007618 else
Reid Spencer2341c222007-02-02 02:16:23 +00007619 assert(0 && "Unknown operation");
Chris Lattner7515cab2004-11-14 19:13:23 +00007620}
Chris Lattner48a44f72002-05-02 17:06:02 +00007621
Chris Lattner71536432005-01-17 05:10:15 +00007622/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7623/// that is dead.
7624static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7625 if (PN->use_empty()) return true;
7626 if (!PN->hasOneUse()) return false;
7627
7628 // Remember this node, and if we find the cycle, return.
7629 if (!PotentiallyDeadPHIs.insert(PN).second)
7630 return true;
7631
7632 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7633 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007634
Chris Lattner71536432005-01-17 05:10:15 +00007635 return false;
7636}
7637
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007638// PHINode simplification
7639//
Chris Lattner113f4f42002-06-25 16:13:24 +00007640Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007641 // If LCSSA is around, don't mess with Phi nodes
7642 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007643
Owen Andersonae8aa642006-07-10 22:03:18 +00007644 if (Value *V = PN.hasConstantValue())
7645 return ReplaceInstUsesWith(PN, V);
7646
Owen Andersonae8aa642006-07-10 22:03:18 +00007647 // If all PHI operands are the same operation, pull them through the PHI,
7648 // reducing code size.
7649 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7650 PN.getIncomingValue(0)->hasOneUse())
7651 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7652 return Result;
7653
7654 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7655 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7656 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007657 if (PN.hasOneUse()) {
7658 Instruction *PHIUser = cast<Instruction>(PN.use_back());
7659 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Owen Andersonae8aa642006-07-10 22:03:18 +00007660 std::set<PHINode*> PotentiallyDeadPHIs;
7661 PotentiallyDeadPHIs.insert(&PN);
7662 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7663 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7664 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007665
7666 // If this phi has a single use, and if that use just computes a value for
7667 // the next iteration of a loop, delete the phi. This occurs with unused
7668 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7669 // common case here is good because the only other things that catch this
7670 // are induction variable analysis (sometimes) and ADCE, which is only run
7671 // late.
7672 if (PHIUser->hasOneUse() &&
7673 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7674 PHIUser->use_back() == &PN) {
7675 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7676 }
7677 }
Owen Andersonae8aa642006-07-10 22:03:18 +00007678
Chris Lattner91daeb52003-12-19 05:58:40 +00007679 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007680}
7681
Reid Spencer13bc5d72006-12-12 09:18:51 +00007682static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7683 Instruction *InsertPoint,
7684 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00007685 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7686 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007687 // We must cast correctly to the pointer type. Ensure that we
7688 // sign extend the integer value if it is smaller as this is
7689 // used for address computation.
7690 Instruction::CastOps opcode =
7691 (VTySize < PtrSize ? Instruction::SExt :
7692 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7693 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007694}
7695
Chris Lattner48a44f72002-05-02 17:06:02 +00007696
Chris Lattner113f4f42002-06-25 16:13:24 +00007697Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007698 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007699 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007700 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007701 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007702 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007703
Chris Lattner81a7a232004-10-16 18:11:37 +00007704 if (isa<UndefValue>(GEP.getOperand(0)))
7705 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7706
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007707 bool HasZeroPointerIndex = false;
7708 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7709 HasZeroPointerIndex = C->isNullValue();
7710
7711 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007712 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007713
Chris Lattner69193f92004-04-05 01:30:19 +00007714 // Eliminate unneeded casts for indices.
7715 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007716 gep_type_iterator GTI = gep_type_begin(GEP);
7717 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7718 if (isa<SequentialType>(*GTI)) {
7719 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00007720 if (CI->getOpcode() == Instruction::ZExt ||
7721 CI->getOpcode() == Instruction::SExt) {
7722 const Type *SrcTy = CI->getOperand(0)->getType();
7723 // We can eliminate a cast from i32 to i64 iff the target
7724 // is a 32-bit pointer target.
7725 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7726 MadeChange = true;
7727 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00007728 }
7729 }
7730 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007731 // If we are using a wider index than needed for this platform, shrink it
7732 // to what we need. If the incoming value needs a cast instruction,
7733 // insert it. This explicit cast can make subsequent optimizations more
7734 // obvious.
7735 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007736 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007737 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007738 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007739 MadeChange = true;
7740 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007741 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7742 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007743 GEP.setOperand(i, Op);
7744 MadeChange = true;
7745 }
Chris Lattner69193f92004-04-05 01:30:19 +00007746 }
7747 if (MadeChange) return &GEP;
7748
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007749 // Combine Indices - If the source pointer to this getelementptr instruction
7750 // is a getelementptr instruction, combine the indices of the two
7751 // getelementptr instructions into a single instruction.
7752 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007753 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007754 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007755 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007756
7757 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007758 // Note that if our source is a gep chain itself that we wait for that
7759 // chain to be resolved before we perform this transformation. This
7760 // avoids us creating a TON of code in some cases.
7761 //
7762 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7763 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7764 return 0; // Wait until our source is folded to completion.
7765
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007766 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007767
7768 // Find out whether the last index in the source GEP is a sequential idx.
7769 bool EndsWithSequential = false;
7770 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7771 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007772 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007773
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007774 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007775 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007776 // Replace: gep (gep %P, long B), long A, ...
7777 // With: T = long A+B; gep %P, T, ...
7778 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007779 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007780 if (SO1 == Constant::getNullValue(SO1->getType())) {
7781 Sum = GO1;
7782 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7783 Sum = SO1;
7784 } else {
7785 // If they aren't the same type, convert both to an integer of the
7786 // target's pointer size.
7787 if (SO1->getType() != GO1->getType()) {
7788 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007789 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007790 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007791 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007792 } else {
7793 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007794 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007795 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007796 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007797
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007798 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007799 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007800 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007801 } else {
7802 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007803 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7804 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007805 }
7806 }
7807 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007808 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7809 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7810 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007811 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7812 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007813 }
Chris Lattner69193f92004-04-05 01:30:19 +00007814 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007815
7816 // Recycle the GEP we already have if possible.
7817 if (SrcGEPOperands.size() == 2) {
7818 GEP.setOperand(0, SrcGEPOperands[0]);
7819 GEP.setOperand(1, Sum);
7820 return &GEP;
7821 } else {
7822 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7823 SrcGEPOperands.end()-1);
7824 Indices.push_back(Sum);
7825 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7826 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007827 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007828 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007829 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007830 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007831 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7832 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007833 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7834 }
7835
7836 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007837 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007838
Chris Lattner5f667a62004-05-07 22:09:22 +00007839 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007840 // GEP of global variable. If all of the indices for this GEP are
7841 // constants, we can promote this to a constexpr instead of an instruction.
7842
7843 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00007844 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007845 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7846 for (; I != E && isa<Constant>(*I); ++I)
7847 Indices.push_back(cast<Constant>(*I));
7848
7849 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00007850 Constant *CE = ConstantExpr::getGetElementPtr(GV,
7851 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007852
7853 // Replace all uses of the GEP with the new constexpr...
7854 return ReplaceInstUsesWith(GEP, CE);
7855 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007856 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00007857 if (!isa<PointerType>(X->getType())) {
7858 // Not interesting. Source pointer must be a cast from pointer.
7859 } else if (HasZeroPointerIndex) {
7860 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7861 // into : GEP [10 x ubyte]* X, long 0, ...
7862 //
7863 // This occurs when the program declares an array extern like "int X[];"
7864 //
7865 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7866 const PointerType *XTy = cast<PointerType>(X->getType());
7867 if (const ArrayType *XATy =
7868 dyn_cast<ArrayType>(XTy->getElementType()))
7869 if (const ArrayType *CATy =
7870 dyn_cast<ArrayType>(CPTy->getElementType()))
7871 if (CATy->getElementType() == XATy->getElementType()) {
7872 // At this point, we know that the cast source type is a pointer
7873 // to an array of the same type as the destination pointer
7874 // array. Because the array type is never stepped over (there
7875 // is a leading zero) we can fold the cast into this GEP.
7876 GEP.setOperand(0, X);
7877 return &GEP;
7878 }
7879 } else if (GEP.getNumOperands() == 2) {
7880 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007881 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7882 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007883 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7884 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7885 if (isa<ArrayType>(SrcElTy) &&
7886 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7887 TD->getTypeSize(ResElTy)) {
7888 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00007889 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00007890 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007891 // V and GEP are both pointer types --> BitCast
7892 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007893 }
Chris Lattner2a893292005-09-13 18:36:04 +00007894
7895 // Transform things like:
7896 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7897 // (where tmp = 8*tmp2) into:
7898 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7899
7900 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00007901 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00007902 uint64_t ArrayEltSize =
7903 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7904
7905 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7906 // allow either a mul, shift, or constant here.
7907 Value *NewIdx = 0;
7908 ConstantInt *Scale = 0;
7909 if (ArrayEltSize == 1) {
7910 NewIdx = GEP.getOperand(1);
7911 Scale = ConstantInt::get(NewIdx->getType(), 1);
7912 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007913 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007914 Scale = CI;
7915 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7916 if (Inst->getOpcode() == Instruction::Shl &&
7917 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007918 unsigned ShAmt =
7919 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007920 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007921 NewIdx = Inst->getOperand(0);
7922 } else if (Inst->getOpcode() == Instruction::Mul &&
7923 isa<ConstantInt>(Inst->getOperand(1))) {
7924 Scale = cast<ConstantInt>(Inst->getOperand(1));
7925 NewIdx = Inst->getOperand(0);
7926 }
7927 }
7928
7929 // If the index will be to exactly the right offset with the scale taken
7930 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007931 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007932 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007933 Scale = ConstantInt::get(Scale->getType(),
7934 Scale->getZExtValue() / ArrayEltSize);
7935 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007936 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7937 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00007938 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7939 NewIdx = InsertNewInstBefore(Sc, GEP);
7940 }
7941
7942 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007943 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00007944 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00007945 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007946 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7947 // The NewGEP must be pointer typed, so must the old one -> BitCast
7948 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00007949 }
7950 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007951 }
Chris Lattnerca081252001-12-14 16:52:21 +00007952 }
7953
Chris Lattnerca081252001-12-14 16:52:21 +00007954 return 0;
7955}
7956
Chris Lattner1085bdf2002-11-04 16:18:53 +00007957Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7958 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7959 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007960 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7961 const Type *NewTy =
7962 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007963 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007964
7965 // Create and insert the replacement instruction...
7966 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007967 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007968 else {
7969 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007970 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007971 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007972
7973 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007974
Chris Lattner1085bdf2002-11-04 16:18:53 +00007975 // Scan to the end of the allocation instructions, to skip over a block of
7976 // allocas if possible...
7977 //
7978 BasicBlock::iterator It = New;
7979 while (isa<AllocationInst>(*It)) ++It;
7980
7981 // Now that I is pointing to the first non-allocation-inst in the block,
7982 // insert our getelementptr instruction...
7983 //
Reid Spencerc635f472006-12-31 05:48:39 +00007984 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00007985 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7986 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007987
7988 // Now make everything use the getelementptr instead of the original
7989 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007990 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007991 } else if (isa<UndefValue>(AI.getArraySize())) {
7992 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007993 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007994
7995 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7996 // Note that we only do this for alloca's, because malloc should allocate and
7997 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007998 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007999 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00008000 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8001
Chris Lattner1085bdf2002-11-04 16:18:53 +00008002 return 0;
8003}
8004
Chris Lattner8427bff2003-12-07 01:24:23 +00008005Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8006 Value *Op = FI.getOperand(0);
8007
8008 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8009 if (CastInst *CI = dyn_cast<CastInst>(Op))
8010 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8011 FI.setOperand(0, CI->getOperand(0));
8012 return &FI;
8013 }
8014
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008015 // free undef -> unreachable.
8016 if (isa<UndefValue>(Op)) {
8017 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008018 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008019 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008020 return EraseInstFromFunction(FI);
8021 }
8022
Chris Lattnerf3a36602004-02-28 04:57:37 +00008023 // If we have 'free null' delete the instruction. This can happen in stl code
8024 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008025 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008026 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00008027
Chris Lattner8427bff2003-12-07 01:24:23 +00008028 return 0;
8029}
8030
8031
Chris Lattner72684fe2005-01-31 05:51:45 +00008032/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008033static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8034 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008035 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008036
8037 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008038 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008039 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008040
Reid Spencer31a4ef42007-01-22 05:51:25 +00008041 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
8042 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008043 // If the source is an array, the code below will not succeed. Check to
8044 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8045 // constants.
8046 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8047 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8048 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008049 Value *Idxs[2];
8050 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8051 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008052 SrcTy = cast<PointerType>(CastOp->getType());
8053 SrcPTy = SrcTy->getElementType();
8054 }
8055
Reid Spencer31a4ef42007-01-22 05:51:25 +00008056 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
8057 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008058 // Do not allow turning this into a load of an integer, which is then
8059 // casted to a pointer, this pessimizes pointer analysis a lot.
8060 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008061 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8062 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008063
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008064 // Okay, we are casting from one integer or pointer type to another of
8065 // the same size. Instead of casting the pointer before the load, cast
8066 // the result of the loaded value.
8067 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8068 CI->getName(),
8069 LI.isVolatile()),LI);
8070 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008071 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008072 }
Chris Lattner35e24772004-07-13 01:49:43 +00008073 }
8074 }
8075 return 0;
8076}
8077
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008078/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008079/// from this value cannot trap. If it is not obviously safe to load from the
8080/// specified pointer, we do a quick local scan of the basic block containing
8081/// ScanFrom, to determine if the address is already accessed.
8082static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8083 // If it is an alloca or global variable, it is always safe to load from.
8084 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8085
8086 // Otherwise, be a little bit agressive by scanning the local block where we
8087 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008088 // from/to. If so, the previous load or store would have already trapped,
8089 // so there is no harm doing an extra load (also, CSE will later eliminate
8090 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008091 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8092
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008093 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008094 --BBI;
8095
8096 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8097 if (LI->getOperand(0) == V) return true;
8098 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8099 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008100
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008101 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008102 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008103}
8104
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008105Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8106 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008107
Chris Lattnera9d84e32005-05-01 04:24:53 +00008108 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008109 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008110 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8111 return Res;
8112
8113 // None of the following transforms are legal for volatile loads.
8114 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008115
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008116 if (&LI.getParent()->front() != &LI) {
8117 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008118 // If the instruction immediately before this is a store to the same
8119 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008120 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8121 if (SI->getOperand(1) == LI.getOperand(0))
8122 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008123 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8124 if (LIB->getOperand(0) == LI.getOperand(0))
8125 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008126 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008127
8128 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8129 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8130 isa<UndefValue>(GEPI->getOperand(0))) {
8131 // Insert a new store to null instruction before the load to indicate
8132 // that this code is not reachable. We do this instead of inserting
8133 // an unreachable instruction directly because we cannot modify the
8134 // CFG.
8135 new StoreInst(UndefValue::get(LI.getType()),
8136 Constant::getNullValue(Op->getType()), &LI);
8137 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8138 }
8139
Chris Lattner81a7a232004-10-16 18:11:37 +00008140 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008141 // load null/undef -> undef
8142 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008143 // Insert a new store to null instruction before the load to indicate that
8144 // this code is not reachable. We do this instead of inserting an
8145 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008146 new StoreInst(UndefValue::get(LI.getType()),
8147 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008148 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008149 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008150
Chris Lattner81a7a232004-10-16 18:11:37 +00008151 // Instcombine load (constant global) into the value loaded.
8152 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008153 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00008154 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008155
Chris Lattner81a7a232004-10-16 18:11:37 +00008156 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8157 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8158 if (CE->getOpcode() == Instruction::GetElementPtr) {
8159 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008160 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008161 if (Constant *V =
8162 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008163 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008164 if (CE->getOperand(0)->isNullValue()) {
8165 // Insert a new store to null instruction before the load to indicate
8166 // that this code is not reachable. We do this instead of inserting
8167 // an unreachable instruction directly because we cannot modify the
8168 // CFG.
8169 new StoreInst(UndefValue::get(LI.getType()),
8170 Constant::getNullValue(Op->getType()), &LI);
8171 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8172 }
8173
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008174 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008175 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8176 return Res;
8177 }
8178 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008179
Chris Lattnera9d84e32005-05-01 04:24:53 +00008180 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008181 // Change select and PHI nodes to select values instead of addresses: this
8182 // helps alias analysis out a lot, allows many others simplifications, and
8183 // exposes redundancy in the code.
8184 //
8185 // Note that we cannot do the transformation unless we know that the
8186 // introduced loads cannot trap! Something like this is valid as long as
8187 // the condition is always false: load (select bool %C, int* null, int* %G),
8188 // but it would not be valid if we transformed it to load from null
8189 // unconditionally.
8190 //
8191 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8192 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008193 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8194 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008195 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008196 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008197 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008198 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008199 return new SelectInst(SI->getCondition(), V1, V2);
8200 }
8201
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008202 // load (select (cond, null, P)) -> load P
8203 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8204 if (C->isNullValue()) {
8205 LI.setOperand(0, SI->getOperand(2));
8206 return &LI;
8207 }
8208
8209 // load (select (cond, P, null)) -> load P
8210 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8211 if (C->isNullValue()) {
8212 LI.setOperand(0, SI->getOperand(1));
8213 return &LI;
8214 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008215 }
8216 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008217 return 0;
8218}
8219
Reid Spencere928a152007-01-19 21:20:31 +00008220/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00008221/// when possible.
8222static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8223 User *CI = cast<User>(SI.getOperand(1));
8224 Value *CastOp = CI->getOperand(0);
8225
8226 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8227 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8228 const Type *SrcPTy = SrcTy->getElementType();
8229
Reid Spencer31a4ef42007-01-22 05:51:25 +00008230 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008231 // If the source is an array, the code below will not succeed. Check to
8232 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8233 // constants.
8234 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8235 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8236 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008237 Value* Idxs[2];
8238 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8239 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00008240 SrcTy = cast<PointerType>(CastOp->getType());
8241 SrcPTy = SrcTy->getElementType();
8242 }
8243
Reid Spencer9a4bed02007-01-20 23:35:48 +00008244 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8245 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8246 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008247
8248 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00008249 // the same size. Instead of casting the pointer before
8250 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00008251 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008252 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00008253 Instruction::CastOps opcode = Instruction::BitCast;
8254 const Type* CastSrcTy = SIOp0->getType();
8255 const Type* CastDstTy = SrcPTy;
8256 if (isa<PointerType>(CastDstTy)) {
8257 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008258 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00008259 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008260 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008261 opcode = Instruction::PtrToInt;
8262 }
8263 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00008264 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008265 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008266 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00008267 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8268 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008269 return new StoreInst(NewCast, CastOp);
8270 }
8271 }
8272 }
8273 return 0;
8274}
8275
Chris Lattner31f486c2005-01-31 05:36:43 +00008276Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8277 Value *Val = SI.getOperand(0);
8278 Value *Ptr = SI.getOperand(1);
8279
8280 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008281 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008282 ++NumCombined;
8283 return 0;
8284 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00008285
8286 // If the RHS is an alloca with a single use, zapify the store, making the
8287 // alloca dead.
8288 if (Ptr->hasOneUse()) {
8289 if (isa<AllocaInst>(Ptr)) {
8290 EraseInstFromFunction(SI);
8291 ++NumCombined;
8292 return 0;
8293 }
8294
8295 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8296 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8297 GEP->getOperand(0)->hasOneUse()) {
8298 EraseInstFromFunction(SI);
8299 ++NumCombined;
8300 return 0;
8301 }
8302 }
Chris Lattner31f486c2005-01-31 05:36:43 +00008303
Chris Lattner5997cf92006-02-08 03:25:32 +00008304 // Do really simple DSE, to catch cases where there are several consequtive
8305 // stores to the same location, separated by a few arithmetic operations. This
8306 // situation often occurs with bitfield accesses.
8307 BasicBlock::iterator BBI = &SI;
8308 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8309 --ScanInsts) {
8310 --BBI;
8311
8312 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8313 // Prev store isn't volatile, and stores to the same location?
8314 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8315 ++NumDeadStore;
8316 ++BBI;
8317 EraseInstFromFunction(*PrevSI);
8318 continue;
8319 }
8320 break;
8321 }
8322
Chris Lattnerdab43b22006-05-26 19:19:20 +00008323 // If this is a load, we have to stop. However, if the loaded value is from
8324 // the pointer we're loading and is producing the pointer we're storing,
8325 // then *this* store is dead (X = load P; store X -> P).
8326 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8327 if (LI == Val && LI->getOperand(0) == Ptr) {
8328 EraseInstFromFunction(SI);
8329 ++NumCombined;
8330 return 0;
8331 }
8332 // Otherwise, this is a load from some other location. Stores before it
8333 // may not be dead.
8334 break;
8335 }
8336
Chris Lattner5997cf92006-02-08 03:25:32 +00008337 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008338 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008339 break;
8340 }
8341
8342
8343 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008344
8345 // store X, null -> turns into 'unreachable' in SimplifyCFG
8346 if (isa<ConstantPointerNull>(Ptr)) {
8347 if (!isa<UndefValue>(Val)) {
8348 SI.setOperand(0, UndefValue::get(Val->getType()));
8349 if (Instruction *U = dyn_cast<Instruction>(Val))
8350 WorkList.push_back(U); // Dropped a use.
8351 ++NumCombined;
8352 }
8353 return 0; // Do not modify these!
8354 }
8355
8356 // store undef, Ptr -> noop
8357 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008358 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008359 ++NumCombined;
8360 return 0;
8361 }
8362
Chris Lattner72684fe2005-01-31 05:51:45 +00008363 // If the pointer destination is a cast, see if we can fold the cast into the
8364 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008365 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008366 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8367 return Res;
8368 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008369 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008370 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8371 return Res;
8372
Chris Lattner219175c2005-09-12 23:23:25 +00008373
8374 // If this store is the last instruction in the basic block, and if the block
8375 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008376 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008377 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8378 if (BI->isUnconditional()) {
8379 // Check to see if the successor block has exactly two incoming edges. If
8380 // so, see if the other predecessor contains a store to the same location.
8381 // if so, insert a PHI node (if needed) and move the stores down.
8382 BasicBlock *Dest = BI->getSuccessor(0);
8383
8384 pred_iterator PI = pred_begin(Dest);
8385 BasicBlock *Other = 0;
8386 if (*PI != BI->getParent())
8387 Other = *PI;
8388 ++PI;
8389 if (PI != pred_end(Dest)) {
8390 if (*PI != BI->getParent())
8391 if (Other)
8392 Other = 0;
8393 else
8394 Other = *PI;
8395 if (++PI != pred_end(Dest))
8396 Other = 0;
8397 }
8398 if (Other) { // If only one other pred...
8399 BBI = Other->getTerminator();
8400 // Make sure this other block ends in an unconditional branch and that
8401 // there is an instruction before the branch.
8402 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8403 BBI != Other->begin()) {
8404 --BBI;
8405 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8406
8407 // If this instruction is a store to the same location.
8408 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8409 // Okay, we know we can perform this transformation. Insert a PHI
8410 // node now if we need it.
8411 Value *MergedVal = OtherStore->getOperand(0);
8412 if (MergedVal != SI.getOperand(0)) {
8413 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8414 PN->reserveOperandSpace(2);
8415 PN->addIncoming(SI.getOperand(0), SI.getParent());
8416 PN->addIncoming(OtherStore->getOperand(0), Other);
8417 MergedVal = InsertNewInstBefore(PN, Dest->front());
8418 }
8419
8420 // Advance to a place where it is safe to insert the new store and
8421 // insert it.
8422 BBI = Dest->begin();
8423 while (isa<PHINode>(BBI)) ++BBI;
8424 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8425 OtherStore->isVolatile()), *BBI);
8426
8427 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008428 EraseInstFromFunction(SI);
8429 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008430 ++NumCombined;
8431 return 0;
8432 }
8433 }
8434 }
8435 }
8436
Chris Lattner31f486c2005-01-31 05:36:43 +00008437 return 0;
8438}
8439
8440
Chris Lattner9eef8a72003-06-04 04:46:00 +00008441Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8442 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008443 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008444 BasicBlock *TrueDest;
8445 BasicBlock *FalseDest;
8446 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8447 !isa<Constant>(X)) {
8448 // Swap Destinations and condition...
8449 BI.setCondition(X);
8450 BI.setSuccessor(0, FalseDest);
8451 BI.setSuccessor(1, TrueDest);
8452 return &BI;
8453 }
8454
Reid Spencer266e42b2006-12-23 06:05:41 +00008455 // Cannonicalize fcmp_one -> fcmp_oeq
8456 FCmpInst::Predicate FPred; Value *Y;
8457 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8458 TrueDest, FalseDest)))
8459 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8460 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8461 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Chris Lattnerd4252a72004-07-30 07:50:03 +00008462 std::string Name = I->getName(); I->setName("");
Reid Spencer266e42b2006-12-23 06:05:41 +00008463 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8464 Value *NewSCC = new FCmpInst(NewPred, X, Y, Name, I);
8465 // Swap Destinations and condition...
8466 BI.setCondition(NewSCC);
8467 BI.setSuccessor(0, FalseDest);
8468 BI.setSuccessor(1, TrueDest);
8469 removeFromWorkList(I);
8470 I->getParent()->getInstList().erase(I);
8471 WorkList.push_back(cast<Instruction>(NewSCC));
8472 return &BI;
8473 }
8474
8475 // Cannonicalize icmp_ne -> icmp_eq
8476 ICmpInst::Predicate IPred;
8477 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8478 TrueDest, FalseDest)))
8479 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8480 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8481 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8482 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8483 std::string Name = I->getName(); I->setName("");
8484 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8485 Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00008486 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008487 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008488 BI.setSuccessor(0, FalseDest);
8489 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00008490 removeFromWorkList(I);
8491 I->getParent()->getInstList().erase(I);
8492 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00008493 return &BI;
8494 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008495
Chris Lattner9eef8a72003-06-04 04:46:00 +00008496 return 0;
8497}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008498
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008499Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8500 Value *Cond = SI.getCondition();
8501 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8502 if (I->getOpcode() == Instruction::Add)
8503 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8504 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8505 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008506 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008507 AddRHS));
8508 SI.setOperand(0, I->getOperand(0));
8509 WorkList.push_back(I);
8510 return &SI;
8511 }
8512 }
8513 return 0;
8514}
8515
Chris Lattner6bc98652006-03-05 00:22:33 +00008516/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8517/// is to leave as a vector operation.
8518static bool CheapToScalarize(Value *V, bool isConstant) {
8519 if (isa<ConstantAggregateZero>(V))
8520 return true;
8521 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8522 if (isConstant) return true;
8523 // If all elts are the same, we can extract.
8524 Constant *Op0 = C->getOperand(0);
8525 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8526 if (C->getOperand(i) != Op0)
8527 return false;
8528 return true;
8529 }
8530 Instruction *I = dyn_cast<Instruction>(V);
8531 if (!I) return false;
8532
8533 // Insert element gets simplified to the inserted element or is deleted if
8534 // this is constant idx extract element and its a constant idx insertelt.
8535 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8536 isa<ConstantInt>(I->getOperand(2)))
8537 return true;
8538 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8539 return true;
8540 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8541 if (BO->hasOneUse() &&
8542 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8543 CheapToScalarize(BO->getOperand(1), isConstant)))
8544 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008545 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8546 if (CI->hasOneUse() &&
8547 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8548 CheapToScalarize(CI->getOperand(1), isConstant)))
8549 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008550
8551 return false;
8552}
8553
Chris Lattner12249be2006-05-25 23:48:38 +00008554/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8555/// elements into values that are larger than the #elts in the input.
8556static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8557 unsigned NElts = SVI->getType()->getNumElements();
8558 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8559 return std::vector<unsigned>(NElts, 0);
8560 if (isa<UndefValue>(SVI->getOperand(2)))
8561 return std::vector<unsigned>(NElts, 2*NElts);
8562
8563 std::vector<unsigned> Result;
8564 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8565 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8566 if (isa<UndefValue>(CP->getOperand(i)))
8567 Result.push_back(NElts*2); // undef -> 8
8568 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008569 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008570 return Result;
8571}
8572
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008573/// FindScalarElement - Given a vector and an element number, see if the scalar
8574/// value is already around as a register, for example if it were inserted then
8575/// extracted from the vector.
8576static Value *FindScalarElement(Value *V, unsigned EltNo) {
8577 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8578 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008579 unsigned Width = PTy->getNumElements();
8580 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008581 return UndefValue::get(PTy->getElementType());
8582
8583 if (isa<UndefValue>(V))
8584 return UndefValue::get(PTy->getElementType());
8585 else if (isa<ConstantAggregateZero>(V))
8586 return Constant::getNullValue(PTy->getElementType());
8587 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8588 return CP->getOperand(EltNo);
8589 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8590 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008591 if (!isa<ConstantInt>(III->getOperand(2)))
8592 return 0;
8593 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008594
8595 // If this is an insert to the element we are looking for, return the
8596 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008597 if (EltNo == IIElt)
8598 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008599
8600 // Otherwise, the insertelement doesn't modify the value, recurse on its
8601 // vector input.
8602 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008603 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008604 unsigned InEl = getShuffleMask(SVI)[EltNo];
8605 if (InEl < Width)
8606 return FindScalarElement(SVI->getOperand(0), InEl);
8607 else if (InEl < Width*2)
8608 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8609 else
8610 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008611 }
8612
8613 // Otherwise, we don't know.
8614 return 0;
8615}
8616
Robert Bocchinoa8352962006-01-13 22:48:06 +00008617Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008618
Chris Lattner92346c32006-03-31 18:25:14 +00008619 // If packed val is undef, replace extract with scalar undef.
8620 if (isa<UndefValue>(EI.getOperand(0)))
8621 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8622
8623 // If packed val is constant 0, replace extract with scalar 0.
8624 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8625 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8626
Robert Bocchinoa8352962006-01-13 22:48:06 +00008627 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8628 // If packed val is constant with uniform operands, replace EI
8629 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008630 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008631 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008632 if (C->getOperand(i) != op0) {
8633 op0 = 0;
8634 break;
8635 }
8636 if (op0)
8637 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008638 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008639
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008640 // If extracting a specified index from the vector, see if we can recursively
8641 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008642 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008643 // This instruction only demands the single element from the input vector.
8644 // If the input vector has a single use, simplify it based on this use
8645 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008646 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008647 if (EI.getOperand(0)->hasOneUse()) {
8648 uint64_t UndefElts;
8649 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008650 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008651 UndefElts)) {
8652 EI.setOperand(0, V);
8653 return &EI;
8654 }
8655 }
8656
Reid Spencere0fc4df2006-10-20 07:07:24 +00008657 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008658 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008659 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008660
Chris Lattner83f65782006-05-25 22:53:38 +00008661 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008662 if (I->hasOneUse()) {
8663 // Push extractelement into predecessor operation if legal and
8664 // profitable to do so
8665 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008666 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8667 if (CheapToScalarize(BO, isConstantElt)) {
8668 ExtractElementInst *newEI0 =
8669 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8670 EI.getName()+".lhs");
8671 ExtractElementInst *newEI1 =
8672 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8673 EI.getName()+".rhs");
8674 InsertNewInstBefore(newEI0, EI);
8675 InsertNewInstBefore(newEI1, EI);
8676 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8677 }
Reid Spencerde46e482006-11-02 20:25:50 +00008678 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008679 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008680 PointerType::get(EI.getType()), EI);
8681 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008682 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008683 InsertNewInstBefore(GEP, EI);
8684 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008685 }
8686 }
8687 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8688 // Extracting the inserted element?
8689 if (IE->getOperand(2) == EI.getOperand(1))
8690 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8691 // If the inserted and extracted elements are constants, they must not
8692 // be the same value, extract from the pre-inserted value instead.
8693 if (isa<Constant>(IE->getOperand(2)) &&
8694 isa<Constant>(EI.getOperand(1))) {
8695 AddUsesToWorkList(EI);
8696 EI.setOperand(0, IE->getOperand(0));
8697 return &EI;
8698 }
8699 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8700 // If this is extracting an element from a shufflevector, figure out where
8701 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008702 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8703 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008704 Value *Src;
8705 if (SrcIdx < SVI->getType()->getNumElements())
8706 Src = SVI->getOperand(0);
8707 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8708 SrcIdx -= SVI->getType()->getNumElements();
8709 Src = SVI->getOperand(1);
8710 } else {
8711 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008712 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008713 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008714 }
8715 }
Chris Lattner83f65782006-05-25 22:53:38 +00008716 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008717 return 0;
8718}
8719
Chris Lattner90951862006-04-16 00:51:47 +00008720/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8721/// elements from either LHS or RHS, return the shuffle mask and true.
8722/// Otherwise, return false.
8723static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8724 std::vector<Constant*> &Mask) {
8725 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8726 "Invalid CollectSingleShuffleElements");
8727 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8728
8729 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008730 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00008731 return true;
8732 } else if (V == LHS) {
8733 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008734 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00008735 return true;
8736 } else if (V == RHS) {
8737 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008738 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008739 return true;
8740 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8741 // If this is an insert of an extract from some other vector, include it.
8742 Value *VecOp = IEI->getOperand(0);
8743 Value *ScalarOp = IEI->getOperand(1);
8744 Value *IdxOp = IEI->getOperand(2);
8745
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008746 if (!isa<ConstantInt>(IdxOp))
8747 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008748 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008749
8750 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8751 // Okay, we can handle this if the vector we are insertinting into is
8752 // transitively ok.
8753 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8754 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00008755 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008756 return true;
8757 }
8758 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8759 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008760 EI->getOperand(0)->getType() == V->getType()) {
8761 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008762 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008763
8764 // This must be extracting from either LHS or RHS.
8765 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8766 // Okay, we can handle this if the vector we are insertinting into is
8767 // transitively ok.
8768 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8769 // If so, update the mask to reflect the inserted value.
8770 if (EI->getOperand(0) == LHS) {
8771 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008772 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008773 } else {
8774 assert(EI->getOperand(0) == RHS);
8775 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008776 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008777
8778 }
8779 return true;
8780 }
8781 }
8782 }
8783 }
8784 }
8785 // TODO: Handle shufflevector here!
8786
8787 return false;
8788}
8789
8790/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8791/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8792/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008793static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008794 Value *&RHS) {
8795 assert(isa<PackedType>(V->getType()) &&
8796 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008797 "Invalid shuffle!");
8798 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8799
8800 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008801 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008802 return V;
8803 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008804 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008805 return V;
8806 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8807 // If this is an insert of an extract from some other vector, include it.
8808 Value *VecOp = IEI->getOperand(0);
8809 Value *ScalarOp = IEI->getOperand(1);
8810 Value *IdxOp = IEI->getOperand(2);
8811
8812 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8813 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8814 EI->getOperand(0)->getType() == V->getType()) {
8815 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008816 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8817 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008818
8819 // Either the extracted from or inserted into vector must be RHSVec,
8820 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008821 if (EI->getOperand(0) == RHS || RHS == 0) {
8822 RHS = EI->getOperand(0);
8823 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008824 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008825 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008826 return V;
8827 }
8828
Chris Lattner90951862006-04-16 00:51:47 +00008829 if (VecOp == RHS) {
8830 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008831 // Everything but the extracted element is replaced with the RHS.
8832 for (unsigned i = 0; i != NumElts; ++i) {
8833 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00008834 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008835 }
8836 return V;
8837 }
Chris Lattner90951862006-04-16 00:51:47 +00008838
8839 // If this insertelement is a chain that comes from exactly these two
8840 // vectors, return the vector and the effective shuffle.
8841 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8842 return EI->getOperand(0);
8843
Chris Lattner39fac442006-04-15 01:39:45 +00008844 }
8845 }
8846 }
Chris Lattner90951862006-04-16 00:51:47 +00008847 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008848
8849 // Otherwise, can't do anything fancy. Return an identity vector.
8850 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008851 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008852 return V;
8853}
8854
8855Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8856 Value *VecOp = IE.getOperand(0);
8857 Value *ScalarOp = IE.getOperand(1);
8858 Value *IdxOp = IE.getOperand(2);
8859
8860 // If the inserted element was extracted from some other vector, and if the
8861 // indexes are constant, try to turn this into a shufflevector operation.
8862 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8863 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8864 EI->getOperand(0)->getType() == IE.getType()) {
8865 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008866 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8867 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008868
8869 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8870 return ReplaceInstUsesWith(IE, VecOp);
8871
8872 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8873 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8874
8875 // If we are extracting a value from a vector, then inserting it right
8876 // back into the same place, just use the input vector.
8877 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8878 return ReplaceInstUsesWith(IE, VecOp);
8879
8880 // We could theoretically do this for ANY input. However, doing so could
8881 // turn chains of insertelement instructions into a chain of shufflevector
8882 // instructions, and right now we do not merge shufflevectors. As such,
8883 // only do this in a situation where it is clear that there is benefit.
8884 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8885 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8886 // the values of VecOp, except then one read from EIOp0.
8887 // Build a new shuffle mask.
8888 std::vector<Constant*> Mask;
8889 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00008890 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008891 else {
8892 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00008893 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00008894 NumVectorElts));
8895 }
Reid Spencerc635f472006-12-31 05:48:39 +00008896 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008897 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8898 ConstantPacked::get(Mask));
8899 }
8900
8901 // If this insertelement isn't used by some other insertelement, turn it
8902 // (and any insertelements it points to), into one big shuffle.
8903 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8904 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008905 Value *RHS = 0;
8906 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8907 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8908 // We now have a shuffle of LHS, RHS, Mask.
8909 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008910 }
8911 }
8912 }
8913
8914 return 0;
8915}
8916
8917
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008918Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8919 Value *LHS = SVI.getOperand(0);
8920 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008921 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008922
8923 bool MadeChange = false;
8924
Chris Lattner2deeaea2006-10-05 06:55:50 +00008925 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008926 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008927 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8928
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008929 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00008930 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008931 if (isa<UndefValue>(SVI.getOperand(1))) {
8932 // Scan to see if there are any references to the RHS. If so, replace them
8933 // with undef element refs and set MadeChange to true.
8934 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8935 if (Mask[i] >= e && Mask[i] != 2*e) {
8936 Mask[i] = 2*e;
8937 MadeChange = true;
8938 }
8939 }
8940
8941 if (MadeChange) {
8942 // Remap any references to RHS to use LHS.
8943 std::vector<Constant*> Elts;
8944 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8945 if (Mask[i] == 2*e)
8946 Elts.push_back(UndefValue::get(Type::Int32Ty));
8947 else
8948 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8949 }
8950 SVI.setOperand(2, ConstantPacked::get(Elts));
8951 }
8952 }
Chris Lattner39fac442006-04-15 01:39:45 +00008953
Chris Lattner12249be2006-05-25 23:48:38 +00008954 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8955 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8956 if (LHS == RHS || isa<UndefValue>(LHS)) {
8957 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008958 // shuffle(undef,undef,mask) -> undef.
8959 return ReplaceInstUsesWith(SVI, LHS);
8960 }
8961
Chris Lattner12249be2006-05-25 23:48:38 +00008962 // Remap any references to RHS to use LHS.
8963 std::vector<Constant*> Elts;
8964 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008965 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00008966 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00008967 else {
8968 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8969 (Mask[i] < e && isa<UndefValue>(LHS)))
8970 Mask[i] = 2*e; // Turn into undef.
8971 else
8972 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00008973 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008974 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008975 }
Chris Lattner12249be2006-05-25 23:48:38 +00008976 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008977 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008978 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008979 LHS = SVI.getOperand(0);
8980 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008981 MadeChange = true;
8982 }
8983
Chris Lattner0e477162006-05-26 00:29:06 +00008984 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008985 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008986
Chris Lattner12249be2006-05-25 23:48:38 +00008987 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8988 if (Mask[i] >= e*2) continue; // Ignore undef values.
8989 // Is this an identity shuffle of the LHS value?
8990 isLHSID &= (Mask[i] == i);
8991
8992 // Is this an identity shuffle of the RHS value?
8993 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008994 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008995
Chris Lattner12249be2006-05-25 23:48:38 +00008996 // Eliminate identity shuffles.
8997 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8998 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008999
Chris Lattner0e477162006-05-26 00:29:06 +00009000 // If the LHS is a shufflevector itself, see if we can combine it with this
9001 // one without producing an unusual shuffle. Here we are really conservative:
9002 // we are absolutely afraid of producing a shuffle mask not in the input
9003 // program, because the code gen may not be smart enough to turn a merged
9004 // shuffle into two specific shuffles: it may produce worse code. As such,
9005 // we only merge two shuffles if the result is one of the two input shuffle
9006 // masks. In this case, merging the shuffles just removes one instruction,
9007 // which we know is safe. This is good for things like turning:
9008 // (splat(splat)) -> splat.
9009 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9010 if (isa<UndefValue>(RHS)) {
9011 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9012
9013 std::vector<unsigned> NewMask;
9014 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9015 if (Mask[i] >= 2*e)
9016 NewMask.push_back(2*e);
9017 else
9018 NewMask.push_back(LHSMask[Mask[i]]);
9019
9020 // If the result mask is equal to the src shuffle or this shuffle mask, do
9021 // the replacement.
9022 if (NewMask == LHSMask || NewMask == Mask) {
9023 std::vector<Constant*> Elts;
9024 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9025 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00009026 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009027 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00009028 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009029 }
9030 }
9031 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9032 LHSSVI->getOperand(1),
9033 ConstantPacked::get(Elts));
9034 }
9035 }
9036 }
Chris Lattner4284f642007-01-30 22:32:46 +00009037
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009038 return MadeChange ? &SVI : 0;
9039}
9040
9041
Robert Bocchinoa8352962006-01-13 22:48:06 +00009042
Chris Lattner99f48c62002-09-02 04:59:56 +00009043void InstCombiner::removeFromWorkList(Instruction *I) {
9044 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
9045 WorkList.end());
9046}
9047
Chris Lattner39c98bb2004-12-08 23:43:58 +00009048
9049/// TryToSinkInstruction - Try to move the specified instruction from its
9050/// current block into the beginning of DestBlock, which can only happen if it's
9051/// safe to move the instruction past all of the instructions between it and the
9052/// end of its block.
9053static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9054 assert(I->hasOneUse() && "Invariants didn't hold!");
9055
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009056 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9057 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009058
Chris Lattner39c98bb2004-12-08 23:43:58 +00009059 // Do not sink alloca instructions out of the entry block.
9060 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9061 return false;
9062
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009063 // We can only sink load instructions if there is nothing between the load and
9064 // the end of block that could change the value.
9065 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009066 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9067 Scan != E; ++Scan)
9068 if (Scan->mayWriteToMemory())
9069 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009070 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009071
9072 BasicBlock::iterator InsertPos = DestBlock->begin();
9073 while (isa<PHINode>(InsertPos)) ++InsertPos;
9074
Chris Lattner9f269e42005-08-08 19:11:57 +00009075 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009076 ++NumSunkInst;
9077 return true;
9078}
9079
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009080
9081/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9082/// all reachable code to the worklist.
9083///
9084/// This has a couple of tricks to make the code faster and more powerful. In
9085/// particular, we constant fold and DCE instructions as we go, to avoid adding
9086/// them to the worklist (this significantly speeds up instcombine on code where
9087/// many instructions are dead or constant). Additionally, if we find a branch
9088/// whose condition is a known constant, we only visit the reachable successors.
9089///
9090static void AddReachableCodeToWorklist(BasicBlock *BB,
9091 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00009092 std::vector<Instruction*> &WorkList,
9093 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009094 // We have now visited this block! If we've already been here, bail out.
9095 if (!Visited.insert(BB).second) return;
9096
9097 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9098 Instruction *Inst = BBI++;
9099
9100 // DCE instruction if trivially dead.
9101 if (isInstructionTriviallyDead(Inst)) {
9102 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009103 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009104 Inst->eraseFromParent();
9105 continue;
9106 }
9107
9108 // ConstantProp instruction if trivially constant.
Chris Lattnere3eda252007-01-30 23:16:15 +00009109 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009110 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009111 Inst->replaceAllUsesWith(C);
9112 ++NumConstProp;
9113 Inst->eraseFromParent();
9114 continue;
9115 }
9116
9117 WorkList.push_back(Inst);
9118 }
9119
9120 // Recursively visit successors. If this is a branch or switch on a constant,
9121 // only visit the reachable successor.
9122 TerminatorInst *TI = BB->getTerminator();
9123 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00009124 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
Reid Spencercddc9df2007-01-12 04:24:46 +00009125 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00009126 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9127 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009128 return;
9129 }
9130 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9131 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9132 // See if this is an explicit destination.
9133 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9134 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009135 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009136 return;
9137 }
9138
9139 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00009140 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009141 return;
9142 }
9143 }
9144
9145 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00009146 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009147}
9148
Chris Lattner113f4f42002-06-25 16:13:24 +00009149bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00009150 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009151 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00009152
Chris Lattner4ed40f72005-07-07 20:40:38 +00009153 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009154 // Do a depth-first traversal of the function, populate the worklist with
9155 // the reachable instructions. Ignore blocks that are not reachable. Keep
9156 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00009157 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00009158 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009159
Chris Lattner4ed40f72005-07-07 20:40:38 +00009160 // Do a quick scan over the function. If we find any blocks that are
9161 // unreachable, remove any instructions inside of them. This prevents
9162 // the instcombine code from having to deal with some bad special cases.
9163 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9164 if (!Visited.count(BB)) {
9165 Instruction *Term = BB->getTerminator();
9166 while (Term != BB->begin()) { // Remove instrs bottom-up
9167 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009168
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009169 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009170 ++NumDeadInst;
9171
9172 if (!I->use_empty())
9173 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9174 I->eraseFromParent();
9175 }
9176 }
9177 }
Chris Lattnerca081252001-12-14 16:52:21 +00009178
9179 while (!WorkList.empty()) {
9180 Instruction *I = WorkList.back(); // Get an instruction from the worklist
9181 WorkList.pop_back();
9182
Chris Lattner1443bc52006-05-11 17:11:52 +00009183 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009184 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009185 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009186 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009187 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009188 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009189
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009190 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009191
9192 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009193 removeFromWorkList(I);
9194 continue;
9195 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009196
Chris Lattner1443bc52006-05-11 17:11:52 +00009197 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +00009198 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009199 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009200
Chris Lattner1443bc52006-05-11 17:11:52 +00009201 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009202 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009203 ReplaceInstUsesWith(*I, C);
9204
Chris Lattner99f48c62002-09-02 04:59:56 +00009205 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009206 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00009207 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009208 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009209 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009210
Chris Lattner39c98bb2004-12-08 23:43:58 +00009211 // See if we can trivially sink this instruction to a successor basic block.
9212 if (I->hasOneUse()) {
9213 BasicBlock *BB = I->getParent();
9214 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9215 if (UserParent != BB) {
9216 bool UserIsSuccessor = false;
9217 // See if the user is one of our successors.
9218 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9219 if (*SI == UserParent) {
9220 UserIsSuccessor = true;
9221 break;
9222 }
9223
9224 // If the user is one of our immediate successors, and if that successor
9225 // only has us as a predecessors (we'd have to split the critical edge
9226 // otherwise), we can keep going.
9227 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9228 next(pred_begin(UserParent)) == pred_end(UserParent))
9229 // Okay, the CFG is simple enough, try to sink this instruction.
9230 Changed |= TryToSinkInstruction(I, UserParent);
9231 }
9232 }
9233
Chris Lattnerca081252001-12-14 16:52:21 +00009234 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009235 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009236 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009237 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009238 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009239 DOUT << "IC: Old = " << *I
9240 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009241
Chris Lattner396dbfe2004-06-09 05:08:07 +00009242 // Everything uses the new instruction now.
9243 I->replaceAllUsesWith(Result);
9244
9245 // Push the new instruction and any users onto the worklist.
9246 WorkList.push_back(Result);
9247 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009248
9249 // Move the name to the new instruction first...
9250 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00009251 Result->setName(OldName);
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