blob: aec61ab07672d9d22a0ff055da638b10209d84c7 [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 Spencer266e42b2006-12-23 06:05:41 +0000148 Instruction *visitFCmpInst(FCmpInst &I);
149 Instruction *visitICmpInst(ICmpInst &I);
150 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000151
Reid Spencer266e42b2006-12-23 06:05:41 +0000152 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
153 ICmpInst::Predicate Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000154 Instruction *visitShiftInst(ShiftInst &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000155 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +0000156 ShiftInst &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000157 Instruction *commonCastTransforms(CastInst &CI);
158 Instruction *commonIntCastTransforms(CastInst &CI);
159 Instruction *visitTrunc(CastInst &CI);
160 Instruction *visitZExt(CastInst &CI);
161 Instruction *visitSExt(CastInst &CI);
162 Instruction *visitFPTrunc(CastInst &CI);
163 Instruction *visitFPExt(CastInst &CI);
164 Instruction *visitFPToUI(CastInst &CI);
165 Instruction *visitFPToSI(CastInst &CI);
166 Instruction *visitUIToFP(CastInst &CI);
167 Instruction *visitSIToFP(CastInst &CI);
168 Instruction *visitPtrToInt(CastInst &CI);
169 Instruction *visitIntToPtr(CastInst &CI);
170 Instruction *visitBitCast(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000171 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
172 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000173 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000174 Instruction *visitCallInst(CallInst &CI);
175 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000176 Instruction *visitPHINode(PHINode &PN);
177 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000178 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000179 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000180 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000181 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000182 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000183 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000184 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000185 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000186 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000187
188 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000189 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000190
Chris Lattner970c33a2003-06-19 17:00:31 +0000191 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000192 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000193 bool transformConstExprCastCall(CallSite CS);
194
Chris Lattner69193f92004-04-05 01:30:19 +0000195 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000196 // InsertNewInstBefore - insert an instruction New before instruction Old
197 // in the program. Add the new instruction to the worklist.
198 //
Chris Lattner623826c2004-09-28 21:48:02 +0000199 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000200 assert(New && New->getParent() == 0 &&
201 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000202 BasicBlock *BB = Old.getParent();
203 BB->getInstList().insert(&Old, New); // Insert inst
204 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000205 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000206 }
207
Chris Lattner7e794272004-09-24 15:21:34 +0000208 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
209 /// This also adds the cast to the worklist. Finally, this returns the
210 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000211 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
212 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000213 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000214
Chris Lattnere79d2492006-04-06 19:19:17 +0000215 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000216 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000217
Reid Spencer13bc5d72006-12-12 09:18:51 +0000218 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattner7e794272004-09-24 15:21:34 +0000219 WorkList.push_back(C);
220 return C;
221 }
222
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000223 // ReplaceInstUsesWith - This method is to be used when an instruction is
224 // found to be dead, replacable with another preexisting expression. Here
225 // we add all uses of I to the worklist, replace all uses of I with the new
226 // value, then return I, so that the inst combiner will know that I was
227 // modified.
228 //
229 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000230 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000231 if (&I != V) {
232 I.replaceAllUsesWith(V);
233 return &I;
234 } else {
235 // If we are replacing the instruction with itself, this must be in a
236 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000237 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000238 return &I;
239 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000240 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000241
Chris Lattner2590e512006-02-07 06:56:34 +0000242 // UpdateValueUsesWith - This method is to be used when an value is
243 // found to be replacable with another preexisting expression or was
244 // updated. Here we add all uses of I to the worklist, replace all uses of
245 // I with the new value (unless the instruction was just updated), then
246 // return true, so that the inst combiner will know that I was modified.
247 //
248 bool UpdateValueUsesWith(Value *Old, Value *New) {
249 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
250 if (Old != New)
251 Old->replaceAllUsesWith(New);
252 if (Instruction *I = dyn_cast<Instruction>(Old))
253 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000254 if (Instruction *I = dyn_cast<Instruction>(New))
255 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000256 return true;
257 }
258
Chris Lattner51ea1272004-02-28 05:22:00 +0000259 // EraseInstFromFunction - When dealing with an instruction that has side
260 // effects or produces a void value, we can't rely on DCE to delete the
261 // instruction. Instead, visit methods should return the value returned by
262 // this function.
263 Instruction *EraseInstFromFunction(Instruction &I) {
264 assert(I.use_empty() && "Cannot erase instruction that is used!");
265 AddUsesToWorkList(I);
266 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000267 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000268 return 0; // Don't do anything with FI
269 }
270
Chris Lattner3ac7c262003-08-13 20:16:26 +0000271 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000272 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
273 /// InsertBefore instruction. This is specialized a bit to avoid inserting
274 /// casts that are known to not do anything...
275 ///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000276 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
277 Value *V, const Type *DestTy,
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000278 Instruction *InsertBefore);
279
Reid Spencer266e42b2006-12-23 06:05:41 +0000280 /// SimplifyCommutative - This performs a few simplifications for
281 /// commutative operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000282 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000283
Reid Spencer266e42b2006-12-23 06:05:41 +0000284 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
285 /// most-complex to least-complex order.
286 bool SimplifyCompare(CmpInst &I);
287
Chris Lattner0157e7f2006-02-11 09:31:47 +0000288 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
289 uint64_t &KnownZero, uint64_t &KnownOne,
290 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000291
Chris Lattner2deeaea2006-10-05 06:55:50 +0000292 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
293 uint64_t &UndefElts, unsigned Depth = 0);
294
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000295 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
296 // PHI node as operand #0, see if we can fold the instruction into the PHI
297 // (which is only possible if all operands to the PHI are constants).
298 Instruction *FoldOpIntoPhi(Instruction &I);
299
Chris Lattner7515cab2004-11-14 19:13:23 +0000300 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
301 // operator and they all are only used by the PHI, PHI together their
302 // inputs, and do the operation once, to the result of the PHI.
303 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000304 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
305
306
Zhou Sheng75b871f2007-01-11 12:24:14 +0000307 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
308 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000309
Zhou Sheng75b871f2007-01-11 12:24:14 +0000310 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000311 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000312 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000313 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000314 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000315 Instruction *MatchBSwap(BinaryOperator &I);
316
Reid Spencer74a528b2006-12-13 18:21:21 +0000317 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000318 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000319
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000320 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000321}
322
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000323// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000324// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000325static unsigned getComplexity(Value *V) {
326 if (isa<Instruction>(V)) {
327 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000328 return 3;
329 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000330 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000331 if (isa<Argument>(V)) return 3;
332 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000333}
Chris Lattner260ab202002-04-18 17:39:14 +0000334
Chris Lattner7fb29e12003-03-11 00:12:48 +0000335// isOnlyUse - Return true if this instruction will be deleted if we stop using
336// it.
337static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000338 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000339}
340
Chris Lattnere79e8542004-02-23 06:38:22 +0000341// getPromotedType - Return the specified type promoted as it would be to pass
342// though a va_arg area...
343static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000344 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
345 if (ITy->getBitWidth() < 32)
346 return Type::Int32Ty;
347 } else if (Ty == Type::FloatTy)
348 return Type::DoubleTy;
349 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000350}
351
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000352/// getBitCastOperand - If the specified operand is a CastInst or a constant
353/// expression bitcast, return the operand value, otherwise return null.
354static Value *getBitCastOperand(Value *V) {
355 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000356 return I->getOperand(0);
357 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000358 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000359 return CE->getOperand(0);
360 return 0;
361}
362
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000363/// This function is a wrapper around CastInst::isEliminableCastPair. It
364/// simply extracts arguments and returns what that function returns.
365/// @Determine if it is valid to eliminate a Convert pair
366static Instruction::CastOps
367isEliminableCastPair(
368 const CastInst *CI, ///< The first cast instruction
369 unsigned opcode, ///< The opcode of the second cast instruction
370 const Type *DstTy, ///< The target type for the second cast instruction
371 TargetData *TD ///< The target data for pointer size
372) {
373
374 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
375 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000376
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000377 // Get the opcodes of the two Cast instructions
378 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
379 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000380
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000381 return Instruction::CastOps(
382 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
383 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000384}
385
386/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
387/// in any code being generated. It does not require codegen if V is simple
388/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000389static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
390 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000391 if (V->getType() == Ty || isa<Constant>(V)) return false;
392
Chris Lattner99155be2006-05-25 23:24:33 +0000393 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000394 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000395 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000396 return false;
397 return true;
398}
399
400/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
401/// InsertBefore instruction. This is specialized a bit to avoid inserting
402/// casts that are known to not do anything...
403///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000404Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
405 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000406 Instruction *InsertBefore) {
407 if (V->getType() == DestTy) return V;
408 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000409 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000410
Reid Spencer13bc5d72006-12-12 09:18:51 +0000411 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000412}
413
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000414// SimplifyCommutative - This performs a few simplifications for commutative
415// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000416//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000417// 1. Order operands such that they are listed from right (least complex) to
418// left (most complex). This puts constants before unary operators before
419// binary operators.
420//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000421// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
422// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000423//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000424bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000425 bool Changed = false;
426 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
427 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000428
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000429 if (!I.isAssociative()) return Changed;
430 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000431 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
432 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
433 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000434 Constant *Folded = ConstantExpr::get(I.getOpcode(),
435 cast<Constant>(I.getOperand(1)),
436 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000437 I.setOperand(0, Op->getOperand(0));
438 I.setOperand(1, Folded);
439 return true;
440 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
441 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
442 isOnlyUse(Op) && isOnlyUse(Op1)) {
443 Constant *C1 = cast<Constant>(Op->getOperand(1));
444 Constant *C2 = cast<Constant>(Op1->getOperand(1));
445
446 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000447 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000448 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
449 Op1->getOperand(0),
450 Op1->getName(), &I);
451 WorkList.push_back(New);
452 I.setOperand(0, New);
453 I.setOperand(1, Folded);
454 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000455 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000456 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000457 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000458}
Chris Lattnerca081252001-12-14 16:52:21 +0000459
Reid Spencer266e42b2006-12-23 06:05:41 +0000460/// SimplifyCompare - For a CmpInst this function just orders the operands
461/// so that theyare listed from right (least complex) to left (most complex).
462/// This puts constants before unary operators before binary operators.
463bool InstCombiner::SimplifyCompare(CmpInst &I) {
464 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
465 return false;
466 I.swapOperands();
467 // Compare instructions are not associative so there's nothing else we can do.
468 return true;
469}
470
Chris Lattnerbb74e222003-03-10 23:06:50 +0000471// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
472// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000473//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000474static inline Value *dyn_castNegVal(Value *V) {
475 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000476 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000477
Chris Lattner9ad0d552004-12-14 20:08:06 +0000478 // Constants can be considered to be negated values if they can be folded.
479 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
480 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000481 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000482}
483
Chris Lattnerbb74e222003-03-10 23:06:50 +0000484static inline Value *dyn_castNotVal(Value *V) {
485 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000486 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000487
488 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000489 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000490 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000491 return 0;
492}
493
Chris Lattner7fb29e12003-03-11 00:12:48 +0000494// dyn_castFoldableMul - If this value is a multiply that can be folded into
495// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000496// non-constant operand of the multiply, and set CST to point to the multiplier.
497// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000498//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000499static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000500 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000501 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000502 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000503 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000504 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000505 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000506 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000507 // The multiplier is really 1 << CST.
508 Constant *One = ConstantInt::get(V->getType(), 1);
509 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
510 return I->getOperand(0);
511 }
512 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000513 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000514}
Chris Lattner31ae8632002-08-14 17:51:49 +0000515
Chris Lattner0798af32005-01-13 20:14:25 +0000516/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
517/// expression, return it.
518static User *dyn_castGetElementPtr(Value *V) {
519 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
520 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
521 if (CE->getOpcode() == Instruction::GetElementPtr)
522 return cast<User>(V);
523 return false;
524}
525
Chris Lattner623826c2004-09-28 21:48:02 +0000526// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000527static ConstantInt *AddOne(ConstantInt *C) {
528 return cast<ConstantInt>(ConstantExpr::getAdd(C,
529 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000530}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000531static ConstantInt *SubOne(ConstantInt *C) {
532 return cast<ConstantInt>(ConstantExpr::getSub(C,
533 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000534}
535
Chris Lattner4534dd592006-02-09 07:38:58 +0000536/// ComputeMaskedBits - Determine which of the bits specified in Mask are
537/// known to be either zero or one and return them in the KnownZero/KnownOne
538/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
539/// processing.
540static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
541 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000542 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
543 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000544 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000545 // optimized based on the contradictory assumption that it is non-zero.
546 // Because instcombine aggressively folds operations with undef args anyway,
547 // this won't lose us code quality.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000548 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000549 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000550 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000551 KnownZero = ~KnownOne & Mask;
552 return;
553 }
554
555 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000556 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000557 return; // Limit search depth.
558
559 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000560 Instruction *I = dyn_cast<Instruction>(V);
561 if (!I) return;
562
Reid Spencera94d3942007-01-19 21:13:56 +0000563 Mask &= cast<IntegerType>(V->getType())->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +0000564
Chris Lattner0157e7f2006-02-11 09:31:47 +0000565 switch (I->getOpcode()) {
566 case Instruction::And:
567 // If either the LHS or the RHS are Zero, the result is zero.
568 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
569 Mask &= ~KnownZero;
570 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
571 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
572 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
573
574 // Output known-1 bits are only known if set in both the LHS & RHS.
575 KnownOne &= KnownOne2;
576 // Output known-0 are known to be clear if zero in either the LHS | RHS.
577 KnownZero |= KnownZero2;
578 return;
579 case Instruction::Or:
580 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
581 Mask &= ~KnownOne;
582 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
583 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
584 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
585
586 // Output known-0 bits are only known if clear in both the LHS & RHS.
587 KnownZero &= KnownZero2;
588 // Output known-1 are known to be set if set in either the LHS | RHS.
589 KnownOne |= KnownOne2;
590 return;
591 case Instruction::Xor: {
592 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
593 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
594 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
595 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
596
597 // Output known-0 bits are known if clear or set in both the LHS & RHS.
598 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
599 // Output known-1 are known to be set if set in only one of the LHS, RHS.
600 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
601 KnownZero = KnownZeroOut;
602 return;
603 }
604 case Instruction::Select:
605 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
606 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
607 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
608 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
609
610 // Only known if known in both the LHS and RHS.
611 KnownOne &= KnownOne2;
612 KnownZero &= KnownZero2;
613 return;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000614 case Instruction::FPTrunc:
615 case Instruction::FPExt:
616 case Instruction::FPToUI:
617 case Instruction::FPToSI:
618 case Instruction::SIToFP:
619 case Instruction::PtrToInt:
620 case Instruction::UIToFP:
621 case Instruction::IntToPtr:
622 return; // Can't work with floating point or pointers
623 case Instruction::Trunc:
624 // All these have integer operands
625 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
626 return;
627 case Instruction::BitCast: {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000628 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +0000629 if (SrcTy->isInteger()) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000630 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000631 return;
632 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000633 break;
634 }
635 case Instruction::ZExt: {
636 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +0000637 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
638 uint64_t NotIn = ~SrcTy->getBitMask();
639 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000640
Reid Spencera94d3942007-01-19 21:13:56 +0000641 Mask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000642 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
643 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
644 // The top bits are known to be zero.
645 KnownZero |= NewBits;
646 return;
647 }
648 case Instruction::SExt: {
649 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +0000650 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
651 uint64_t NotIn = ~SrcTy->getBitMask();
652 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000653
Reid Spencera94d3942007-01-19 21:13:56 +0000654 Mask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000655 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
656 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000657
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000658 // If the sign bit of the input is known set or clear, then we know the
659 // top bits of the result.
660 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
661 if (KnownZero & InSignBit) { // Input sign bit known zero
662 KnownZero |= NewBits;
663 KnownOne &= ~NewBits;
664 } else if (KnownOne & InSignBit) { // Input sign bit known set
665 KnownOne |= NewBits;
666 KnownZero &= ~NewBits;
667 } else { // Input sign bit unknown
668 KnownZero &= ~NewBits;
669 KnownOne &= ~NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000670 }
671 return;
672 }
673 case Instruction::Shl:
674 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000675 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
676 uint64_t ShiftAmt = SA->getZExtValue();
677 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000678 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
679 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000680 KnownZero <<= ShiftAmt;
681 KnownOne <<= ShiftAmt;
682 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000683 return;
684 }
685 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000686 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000687 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000688 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000689 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000690 uint64_t ShiftAmt = SA->getZExtValue();
691 uint64_t HighBits = (1ULL << ShiftAmt)-1;
692 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000693
Reid Spencerfdff9382006-11-08 06:47:33 +0000694 // Unsigned shift right.
695 Mask <<= ShiftAmt;
696 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
697 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
698 KnownZero >>= ShiftAmt;
699 KnownOne >>= ShiftAmt;
700 KnownZero |= HighBits; // high bits known zero.
701 return;
702 }
703 break;
704 case Instruction::AShr:
705 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
706 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
707 // Compute the new bits that are at the top now.
708 uint64_t ShiftAmt = SA->getZExtValue();
709 uint64_t HighBits = (1ULL << ShiftAmt)-1;
710 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
711
712 // Signed shift right.
713 Mask <<= ShiftAmt;
714 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
715 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
716 KnownZero >>= ShiftAmt;
717 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000718
Reid Spencerfdff9382006-11-08 06:47:33 +0000719 // Handle the sign bits.
720 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
721 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000722
Reid Spencerfdff9382006-11-08 06:47:33 +0000723 if (KnownZero & SignBit) { // New bits are known zero.
724 KnownZero |= HighBits;
725 } else if (KnownOne & SignBit) { // New bits are known one.
726 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000727 }
728 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000729 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000730 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000731 }
Chris Lattner92a68652006-02-07 08:05:22 +0000732}
733
734/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
735/// this predicate to simplify operations downstream. Mask is known to be zero
736/// for bits that V cannot have.
737static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000738 uint64_t KnownZero, KnownOne;
739 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
740 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
741 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000742}
743
Chris Lattner0157e7f2006-02-11 09:31:47 +0000744/// ShrinkDemandedConstant - Check to see if the specified operand of the
745/// specified instruction is a constant integer. If so, check to see if there
746/// are any bits set in the constant that are not demanded. If so, shrink the
747/// constant and return true.
748static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
749 uint64_t Demanded) {
750 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
751 if (!OpC) return false;
752
753 // If there are no bits set that aren't demanded, nothing to do.
754 if ((~Demanded & OpC->getZExtValue()) == 0)
755 return false;
756
757 // This is producing any bits that are not needed, shrink the RHS.
758 uint64_t Val = Demanded & OpC->getZExtValue();
Zhou Sheng75b871f2007-01-11 12:24:14 +0000759 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000760 return true;
761}
762
Chris Lattneree0f2802006-02-12 02:07:56 +0000763// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
764// set of known zero and one bits, compute the maximum and minimum values that
765// could have the specified known zero and known one bits, returning them in
766// min/max.
767static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
768 uint64_t KnownZero,
769 uint64_t KnownOne,
770 int64_t &Min, int64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +0000771 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +0000772 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
773
774 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
775
776 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
777 // bit if it is unknown.
778 Min = KnownOne;
779 Max = KnownOne|UnknownBits;
780
781 if (SignBit & UnknownBits) { // Sign bit is unknown
782 Min |= SignBit;
783 Max &= ~SignBit;
784 }
785
786 // Sign extend the min/max values.
787 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
788 Min = (Min << ShAmt) >> ShAmt;
789 Max = (Max << ShAmt) >> ShAmt;
790}
791
792// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
793// a set of known zero and one bits, compute the maximum and minimum values that
794// could have the specified known zero and known one bits, returning them in
795// min/max.
796static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
797 uint64_t KnownZero,
798 uint64_t KnownOne,
799 uint64_t &Min,
800 uint64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +0000801 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +0000802 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
803
804 // The minimum value is when the unknown bits are all zeros.
805 Min = KnownOne;
806 // The maximum value is when the unknown bits are all ones.
807 Max = KnownOne|UnknownBits;
808}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000809
810
811/// SimplifyDemandedBits - Look at V. At this point, we know that only the
812/// DemandedMask bits of the result of V are ever used downstream. If we can
813/// use this information to simplify V, do so and return true. Otherwise,
814/// analyze the expression and return a mask of KnownOne and KnownZero bits for
815/// the expression (used to simplify the caller). The KnownZero/One bits may
816/// only be accurate for those bits in the DemandedMask.
817bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
818 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000819 unsigned Depth) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000820 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000821 // We know all of the bits for a constant!
822 KnownOne = CI->getZExtValue() & DemandedMask;
823 KnownZero = ~KnownOne & DemandedMask;
824 return false;
825 }
826
827 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000828 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000829 if (Depth != 0) { // Not at the root.
830 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
831 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000832 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000833 }
Chris Lattner2590e512006-02-07 06:56:34 +0000834 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000835 // just set the DemandedMask to all bits.
Reid Spencera94d3942007-01-19 21:13:56 +0000836 DemandedMask = cast<IntegerType>(V->getType())->getBitMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000837 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000838 if (V != UndefValue::get(V->getType()))
839 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
840 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000841 } else if (Depth == 6) { // Limit search depth.
842 return false;
843 }
844
845 Instruction *I = dyn_cast<Instruction>(V);
846 if (!I) return false; // Only analyze instructions.
847
Reid Spencera94d3942007-01-19 21:13:56 +0000848 DemandedMask &= cast<IntegerType>(V->getType())->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +0000849
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000850 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000851 switch (I->getOpcode()) {
852 default: break;
853 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000854 // If either the LHS or the RHS are Zero, the result is zero.
855 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
856 KnownZero, KnownOne, Depth+1))
857 return true;
858 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
859
860 // If something is known zero on the RHS, the bits aren't demanded on the
861 // LHS.
862 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
863 KnownZero2, KnownOne2, Depth+1))
864 return true;
865 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
866
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000867 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000868 // These bits cannot contribute to the result of the 'and'.
869 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
870 return UpdateValueUsesWith(I, I->getOperand(0));
871 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
872 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000873
874 // If all of the demanded bits in the inputs are known zeros, return zero.
875 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
876 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
877
Chris Lattner0157e7f2006-02-11 09:31:47 +0000878 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000879 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000880 return UpdateValueUsesWith(I, I);
881
882 // Output known-1 bits are only known if set in both the LHS & RHS.
883 KnownOne &= KnownOne2;
884 // Output known-0 are known to be clear if zero in either the LHS | RHS.
885 KnownZero |= KnownZero2;
886 break;
887 case Instruction::Or:
888 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
889 KnownZero, KnownOne, Depth+1))
890 return true;
891 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
892 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
893 KnownZero2, KnownOne2, Depth+1))
894 return true;
895 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
896
897 // If all of the demanded bits are known zero on one side, return the other.
898 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000899 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000900 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000901 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000902 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000903
904 // If all of the potentially set bits on one side are known to be set on
905 // the other side, just use the 'other' side.
906 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
907 (DemandedMask & (~KnownZero)))
908 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000909 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
910 (DemandedMask & (~KnownZero2)))
911 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000912
913 // If the RHS is a constant, see if we can simplify it.
914 if (ShrinkDemandedConstant(I, 1, DemandedMask))
915 return UpdateValueUsesWith(I, I);
916
917 // Output known-0 bits are only known if clear in both the LHS & RHS.
918 KnownZero &= KnownZero2;
919 // Output known-1 are known to be set if set in either the LHS | RHS.
920 KnownOne |= KnownOne2;
921 break;
922 case Instruction::Xor: {
923 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
924 KnownZero, KnownOne, Depth+1))
925 return true;
926 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
927 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
928 KnownZero2, KnownOne2, Depth+1))
929 return true;
930 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
931
932 // If all of the demanded bits are known zero on one side, return the other.
933 // These bits cannot contribute to the result of the 'xor'.
934 if ((DemandedMask & KnownZero) == DemandedMask)
935 return UpdateValueUsesWith(I, I->getOperand(0));
936 if ((DemandedMask & KnownZero2) == DemandedMask)
937 return UpdateValueUsesWith(I, I->getOperand(1));
938
939 // Output known-0 bits are known if clear or set in both the LHS & RHS.
940 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
941 // Output known-1 are known to be set if set in only one of the LHS, RHS.
942 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
943
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000944 // If all of the demanded bits are known to be zero on one side or the
945 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000946 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000947 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
948 Instruction *Or =
949 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
950 I->getName());
951 InsertNewInstBefore(Or, *I);
952 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000953 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000954
Chris Lattner5b2edb12006-02-12 08:02:11 +0000955 // If all of the demanded bits on one side are known, and all of the set
956 // bits on that side are also known to be set on the other side, turn this
957 // into an AND, as we know the bits will be cleared.
958 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
959 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
960 if ((KnownOne & KnownOne2) == KnownOne) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000961 Constant *AndC = ConstantInt::get(I->getType(),
962 ~KnownOne & DemandedMask);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000963 Instruction *And =
964 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
965 InsertNewInstBefore(And, *I);
966 return UpdateValueUsesWith(I, And);
967 }
968 }
969
Chris Lattner0157e7f2006-02-11 09:31:47 +0000970 // If the RHS is a constant, see if we can simplify it.
971 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
972 if (ShrinkDemandedConstant(I, 1, DemandedMask))
973 return UpdateValueUsesWith(I, I);
974
975 KnownZero = KnownZeroOut;
976 KnownOne = KnownOneOut;
977 break;
978 }
979 case Instruction::Select:
980 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
981 KnownZero, KnownOne, Depth+1))
982 return true;
983 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
984 KnownZero2, KnownOne2, Depth+1))
985 return true;
986 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
987 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
988
989 // If the operands are constants, see if we can simplify them.
990 if (ShrinkDemandedConstant(I, 1, DemandedMask))
991 return UpdateValueUsesWith(I, I);
992 if (ShrinkDemandedConstant(I, 2, DemandedMask))
993 return UpdateValueUsesWith(I, I);
994
995 // Only known if known in both the LHS and RHS.
996 KnownOne &= KnownOne2;
997 KnownZero &= KnownZero2;
998 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000999 case Instruction::Trunc:
1000 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1001 KnownZero, KnownOne, Depth+1))
1002 return true;
1003 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1004 break;
1005 case Instruction::BitCast:
Chris Lattner03c49532007-01-15 02:27:26 +00001006 if (!I->getOperand(0)->getType()->isInteger())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001007 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001008
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001009 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1010 KnownZero, KnownOne, Depth+1))
1011 return true;
1012 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1013 break;
1014 case Instruction::ZExt: {
1015 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001016 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1017 uint64_t NotIn = ~SrcTy->getBitMask();
1018 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001019
Reid Spencera94d3942007-01-19 21:13:56 +00001020 DemandedMask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001021 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1022 KnownZero, KnownOne, Depth+1))
1023 return true;
1024 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1025 // The top bits are known to be zero.
1026 KnownZero |= NewBits;
1027 break;
1028 }
1029 case Instruction::SExt: {
1030 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001031 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1032 uint64_t NotIn = ~SrcTy->getBitMask();
1033 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001034
1035 // Get the sign bit for the source type
1036 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
Reid Spencera94d3942007-01-19 21:13:56 +00001037 int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
Chris Lattner7d852282006-02-13 22:41:07 +00001038
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001039 // If any of the sign extended bits are demanded, we know that the sign
1040 // bit is demanded.
1041 if (NewBits & DemandedMask)
1042 InputDemandedBits |= InSignBit;
Chris Lattner7d852282006-02-13 22:41:07 +00001043
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001044 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1045 KnownZero, KnownOne, Depth+1))
1046 return true;
1047 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0157e7f2006-02-11 09:31:47 +00001048
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001049 // If the sign bit of the input is known set or clear, then we know the
1050 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001051
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001052 // If the input sign bit is known zero, or if the NewBits are not demanded
1053 // convert this into a zero extension.
1054 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1055 // Convert to ZExt cast
1056 CastInst *NewCast = CastInst::create(
1057 Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1058 return UpdateValueUsesWith(I, NewCast);
1059 } else if (KnownOne & InSignBit) { // Input sign bit known set
1060 KnownOne |= NewBits;
1061 KnownZero &= ~NewBits;
1062 } else { // Input sign bit unknown
1063 KnownZero &= ~NewBits;
1064 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001065 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001066 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001067 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001068 case Instruction::Add:
1069 // If there is a constant on the RHS, there are a variety of xformations
1070 // we can do.
1071 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1072 // If null, this should be simplified elsewhere. Some of the xforms here
1073 // won't work if the RHS is zero.
1074 if (RHS->isNullValue())
1075 break;
1076
1077 // Figure out what the input bits are. If the top bits of the and result
1078 // are not demanded, then the add doesn't demand them from its input
1079 // either.
1080
1081 // Shift the demanded mask up so that it's at the top of the uint64_t.
1082 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1083 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1084
1085 // If the top bit of the output is demanded, demand everything from the
1086 // input. Otherwise, we demand all the input bits except NLZ top bits.
Jeff Cohen223004c2007-01-08 20:17:17 +00001087 uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001088
1089 // Find information about known zero/one bits in the input.
1090 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1091 KnownZero2, KnownOne2, Depth+1))
1092 return true;
1093
1094 // If the RHS of the add has bits set that can't affect the input, reduce
1095 // the constant.
1096 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1097 return UpdateValueUsesWith(I, I);
1098
1099 // Avoid excess work.
1100 if (KnownZero2 == 0 && KnownOne2 == 0)
1101 break;
1102
1103 // Turn it into OR if input bits are zero.
1104 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1105 Instruction *Or =
1106 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1107 I->getName());
1108 InsertNewInstBefore(Or, *I);
1109 return UpdateValueUsesWith(I, Or);
1110 }
1111
1112 // We can say something about the output known-zero and known-one bits,
1113 // depending on potential carries from the input constant and the
1114 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1115 // bits set and the RHS constant is 0x01001, then we know we have a known
1116 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1117
1118 // To compute this, we first compute the potential carry bits. These are
1119 // the bits which may be modified. I'm not aware of a better way to do
1120 // this scan.
1121 uint64_t RHSVal = RHS->getZExtValue();
1122
1123 bool CarryIn = false;
1124 uint64_t CarryBits = 0;
1125 uint64_t CurBit = 1;
1126 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1127 // Record the current carry in.
1128 if (CarryIn) CarryBits |= CurBit;
1129
1130 bool CarryOut;
1131
1132 // This bit has a carry out unless it is "zero + zero" or
1133 // "zero + anything" with no carry in.
1134 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1135 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1136 } else if (!CarryIn &&
1137 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1138 CarryOut = false; // 0 + anything has no carry out if no carry in.
1139 } else {
1140 // Otherwise, we have to assume we have a carry out.
1141 CarryOut = true;
1142 }
1143
1144 // This stage's carry out becomes the next stage's carry-in.
1145 CarryIn = CarryOut;
1146 }
1147
1148 // Now that we know which bits have carries, compute the known-1/0 sets.
1149
1150 // Bits are known one if they are known zero in one operand and one in the
1151 // other, and there is no input carry.
1152 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1153
1154 // Bits are known zero if they are known zero in both operands and there
1155 // is no input carry.
1156 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1157 }
1158 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001159 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001160 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1161 uint64_t ShiftAmt = SA->getZExtValue();
1162 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001163 KnownZero, KnownOne, Depth+1))
1164 return true;
1165 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001166 KnownZero <<= ShiftAmt;
1167 KnownOne <<= ShiftAmt;
1168 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001169 }
Chris Lattner2590e512006-02-07 06:56:34 +00001170 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001171 case Instruction::LShr:
1172 // For a logical shift right
1173 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1174 unsigned ShiftAmt = SA->getZExtValue();
1175
1176 // Compute the new bits that are at the top now.
1177 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1178 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Reid Spencera94d3942007-01-19 21:13:56 +00001179 uint64_t TypeMask = cast<IntegerType>(I->getType())->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001180 // Unsigned shift right.
1181 if (SimplifyDemandedBits(I->getOperand(0),
1182 (DemandedMask << ShiftAmt) & TypeMask,
1183 KnownZero, KnownOne, Depth+1))
1184 return true;
1185 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1186 KnownZero &= TypeMask;
1187 KnownOne &= TypeMask;
1188 KnownZero >>= ShiftAmt;
1189 KnownOne >>= ShiftAmt;
1190 KnownZero |= HighBits; // high bits known zero.
1191 }
1192 break;
1193 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001194 // If this is an arithmetic shift right and only the low-bit is set, we can
1195 // always convert this into a logical shr, even if the shift amount is
1196 // variable. The low bit of the shift cannot be an input sign bit unless
1197 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001198 if (DemandedMask == 1) {
1199 // Perform the logical shift right.
1200 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1201 I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001202 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001203 return UpdateValueUsesWith(I, NewVal);
1204 }
1205
Reid Spencere0fc4df2006-10-20 07:07:24 +00001206 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1207 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001208
1209 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001210 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1211 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Reid Spencera94d3942007-01-19 21:13:56 +00001212 uint64_t TypeMask = cast<IntegerType>(I->getType())->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001213 // Signed shift right.
1214 if (SimplifyDemandedBits(I->getOperand(0),
1215 (DemandedMask << ShiftAmt) & TypeMask,
1216 KnownZero, KnownOne, Depth+1))
1217 return true;
1218 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1219 KnownZero &= TypeMask;
1220 KnownOne &= TypeMask;
1221 KnownZero >>= ShiftAmt;
1222 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001223
Reid Spencerfdff9382006-11-08 06:47:33 +00001224 // Handle the sign bits.
1225 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1226 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001227
Reid Spencerfdff9382006-11-08 06:47:33 +00001228 // If the input sign bit is known to be zero, or if none of the top bits
1229 // are demanded, turn this into an unsigned shift right.
1230 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1231 // Perform the logical shift right.
1232 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1233 SA, I->getName());
1234 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1235 return UpdateValueUsesWith(I, NewVal);
1236 } else if (KnownOne & SignBit) { // New bits are known one.
1237 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001238 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001239 }
Chris Lattner2590e512006-02-07 06:56:34 +00001240 break;
1241 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001242
1243 // If the client is only demanding bits that we know, return the known
1244 // constant.
1245 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001246 return UpdateValueUsesWith(I, ConstantInt::get(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001247 return false;
1248}
1249
Chris Lattner2deeaea2006-10-05 06:55:50 +00001250
1251/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1252/// 64 or fewer elements. DemandedElts contains the set of elements that are
1253/// actually used by the caller. This method analyzes which elements of the
1254/// operand are undef and returns that information in UndefElts.
1255///
1256/// If the information about demanded elements can be used to simplify the
1257/// operation, the operation is simplified, then the resultant value is
1258/// returned. This returns null if no change was made.
1259Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1260 uint64_t &UndefElts,
1261 unsigned Depth) {
1262 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1263 assert(VWidth <= 64 && "Vector too wide to analyze!");
1264 uint64_t EltMask = ~0ULL >> (64-VWidth);
1265 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1266 "Invalid DemandedElts!");
1267
1268 if (isa<UndefValue>(V)) {
1269 // If the entire vector is undefined, just return this info.
1270 UndefElts = EltMask;
1271 return 0;
1272 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1273 UndefElts = EltMask;
1274 return UndefValue::get(V->getType());
1275 }
1276
1277 UndefElts = 0;
1278 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1279 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1280 Constant *Undef = UndefValue::get(EltTy);
1281
1282 std::vector<Constant*> Elts;
1283 for (unsigned i = 0; i != VWidth; ++i)
1284 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1285 Elts.push_back(Undef);
1286 UndefElts |= (1ULL << i);
1287 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1288 Elts.push_back(Undef);
1289 UndefElts |= (1ULL << i);
1290 } else { // Otherwise, defined.
1291 Elts.push_back(CP->getOperand(i));
1292 }
1293
1294 // If we changed the constant, return it.
1295 Constant *NewCP = ConstantPacked::get(Elts);
1296 return NewCP != CP ? NewCP : 0;
1297 } else if (isa<ConstantAggregateZero>(V)) {
1298 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1299 // set to undef.
1300 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1301 Constant *Zero = Constant::getNullValue(EltTy);
1302 Constant *Undef = UndefValue::get(EltTy);
1303 std::vector<Constant*> Elts;
1304 for (unsigned i = 0; i != VWidth; ++i)
1305 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1306 UndefElts = DemandedElts ^ EltMask;
1307 return ConstantPacked::get(Elts);
1308 }
1309
1310 if (!V->hasOneUse()) { // Other users may use these bits.
1311 if (Depth != 0) { // Not at the root.
1312 // TODO: Just compute the UndefElts information recursively.
1313 return false;
1314 }
1315 return false;
1316 } else if (Depth == 10) { // Limit search depth.
1317 return false;
1318 }
1319
1320 Instruction *I = dyn_cast<Instruction>(V);
1321 if (!I) return false; // Only analyze instructions.
1322
1323 bool MadeChange = false;
1324 uint64_t UndefElts2;
1325 Value *TmpV;
1326 switch (I->getOpcode()) {
1327 default: break;
1328
1329 case Instruction::InsertElement: {
1330 // If this is a variable index, we don't know which element it overwrites.
1331 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001332 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001333 if (Idx == 0) {
1334 // Note that we can't propagate undef elt info, because we don't know
1335 // which elt is getting updated.
1336 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1337 UndefElts2, Depth+1);
1338 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1339 break;
1340 }
1341
1342 // If this is inserting an element that isn't demanded, remove this
1343 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001344 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001345 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1346 return AddSoonDeadInstToWorklist(*I, 0);
1347
1348 // Otherwise, the element inserted overwrites whatever was there, so the
1349 // input demanded set is simpler than the output set.
1350 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1351 DemandedElts & ~(1ULL << IdxNo),
1352 UndefElts, Depth+1);
1353 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1354
1355 // The inserted element is defined.
1356 UndefElts |= 1ULL << IdxNo;
1357 break;
1358 }
1359
1360 case Instruction::And:
1361 case Instruction::Or:
1362 case Instruction::Xor:
1363 case Instruction::Add:
1364 case Instruction::Sub:
1365 case Instruction::Mul:
1366 // div/rem demand all inputs, because they don't want divide by zero.
1367 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1368 UndefElts, Depth+1);
1369 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1370 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1371 UndefElts2, Depth+1);
1372 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1373
1374 // Output elements are undefined if both are undefined. Consider things
1375 // like undef&0. The result is known zero, not undef.
1376 UndefElts &= UndefElts2;
1377 break;
1378
1379 case Instruction::Call: {
1380 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1381 if (!II) break;
1382 switch (II->getIntrinsicID()) {
1383 default: break;
1384
1385 // Binary vector operations that work column-wise. A dest element is a
1386 // function of the corresponding input elements from the two inputs.
1387 case Intrinsic::x86_sse_sub_ss:
1388 case Intrinsic::x86_sse_mul_ss:
1389 case Intrinsic::x86_sse_min_ss:
1390 case Intrinsic::x86_sse_max_ss:
1391 case Intrinsic::x86_sse2_sub_sd:
1392 case Intrinsic::x86_sse2_mul_sd:
1393 case Intrinsic::x86_sse2_min_sd:
1394 case Intrinsic::x86_sse2_max_sd:
1395 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1396 UndefElts, Depth+1);
1397 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1398 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1399 UndefElts2, Depth+1);
1400 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1401
1402 // If only the low elt is demanded and this is a scalarizable intrinsic,
1403 // scalarize it now.
1404 if (DemandedElts == 1) {
1405 switch (II->getIntrinsicID()) {
1406 default: break;
1407 case Intrinsic::x86_sse_sub_ss:
1408 case Intrinsic::x86_sse_mul_ss:
1409 case Intrinsic::x86_sse2_sub_sd:
1410 case Intrinsic::x86_sse2_mul_sd:
1411 // TODO: Lower MIN/MAX/ABS/etc
1412 Value *LHS = II->getOperand(1);
1413 Value *RHS = II->getOperand(2);
1414 // Extract the element as scalars.
1415 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1416 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1417
1418 switch (II->getIntrinsicID()) {
1419 default: assert(0 && "Case stmts out of sync!");
1420 case Intrinsic::x86_sse_sub_ss:
1421 case Intrinsic::x86_sse2_sub_sd:
1422 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1423 II->getName()), *II);
1424 break;
1425 case Intrinsic::x86_sse_mul_ss:
1426 case Intrinsic::x86_sse2_mul_sd:
1427 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1428 II->getName()), *II);
1429 break;
1430 }
1431
1432 Instruction *New =
1433 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1434 II->getName());
1435 InsertNewInstBefore(New, *II);
1436 AddSoonDeadInstToWorklist(*II, 0);
1437 return New;
1438 }
1439 }
1440
1441 // Output elements are undefined if both are undefined. Consider things
1442 // like undef&0. The result is known zero, not undef.
1443 UndefElts &= UndefElts2;
1444 break;
1445 }
1446 break;
1447 }
1448 }
1449 return MadeChange ? I : 0;
1450}
1451
Reid Spencer266e42b2006-12-23 06:05:41 +00001452/// @returns true if the specified compare instruction is
1453/// true when both operands are equal...
1454/// @brief Determine if the ICmpInst returns true if both operands are equal
1455static bool isTrueWhenEqual(ICmpInst &ICI) {
1456 ICmpInst::Predicate pred = ICI.getPredicate();
1457 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1458 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1459 pred == ICmpInst::ICMP_SLE;
1460}
1461
Chris Lattnerb8b97502003-08-13 19:01:45 +00001462/// AssociativeOpt - Perform an optimization on an associative operator. This
1463/// function is designed to check a chain of associative operators for a
1464/// potential to apply a certain optimization. Since the optimization may be
1465/// applicable if the expression was reassociated, this checks the chain, then
1466/// reassociates the expression as necessary to expose the optimization
1467/// opportunity. This makes use of a special Functor, which must define
1468/// 'shouldApply' and 'apply' methods.
1469///
1470template<typename Functor>
1471Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1472 unsigned Opcode = Root.getOpcode();
1473 Value *LHS = Root.getOperand(0);
1474
1475 // Quick check, see if the immediate LHS matches...
1476 if (F.shouldApply(LHS))
1477 return F.apply(Root);
1478
1479 // Otherwise, if the LHS is not of the same opcode as the root, return.
1480 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001481 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001482 // Should we apply this transform to the RHS?
1483 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1484
1485 // If not to the RHS, check to see if we should apply to the LHS...
1486 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1487 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1488 ShouldApply = true;
1489 }
1490
1491 // If the functor wants to apply the optimization to the RHS of LHSI,
1492 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1493 if (ShouldApply) {
1494 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001495
Chris Lattnerb8b97502003-08-13 19:01:45 +00001496 // Now all of the instructions are in the current basic block, go ahead
1497 // and perform the reassociation.
1498 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1499
1500 // First move the selected RHS to the LHS of the root...
1501 Root.setOperand(0, LHSI->getOperand(1));
1502
1503 // Make what used to be the LHS of the root be the user of the root...
1504 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001505 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001506 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1507 return 0;
1508 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001509 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001510 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001511 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1512 BasicBlock::iterator ARI = &Root; ++ARI;
1513 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1514 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001515
1516 // Now propagate the ExtraOperand down the chain of instructions until we
1517 // get to LHSI.
1518 while (TmpLHSI != LHSI) {
1519 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001520 // Move the instruction to immediately before the chain we are
1521 // constructing to avoid breaking dominance properties.
1522 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1523 BB->getInstList().insert(ARI, NextLHSI);
1524 ARI = NextLHSI;
1525
Chris Lattnerb8b97502003-08-13 19:01:45 +00001526 Value *NextOp = NextLHSI->getOperand(1);
1527 NextLHSI->setOperand(1, ExtraOperand);
1528 TmpLHSI = NextLHSI;
1529 ExtraOperand = NextOp;
1530 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001531
Chris Lattnerb8b97502003-08-13 19:01:45 +00001532 // Now that the instructions are reassociated, have the functor perform
1533 // the transformation...
1534 return F.apply(Root);
1535 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001536
Chris Lattnerb8b97502003-08-13 19:01:45 +00001537 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1538 }
1539 return 0;
1540}
1541
1542
1543// AddRHS - Implements: X + X --> X << 1
1544struct AddRHS {
1545 Value *RHS;
1546 AddRHS(Value *rhs) : RHS(rhs) {}
1547 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1548 Instruction *apply(BinaryOperator &Add) const {
1549 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001550 ConstantInt::get(Type::Int8Ty, 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001551 }
1552};
1553
1554// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1555// iff C1&C2 == 0
1556struct AddMaskingAnd {
1557 Constant *C2;
1558 AddMaskingAnd(Constant *c) : C2(c) {}
1559 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001560 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001561 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001562 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001563 }
1564 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001565 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001566 }
1567};
1568
Chris Lattner86102b82005-01-01 16:22:27 +00001569static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001570 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001571 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001572 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001573 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001574
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001575 return IC->InsertNewInstBefore(CastInst::create(
1576 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001577 }
1578
Chris Lattner183b3362004-04-09 19:05:30 +00001579 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001580 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1581 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001582
Chris Lattner183b3362004-04-09 19:05:30 +00001583 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1584 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001585 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1586 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001587 }
1588
1589 Value *Op0 = SO, *Op1 = ConstOperand;
1590 if (!ConstIsRHS)
1591 std::swap(Op0, Op1);
1592 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001593 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1594 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001595 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1596 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1597 SO->getName()+".cmp");
Chris Lattner86102b82005-01-01 16:22:27 +00001598 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1599 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001600 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001601 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001602 abort();
1603 }
Chris Lattner86102b82005-01-01 16:22:27 +00001604 return IC->InsertNewInstBefore(New, I);
1605}
1606
1607// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1608// constant as the other operand, try to fold the binary operator into the
1609// select arguments. This also works for Cast instructions, which obviously do
1610// not have a second operand.
1611static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1612 InstCombiner *IC) {
1613 // Don't modify shared select instructions
1614 if (!SI->hasOneUse()) return 0;
1615 Value *TV = SI->getOperand(1);
1616 Value *FV = SI->getOperand(2);
1617
1618 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001619 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001620 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001621
Chris Lattner86102b82005-01-01 16:22:27 +00001622 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1623 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1624
1625 return new SelectInst(SI->getCondition(), SelectTrueVal,
1626 SelectFalseVal);
1627 }
1628 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001629}
1630
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001631
1632/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1633/// node as operand #0, see if we can fold the instruction into the PHI (which
1634/// is only possible if all operands to the PHI are constants).
1635Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1636 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001637 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001638 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001639
Chris Lattner04689872006-09-09 22:02:56 +00001640 // Check to see if all of the operands of the PHI are constants. If there is
1641 // one non-constant value, remember the BB it is. If there is more than one
1642 // bail out.
1643 BasicBlock *NonConstBB = 0;
1644 for (unsigned i = 0; i != NumPHIValues; ++i)
1645 if (!isa<Constant>(PN->getIncomingValue(i))) {
1646 if (NonConstBB) return 0; // More than one non-const value.
1647 NonConstBB = PN->getIncomingBlock(i);
1648
1649 // If the incoming non-constant value is in I's block, we have an infinite
1650 // loop.
1651 if (NonConstBB == I.getParent())
1652 return 0;
1653 }
1654
1655 // If there is exactly one non-constant value, we can insert a copy of the
1656 // operation in that block. However, if this is a critical edge, we would be
1657 // inserting the computation one some other paths (e.g. inside a loop). Only
1658 // do this if the pred block is unconditionally branching into the phi block.
1659 if (NonConstBB) {
1660 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1661 if (!BI || !BI->isUnconditional()) return 0;
1662 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001663
1664 // Okay, we can do the transformation: create the new PHI node.
1665 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1666 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001667 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001668 InsertNewInstBefore(NewPN, *PN);
1669
1670 // Next, add all of the operands to the PHI.
1671 if (I.getNumOperands() == 2) {
1672 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001673 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001674 Value *InV;
1675 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001676 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1677 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1678 else
1679 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001680 } else {
1681 assert(PN->getIncomingBlock(i) == NonConstBB);
1682 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1683 InV = BinaryOperator::create(BO->getOpcode(),
1684 PN->getIncomingValue(i), C, "phitmp",
1685 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001686 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1687 InV = CmpInst::create(CI->getOpcode(),
1688 CI->getPredicate(),
1689 PN->getIncomingValue(i), C, "phitmp",
1690 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001691 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1692 InV = new ShiftInst(SI->getOpcode(),
1693 PN->getIncomingValue(i), C, "phitmp",
1694 NonConstBB->getTerminator());
1695 else
1696 assert(0 && "Unknown binop!");
1697
1698 WorkList.push_back(cast<Instruction>(InV));
1699 }
1700 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001701 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001702 } else {
1703 CastInst *CI = cast<CastInst>(&I);
1704 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001705 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001706 Value *InV;
1707 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001708 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001709 } else {
1710 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001711 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1712 I.getType(), "phitmp",
1713 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001714 WorkList.push_back(cast<Instruction>(InV));
1715 }
1716 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001717 }
1718 }
1719 return ReplaceInstUsesWith(I, NewPN);
1720}
1721
Chris Lattner113f4f42002-06-25 16:13:24 +00001722Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001723 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001724 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001725
Chris Lattnercf4a9962004-04-10 22:01:55 +00001726 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001727 // X + undef -> undef
1728 if (isa<UndefValue>(RHS))
1729 return ReplaceInstUsesWith(I, RHS);
1730
Chris Lattnercf4a9962004-04-10 22:01:55 +00001731 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001732 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001733 if (RHSC->isNullValue())
1734 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001735 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1736 if (CFP->isExactlyValue(-0.0))
1737 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001738 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001739
Chris Lattnercf4a9962004-04-10 22:01:55 +00001740 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001741 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00001742 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001743 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001744 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001745
1746 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1747 // (X & 254)+1 -> (X&254)|1
1748 uint64_t KnownZero, KnownOne;
1749 if (!isa<PackedType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00001750 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001751 KnownZero, KnownOne))
1752 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00001753 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001754
1755 if (isa<PHINode>(LHS))
1756 if (Instruction *NV = FoldOpIntoPhi(I))
1757 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001758
Chris Lattner330628a2006-01-06 17:59:59 +00001759 ConstantInt *XorRHS = 0;
1760 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00001761 if (isa<ConstantInt>(RHSC) &&
1762 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001763 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1764 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1765 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1766
1767 uint64_t C0080Val = 1ULL << 31;
1768 int64_t CFF80Val = -C0080Val;
1769 unsigned Size = 32;
1770 do {
1771 if (TySizeBits > Size) {
1772 bool Found = false;
1773 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1774 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1775 if (RHSSExt == CFF80Val) {
1776 if (XorRHS->getZExtValue() == C0080Val)
1777 Found = true;
1778 } else if (RHSZExt == C0080Val) {
1779 if (XorRHS->getSExtValue() == CFF80Val)
1780 Found = true;
1781 }
1782 if (Found) {
1783 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001784 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001785 Mask <<= 64-(TySizeBits-Size);
Reid Spencera94d3942007-01-19 21:13:56 +00001786 Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001787 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001788 Size = 0; // Not a sign ext, but can't be any others either.
1789 goto FoundSExt;
1790 }
1791 }
1792 Size >>= 1;
1793 C0080Val >>= Size;
1794 CFF80Val >>= Size;
1795 } while (Size >= 8);
1796
1797FoundSExt:
1798 const Type *MiddleType = 0;
1799 switch (Size) {
1800 default: break;
Reid Spencerc635f472006-12-31 05:48:39 +00001801 case 32: MiddleType = Type::Int32Ty; break;
1802 case 16: MiddleType = Type::Int16Ty; break;
1803 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001804 }
1805 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001806 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001807 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001808 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001809 }
1810 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001811 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001812
Chris Lattnerb8b97502003-08-13 19:01:45 +00001813 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00001814 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001815 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001816
1817 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1818 if (RHSI->getOpcode() == Instruction::Sub)
1819 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1820 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1821 }
1822 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1823 if (LHSI->getOpcode() == Instruction::Sub)
1824 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1825 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1826 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001827 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001828
Chris Lattner147e9752002-05-08 22:46:53 +00001829 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001830 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001831 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001832
1833 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001834 if (!isa<Constant>(RHS))
1835 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001836 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001837
Misha Brukmanb1c93172005-04-21 23:48:37 +00001838
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001839 ConstantInt *C2;
1840 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1841 if (X == RHS) // X*C + X --> X * (C+1)
1842 return BinaryOperator::createMul(RHS, AddOne(C2));
1843
1844 // X*C1 + X*C2 --> X * (C1+C2)
1845 ConstantInt *C1;
1846 if (X == dyn_castFoldableMul(RHS, C1))
1847 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001848 }
1849
1850 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001851 if (dyn_castFoldableMul(RHS, C2) == LHS)
1852 return BinaryOperator::createMul(LHS, AddOne(C2));
1853
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001854 // X + ~X --> -1 since ~X = -X-1
1855 if (dyn_castNotVal(LHS) == RHS ||
1856 dyn_castNotVal(RHS) == LHS)
1857 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1858
Chris Lattner57c8d992003-02-18 19:57:07 +00001859
Chris Lattnerb8b97502003-08-13 19:01:45 +00001860 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001861 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001862 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1863 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001864
Chris Lattnerb9cde762003-10-02 15:11:26 +00001865 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001866 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001867 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1868 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1869 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001870 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001871
Chris Lattnerbff91d92004-10-08 05:07:56 +00001872 // (X & FF00) + xx00 -> (X+xx00) & FF00
1873 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1874 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1875 if (Anded == CRHS) {
1876 // See if all bits from the first bit set in the Add RHS up are included
1877 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001878 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001879
1880 // Form a mask of all bits from the lowest bit added through the top.
1881 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Reid Spencera94d3942007-01-19 21:13:56 +00001882 AddRHSHighBits &= C2->getType()->getBitMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001883
1884 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001885 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001886
Chris Lattnerbff91d92004-10-08 05:07:56 +00001887 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1888 // Okay, the xform is safe. Insert the new add pronto.
1889 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1890 LHS->getName()), I);
1891 return BinaryOperator::createAnd(NewAdd, C2);
1892 }
1893 }
1894 }
1895
Chris Lattnerd4252a72004-07-30 07:50:03 +00001896 // Try to fold constant add into select arguments.
1897 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001898 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001899 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001900 }
1901
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001902 // add (cast *A to intptrtype) B ->
1903 // cast (GEP (cast *A to sbyte*) B) ->
1904 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001905 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001906 CastInst *CI = dyn_cast<CastInst>(LHS);
1907 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001908 if (!CI) {
1909 CI = dyn_cast<CastInst>(RHS);
1910 Other = LHS;
1911 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001912 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00001913 (CI->getType()->getPrimitiveSizeInBits() ==
1914 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001915 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00001916 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001917 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001918 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001919 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001920 }
1921 }
1922
Chris Lattner113f4f42002-06-25 16:13:24 +00001923 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001924}
1925
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001926// isSignBit - Return true if the value represented by the constant only has the
1927// highest order bit set.
1928static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001929 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001930 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001931}
1932
Chris Lattner113f4f42002-06-25 16:13:24 +00001933Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001934 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001935
Chris Lattnere6794492002-08-12 21:17:25 +00001936 if (Op0 == Op1) // sub X, X -> 0
1937 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001938
Chris Lattnere6794492002-08-12 21:17:25 +00001939 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001940 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001941 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001942
Chris Lattner81a7a232004-10-16 18:11:37 +00001943 if (isa<UndefValue>(Op0))
1944 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1945 if (isa<UndefValue>(Op1))
1946 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1947
Chris Lattner8f2f5982003-11-05 01:06:05 +00001948 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1949 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001950 if (C->isAllOnesValue())
1951 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001952
Chris Lattner8f2f5982003-11-05 01:06:05 +00001953 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001954 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001955 if (match(Op1, m_Not(m_Value(X))))
1956 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001957 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner27df1db2007-01-15 07:02:54 +00001958 // -(X >>u 31) -> (X >>s 31)
1959 // -(X >>s 31) -> (X >>u 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001960 if (C->isNullValue()) {
Chris Lattner27df1db2007-01-15 07:02:54 +00001961 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00001962 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001963 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001964 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001965 if (CU->getZExtValue() ==
1966 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001967 // Ok, the transformation is safe. Insert AShr.
Chris Lattner27df1db2007-01-15 07:02:54 +00001968 return new ShiftInst(Instruction::AShr, SI->getOperand(0), CU,
Reid Spencer193df252006-12-24 00:40:59 +00001969 SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00001970 }
1971 }
Reid Spencerfdff9382006-11-08 06:47:33 +00001972 }
1973 else if (SI->getOpcode() == Instruction::AShr) {
1974 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1975 // Check to see if we are shifting out everything but the sign bit.
1976 if (CU->getZExtValue() ==
1977 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00001978 // Ok, the transformation is safe. Insert LShr.
1979 return new ShiftInst(Instruction::LShr, SI->getOperand(0), CU,
1980 SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00001981 }
1982 }
1983 }
Chris Lattner022167f2004-03-13 00:11:49 +00001984 }
Chris Lattner183b3362004-04-09 19:05:30 +00001985
1986 // Try to fold constant sub into select arguments.
1987 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001988 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001989 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001990
1991 if (isa<PHINode>(Op0))
1992 if (Instruction *NV = FoldOpIntoPhi(I))
1993 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001994 }
1995
Chris Lattnera9be4492005-04-07 16:15:25 +00001996 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1997 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00001998 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001999 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002000 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002001 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002002 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002003 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2004 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2005 // C1-(X+C2) --> (C1-C2)-X
2006 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2007 Op1I->getOperand(0));
2008 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002009 }
2010
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002011 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002012 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2013 // is not used by anyone else...
2014 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002015 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002016 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002017 // Swap the two operands of the subexpr...
2018 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2019 Op1I->setOperand(0, IIOp1);
2020 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002021
Chris Lattner3082c5a2003-02-18 19:28:33 +00002022 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002023 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002024 }
2025
2026 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2027 //
2028 if (Op1I->getOpcode() == Instruction::And &&
2029 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2030 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2031
Chris Lattner396dbfe2004-06-09 05:08:07 +00002032 Value *NewNot =
2033 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002034 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002035 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002036
Reid Spencer3c514952006-10-16 23:08:08 +00002037 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002038 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002039 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002040 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002041 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002042 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002043 ConstantExpr::getNeg(DivRHS));
2044
Chris Lattner57c8d992003-02-18 19:57:07 +00002045 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002046 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002047 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002048 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002049 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002050 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002051 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002052 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002053 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002054
Chris Lattner7a002fe2006-12-02 00:13:08 +00002055 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002056 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2057 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002058 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2059 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2060 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2061 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002062 } else if (Op0I->getOpcode() == Instruction::Sub) {
2063 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2064 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002065 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002066
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002067 ConstantInt *C1;
2068 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2069 if (X == Op1) { // X*C - X --> X * (C-1)
2070 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2071 return BinaryOperator::createMul(Op1, CP1);
2072 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002073
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002074 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2075 if (X == dyn_castFoldableMul(Op1, C2))
2076 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2077 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002078 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002079}
2080
Reid Spencer266e42b2006-12-23 06:05:41 +00002081/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002082/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002083static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2084 switch (pred) {
2085 case ICmpInst::ICMP_SLT:
2086 // True if LHS s< RHS and RHS == 0
2087 return RHS->isNullValue();
2088 case ICmpInst::ICMP_SLE:
2089 // True if LHS s<= RHS and RHS == -1
2090 return RHS->isAllOnesValue();
2091 case ICmpInst::ICMP_UGE:
2092 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2093 return RHS->getZExtValue() == (1ULL <<
2094 (RHS->getType()->getPrimitiveSizeInBits()-1));
2095 case ICmpInst::ICMP_UGT:
2096 // True if LHS u> RHS and RHS == high-bit-mask - 1
2097 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002098 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002099 default:
2100 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002101 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002102}
2103
Chris Lattner113f4f42002-06-25 16:13:24 +00002104Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002105 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002106 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002107
Chris Lattner81a7a232004-10-16 18:11:37 +00002108 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2109 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2110
Chris Lattnere6794492002-08-12 21:17:25 +00002111 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002112 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2113 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002114
2115 // ((X << C1)*C2) == (X * (C2 << C1))
2116 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2117 if (SI->getOpcode() == Instruction::Shl)
2118 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002119 return BinaryOperator::createMul(SI->getOperand(0),
2120 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002121
Chris Lattnercce81be2003-09-11 22:24:54 +00002122 if (CI->isNullValue())
2123 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2124 if (CI->equalsInt(1)) // X * 1 == X
2125 return ReplaceInstUsesWith(I, Op0);
2126 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002127 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002128
Reid Spencere0fc4df2006-10-20 07:07:24 +00002129 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002130 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2131 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002132 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencerc635f472006-12-31 05:48:39 +00002133 ConstantInt::get(Type::Int8Ty, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002134 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002135 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002136 if (Op1F->isNullValue())
2137 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002138
Chris Lattner3082c5a2003-02-18 19:28:33 +00002139 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2140 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2141 if (Op1F->getValue() == 1.0)
2142 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2143 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002144
2145 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2146 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2147 isa<ConstantInt>(Op0I->getOperand(1))) {
2148 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2149 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2150 Op1, "tmp");
2151 InsertNewInstBefore(Add, I);
2152 Value *C1C2 = ConstantExpr::getMul(Op1,
2153 cast<Constant>(Op0I->getOperand(1)));
2154 return BinaryOperator::createAdd(Add, C1C2);
2155
2156 }
Chris Lattner183b3362004-04-09 19:05:30 +00002157
2158 // Try to fold constant mul into select arguments.
2159 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002160 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002161 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002162
2163 if (isa<PHINode>(Op0))
2164 if (Instruction *NV = FoldOpIntoPhi(I))
2165 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002166 }
2167
Chris Lattner934a64cf2003-03-10 23:23:04 +00002168 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2169 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002170 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002171
Chris Lattner2635b522004-02-23 05:39:21 +00002172 // If one of the operands of the multiply is a cast from a boolean value, then
2173 // we know the bool is either zero or one, so this is a 'masking' multiply.
2174 // See if we can simplify things based on how the boolean was originally
2175 // formed.
2176 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002177 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002178 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002179 BoolCast = CI;
2180 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002181 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002182 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002183 BoolCast = CI;
2184 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002185 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002186 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2187 const Type *SCOpTy = SCIOp0->getType();
2188
Reid Spencer266e42b2006-12-23 06:05:41 +00002189 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002190 // multiply into a shift/and combination.
2191 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002192 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002193 // Shift the X value right to turn it into "all signbits".
Reid Spencerc635f472006-12-31 05:48:39 +00002194 Constant *Amt = ConstantInt::get(Type::Int8Ty,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002195 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002196 Value *V =
Reid Spencerfdff9382006-11-08 06:47:33 +00002197 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002198 BoolCast->getOperand(0)->getName()+
2199 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002200
2201 // If the multiply type is not the same as the source type, sign extend
2202 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002203 if (I.getType() != V->getType()) {
2204 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2205 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2206 Instruction::CastOps opcode =
2207 (SrcBits == DstBits ? Instruction::BitCast :
2208 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2209 V = InsertCastBefore(opcode, V, I.getType(), I);
2210 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002211
Chris Lattner2635b522004-02-23 05:39:21 +00002212 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002213 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002214 }
2215 }
2216 }
2217
Chris Lattner113f4f42002-06-25 16:13:24 +00002218 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002219}
2220
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002221/// This function implements the transforms on div instructions that work
2222/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2223/// used by the visitors to those instructions.
2224/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002225Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002226 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002227
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002228 // undef / X -> 0
2229 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002230 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002231
2232 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002233 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002234 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002235
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002236 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002237 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2238 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002239 // same basic block, then we replace the select with Y, and the condition
2240 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002241 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002242 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002243 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2244 if (ST->isNullValue()) {
2245 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2246 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002247 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002248 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2249 I.setOperand(1, SI->getOperand(2));
2250 else
2251 UpdateValueUsesWith(SI, SI->getOperand(2));
2252 return &I;
2253 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002254
Chris Lattnerd79dc792006-09-09 20:26:32 +00002255 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2256 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2257 if (ST->isNullValue()) {
2258 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2259 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002260 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002261 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2262 I.setOperand(1, SI->getOperand(1));
2263 else
2264 UpdateValueUsesWith(SI, SI->getOperand(1));
2265 return &I;
2266 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002267 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002268
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002269 return 0;
2270}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002271
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002272/// This function implements the transforms common to both integer division
2273/// instructions (udiv and sdiv). It is called by the visitors to those integer
2274/// division instructions.
2275/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002276Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002277 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2278
2279 if (Instruction *Common = commonDivTransforms(I))
2280 return Common;
2281
2282 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2283 // div X, 1 == X
2284 if (RHS->equalsInt(1))
2285 return ReplaceInstUsesWith(I, Op0);
2286
2287 // (X / C1) / C2 -> X / (C1*C2)
2288 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2289 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2290 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2291 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2292 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002293 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002294
2295 if (!RHS->isNullValue()) { // avoid X udiv 0
2296 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2297 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2298 return R;
2299 if (isa<PHINode>(Op0))
2300 if (Instruction *NV = FoldOpIntoPhi(I))
2301 return NV;
2302 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002303 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002304
Chris Lattner3082c5a2003-02-18 19:28:33 +00002305 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002306 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002307 if (LHS->equalsInt(0))
2308 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2309
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002310 return 0;
2311}
2312
2313Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2314 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2315
2316 // Handle the integer div common cases
2317 if (Instruction *Common = commonIDivTransforms(I))
2318 return Common;
2319
2320 // X udiv C^2 -> X >> C
2321 // Check to see if this is an unsigned division with an exact power of 2,
2322 // if so, convert to a right shift.
2323 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2324 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2325 if (isPowerOf2_64(Val)) {
2326 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencerfdff9382006-11-08 06:47:33 +00002327 return new ShiftInst(Instruction::LShr, Op0,
Reid Spencerc635f472006-12-31 05:48:39 +00002328 ConstantInt::get(Type::Int8Ty, ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002329 }
2330 }
2331
2332 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2333 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2334 if (RHSI->getOpcode() == Instruction::Shl &&
2335 isa<ConstantInt>(RHSI->getOperand(0))) {
2336 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2337 if (isPowerOf2_64(C1)) {
2338 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002339 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002340 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002341 Constant *C2V = ConstantInt::get(NTy, C2);
2342 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002343 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002344 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002345 }
2346 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002347 }
2348
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002349 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2350 // where C1&C2 are powers of two.
2351 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2352 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2353 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2354 if (!STO->isNullValue() && !STO->isNullValue()) {
2355 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2356 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2357 // Compute the shift amounts
2358 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002359 // Construct the "on true" case of the select
Reid Spencerc635f472006-12-31 05:48:39 +00002360 Constant *TC = ConstantInt::get(Type::Int8Ty, TSA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002361 Instruction *TSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002362 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002363 TSI = InsertNewInstBefore(TSI, I);
2364
2365 // Construct the "on false" case of the select
Reid Spencerc635f472006-12-31 05:48:39 +00002366 Constant *FC = ConstantInt::get(Type::Int8Ty, FSA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002367 Instruction *FSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002368 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002369 FSI = InsertNewInstBefore(FSI, I);
2370
2371 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002372 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002373 }
2374 }
2375 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002376 return 0;
2377}
2378
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002379Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2380 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2381
2382 // Handle the integer div common cases
2383 if (Instruction *Common = commonIDivTransforms(I))
2384 return Common;
2385
2386 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2387 // sdiv X, -1 == -X
2388 if (RHS->isAllOnesValue())
2389 return BinaryOperator::createNeg(Op0);
2390
2391 // -X/C -> X/-C
2392 if (Value *LHSNeg = dyn_castNegVal(Op0))
2393 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2394 }
2395
2396 // If the sign bits of both operands are zero (i.e. we can prove they are
2397 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002398 if (I.getType()->isInteger()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002399 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2400 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2401 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2402 }
2403 }
2404
2405 return 0;
2406}
2407
2408Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2409 return commonDivTransforms(I);
2410}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002411
Chris Lattner85dda9a2006-03-02 06:50:58 +00002412/// GetFactor - If we can prove that the specified value is at least a multiple
2413/// of some factor, return that factor.
2414static Constant *GetFactor(Value *V) {
2415 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2416 return CI;
2417
2418 // Unless we can be tricky, we know this is a multiple of 1.
2419 Constant *Result = ConstantInt::get(V->getType(), 1);
2420
2421 Instruction *I = dyn_cast<Instruction>(V);
2422 if (!I) return Result;
2423
2424 if (I->getOpcode() == Instruction::Mul) {
2425 // Handle multiplies by a constant, etc.
2426 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2427 GetFactor(I->getOperand(1)));
2428 } else if (I->getOpcode() == Instruction::Shl) {
2429 // (X<<C) -> X * (1 << C)
2430 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2431 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2432 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2433 }
2434 } else if (I->getOpcode() == Instruction::And) {
2435 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2436 // X & 0xFFF0 is known to be a multiple of 16.
2437 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2438 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2439 return ConstantExpr::getShl(Result,
Reid Spencerc635f472006-12-31 05:48:39 +00002440 ConstantInt::get(Type::Int8Ty, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002441 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002442 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002443 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002444 if (!CI->isIntegerCast())
2445 return Result;
2446 Value *Op = CI->getOperand(0);
2447 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002448 }
2449 return Result;
2450}
2451
Reid Spencer7eb55b32006-11-02 01:53:59 +00002452/// This function implements the transforms on rem instructions that work
2453/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2454/// is used by the visitors to those instructions.
2455/// @brief Transforms common to all three rem instructions
2456Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002457 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002458
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002459 // 0 % X == 0, we don't need to preserve faults!
2460 if (Constant *LHS = dyn_cast<Constant>(Op0))
2461 if (LHS->isNullValue())
2462 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2463
2464 if (isa<UndefValue>(Op0)) // undef % X -> 0
2465 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2466 if (isa<UndefValue>(Op1))
2467 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002468
2469 // Handle cases involving: rem X, (select Cond, Y, Z)
2470 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2471 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2472 // the same basic block, then we replace the select with Y, and the
2473 // condition of the select with false (if the cond value is in the same
2474 // BB). If the select has uses other than the div, this allows them to be
2475 // simplified also.
2476 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2477 if (ST->isNullValue()) {
2478 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2479 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002480 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002481 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2482 I.setOperand(1, SI->getOperand(2));
2483 else
2484 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002485 return &I;
2486 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002487 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2488 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2489 if (ST->isNullValue()) {
2490 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2491 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002492 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002493 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2494 I.setOperand(1, SI->getOperand(1));
2495 else
2496 UpdateValueUsesWith(SI, SI->getOperand(1));
2497 return &I;
2498 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002499 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002500
Reid Spencer7eb55b32006-11-02 01:53:59 +00002501 return 0;
2502}
2503
2504/// This function implements the transforms common to both integer remainder
2505/// instructions (urem and srem). It is called by the visitors to those integer
2506/// remainder instructions.
2507/// @brief Common integer remainder transforms
2508Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2509 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2510
2511 if (Instruction *common = commonRemTransforms(I))
2512 return common;
2513
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002514 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002515 // X % 0 == undef, we don't need to preserve faults!
2516 if (RHS->equalsInt(0))
2517 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2518
Chris Lattner3082c5a2003-02-18 19:28:33 +00002519 if (RHS->equalsInt(1)) // X % 1 == 0
2520 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2521
Chris Lattnerb70f1412006-02-28 05:49:21 +00002522 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2523 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2524 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2525 return R;
2526 } else if (isa<PHINode>(Op0I)) {
2527 if (Instruction *NV = FoldOpIntoPhi(I))
2528 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002529 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002530 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2531 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002532 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002533 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002534 }
2535
Reid Spencer7eb55b32006-11-02 01:53:59 +00002536 return 0;
2537}
2538
2539Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2540 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2541
2542 if (Instruction *common = commonIRemTransforms(I))
2543 return common;
2544
2545 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2546 // X urem C^2 -> X and C
2547 // Check to see if this is an unsigned remainder with an exact power of 2,
2548 // if so, convert to a bitwise and.
2549 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2550 if (isPowerOf2_64(C->getZExtValue()))
2551 return BinaryOperator::createAnd(Op0, SubOne(C));
2552 }
2553
Chris Lattner2e90b732006-02-05 07:54:04 +00002554 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002555 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2556 if (RHSI->getOpcode() == Instruction::Shl &&
2557 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002558 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002559 if (isPowerOf2_64(C1)) {
2560 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2561 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2562 "tmp"), I);
2563 return BinaryOperator::createAnd(Op0, Add);
2564 }
2565 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002566 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002567
Reid Spencer7eb55b32006-11-02 01:53:59 +00002568 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2569 // where C1&C2 are powers of two.
2570 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2571 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2572 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2573 // STO == 0 and SFO == 0 handled above.
2574 if (isPowerOf2_64(STO->getZExtValue()) &&
2575 isPowerOf2_64(SFO->getZExtValue())) {
2576 Value *TrueAnd = InsertNewInstBefore(
2577 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2578 Value *FalseAnd = InsertNewInstBefore(
2579 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2580 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2581 }
2582 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002583 }
2584
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002585 return 0;
2586}
2587
Reid Spencer7eb55b32006-11-02 01:53:59 +00002588Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2589 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2590
2591 if (Instruction *common = commonIRemTransforms(I))
2592 return common;
2593
2594 if (Value *RHSNeg = dyn_castNegVal(Op1))
2595 if (!isa<ConstantInt>(RHSNeg) ||
2596 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2597 // X % -Y -> X % Y
2598 AddUsesToWorkList(I);
2599 I.setOperand(1, RHSNeg);
2600 return &I;
2601 }
2602
2603 // If the top bits of both operands are zero (i.e. we can prove they are
2604 // unsigned inputs), turn this into a urem.
2605 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2606 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2607 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2608 return BinaryOperator::createURem(Op0, Op1, I.getName());
2609 }
2610
2611 return 0;
2612}
2613
2614Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002615 return commonRemTransforms(I);
2616}
2617
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002618// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002619static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2620 if (isSigned) {
2621 // Calculate 0111111111..11111
2622 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2623 int64_t Val = INT64_MAX; // All ones
2624 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2625 return C->getSExtValue() == Val-1;
2626 }
Reid Spencera94d3942007-01-19 21:13:56 +00002627 return C->getZExtValue() == C->getType()->getBitMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002628}
2629
2630// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002631static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2632 if (isSigned) {
2633 // Calculate 1111111111000000000000
2634 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2635 int64_t Val = -1; // All ones
2636 Val <<= TypeBits-1; // Shift over to the right spot
2637 return C->getSExtValue() == Val+1;
2638 }
2639 return C->getZExtValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002640}
2641
Chris Lattner35167c32004-06-09 07:59:58 +00002642// isOneBitSet - Return true if there is exactly one bit set in the specified
2643// constant.
2644static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002645 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002646 return V && (V & (V-1)) == 0;
2647}
2648
Chris Lattner8fc5af42004-09-23 21:46:38 +00002649#if 0 // Currently unused
2650// isLowOnes - Return true if the constant is of the form 0+1+.
2651static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002652 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002653
2654 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002655 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002656
2657 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2658 return U && V && (U & V) == 0;
2659}
2660#endif
2661
2662// isHighOnes - Return true if the constant is of the form 1+0+.
2663// This is the same as lowones(~X).
2664static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002665 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002666 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002667
2668 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002669 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002670
2671 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2672 return U && V && (U & V) == 0;
2673}
2674
Reid Spencer266e42b2006-12-23 06:05:41 +00002675/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002676/// are carefully arranged to allow folding of expressions such as:
2677///
2678/// (A < B) | (A > B) --> (A != B)
2679///
Reid Spencer266e42b2006-12-23 06:05:41 +00002680/// Note that this is only valid if the first and second predicates have the
2681/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002682///
Reid Spencer266e42b2006-12-23 06:05:41 +00002683/// Three bits are used to represent the condition, as follows:
2684/// 0 A > B
2685/// 1 A == B
2686/// 2 A < B
2687///
2688/// <=> Value Definition
2689/// 000 0 Always false
2690/// 001 1 A > B
2691/// 010 2 A == B
2692/// 011 3 A >= B
2693/// 100 4 A < B
2694/// 101 5 A != B
2695/// 110 6 A <= B
2696/// 111 7 Always true
2697///
2698static unsigned getICmpCode(const ICmpInst *ICI) {
2699 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002700 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002701 case ICmpInst::ICMP_UGT: return 1; // 001
2702 case ICmpInst::ICMP_SGT: return 1; // 001
2703 case ICmpInst::ICMP_EQ: return 2; // 010
2704 case ICmpInst::ICMP_UGE: return 3; // 011
2705 case ICmpInst::ICMP_SGE: return 3; // 011
2706 case ICmpInst::ICMP_ULT: return 4; // 100
2707 case ICmpInst::ICMP_SLT: return 4; // 100
2708 case ICmpInst::ICMP_NE: return 5; // 101
2709 case ICmpInst::ICMP_ULE: return 6; // 110
2710 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002711 // True -> 7
2712 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002713 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002714 return 0;
2715 }
2716}
2717
Reid Spencer266e42b2006-12-23 06:05:41 +00002718/// getICmpValue - This is the complement of getICmpCode, which turns an
2719/// opcode and two operands into either a constant true or false, or a brand
2720/// new /// ICmp instruction. The sign is passed in to determine which kind
2721/// of predicate to use in new icmp instructions.
2722static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2723 switch (code) {
2724 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002725 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002726 case 1:
2727 if (sign)
2728 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2729 else
2730 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2731 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2732 case 3:
2733 if (sign)
2734 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2735 else
2736 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2737 case 4:
2738 if (sign)
2739 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2740 else
2741 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2742 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2743 case 6:
2744 if (sign)
2745 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2746 else
2747 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002748 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002749 }
2750}
2751
Reid Spencer266e42b2006-12-23 06:05:41 +00002752static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2753 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2754 (ICmpInst::isSignedPredicate(p1) &&
2755 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2756 (ICmpInst::isSignedPredicate(p2) &&
2757 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2758}
2759
2760namespace {
2761// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2762struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002763 InstCombiner &IC;
2764 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002765 ICmpInst::Predicate pred;
2766 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2767 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2768 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002769 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002770 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2771 if (PredicatesFoldable(pred, ICI->getPredicate()))
2772 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2773 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002774 return false;
2775 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002776 Instruction *apply(Instruction &Log) const {
2777 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2778 if (ICI->getOperand(0) != LHS) {
2779 assert(ICI->getOperand(1) == LHS);
2780 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002781 }
2782
Reid Spencer266e42b2006-12-23 06:05:41 +00002783 unsigned LHSCode = getICmpCode(ICI);
2784 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattner3ac7c262003-08-13 20:16:26 +00002785 unsigned Code;
2786 switch (Log.getOpcode()) {
2787 case Instruction::And: Code = LHSCode & RHSCode; break;
2788 case Instruction::Or: Code = LHSCode | RHSCode; break;
2789 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002790 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002791 }
2792
Reid Spencer266e42b2006-12-23 06:05:41 +00002793 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002794 if (Instruction *I = dyn_cast<Instruction>(RV))
2795 return I;
2796 // Otherwise, it's a constant boolean value...
2797 return IC.ReplaceInstUsesWith(Log, RV);
2798 }
2799};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002800} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002801
Chris Lattnerba1cb382003-09-19 17:17:26 +00002802// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2803// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2804// guaranteed to be either a shift instruction or a binary operator.
2805Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00002806 ConstantInt *OpRHS,
2807 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00002808 BinaryOperator &TheAnd) {
2809 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002810 Constant *Together = 0;
2811 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002812 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002813
Chris Lattnerba1cb382003-09-19 17:17:26 +00002814 switch (Op->getOpcode()) {
2815 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002816 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002817 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2818 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002819 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002820 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002821 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002822 }
2823 break;
2824 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002825 if (Together == AndRHS) // (X | C) & C --> C
2826 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002827
Chris Lattner86102b82005-01-01 16:22:27 +00002828 if (Op->hasOneUse() && Together != OpRHS) {
2829 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2830 std::string Op0Name = Op->getName(); Op->setName("");
2831 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2832 InsertNewInstBefore(Or, TheAnd);
2833 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002834 }
2835 break;
2836 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002837 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002838 // Adding a one to a single bit bit-field should be turned into an XOR
2839 // of the bit. First thing to check is to see if this AND is with a
2840 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002841 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002842
2843 // Clear bits that are not part of the constant.
Reid Spencera94d3942007-01-19 21:13:56 +00002844 AndRHSV &= AndRHS->getType()->getBitMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002845
2846 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002847 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002848 // Ok, at this point, we know that we are masking the result of the
2849 // ADD down to exactly one bit. If the constant we are adding has
2850 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002851 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002852
Chris Lattnerba1cb382003-09-19 17:17:26 +00002853 // Check to see if any bits below the one bit set in AndRHSV are set.
2854 if ((AddRHS & (AndRHSV-1)) == 0) {
2855 // If not, the only thing that can effect the output of the AND is
2856 // the bit specified by AndRHSV. If that bit is set, the effect of
2857 // the XOR is to toggle the bit. If it is clear, then the ADD has
2858 // no effect.
2859 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2860 TheAnd.setOperand(0, X);
2861 return &TheAnd;
2862 } else {
2863 std::string Name = Op->getName(); Op->setName("");
2864 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002865 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002866 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002867 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002868 }
2869 }
2870 }
2871 }
2872 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002873
2874 case Instruction::Shl: {
2875 // We know that the AND will not produce any of the bits shifted in, so if
2876 // the anded constant includes them, clear them now!
2877 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002878 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002879 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2880 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002881
Chris Lattner7e794272004-09-24 15:21:34 +00002882 if (CI == ShlMask) { // Masking out bits that the shift already masks
2883 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2884 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002885 TheAnd.setOperand(1, CI);
2886 return &TheAnd;
2887 }
2888 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002889 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002890 case Instruction::LShr:
2891 {
Chris Lattner2da29172003-09-19 19:05:02 +00002892 // We know that the AND will not produce any of the bits shifted in, so if
2893 // the anded constant includes them, clear them now! This only applies to
2894 // unsigned shifts, because a signed shr may bring in set bits!
2895 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002896 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00002897 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2898 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002899
Reid Spencerfdff9382006-11-08 06:47:33 +00002900 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2901 return ReplaceInstUsesWith(TheAnd, Op);
2902 } else if (CI != AndRHS) {
2903 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2904 return &TheAnd;
2905 }
2906 break;
2907 }
2908 case Instruction::AShr:
2909 // Signed shr.
2910 // See if this is shifting in some sign extension, then masking it out
2911 // with an and.
2912 if (Op->hasOneUse()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002913 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00002914 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00002915 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2916 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002917 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00002918 // Make the argument unsigned.
2919 Value *ShVal = Op->getOperand(0);
Reid Spencer2a499b02006-12-13 17:19:09 +00002920 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2921 OpRHS, Op->getName()), TheAnd);
2922 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002923 }
Chris Lattner2da29172003-09-19 19:05:02 +00002924 }
2925 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002926 }
2927 return 0;
2928}
2929
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002930
Chris Lattner6862fbd2004-09-29 17:40:11 +00002931/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2932/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00002933/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2934/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00002935/// insert new instructions.
2936Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00002937 bool isSigned, bool Inside,
2938 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002939 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00002940 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00002941 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002942
Chris Lattner6862fbd2004-09-29 17:40:11 +00002943 if (Inside) {
2944 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00002945 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002946
Reid Spencer266e42b2006-12-23 06:05:41 +00002947 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00002948 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002949 ICmpInst::Predicate pred = (isSigned ?
2950 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2951 return new ICmpInst(pred, V, Hi);
2952 }
2953
2954 // Emit V-Lo <u Hi-Lo
2955 Constant *NegLo = ConstantExpr::getNeg(Lo);
2956 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00002957 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00002958 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2959 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002960 }
2961
2962 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00002963 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002964
Reid Spencer266e42b2006-12-23 06:05:41 +00002965 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattner6862fbd2004-09-29 17:40:11 +00002966 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00002967 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002968 ICmpInst::Predicate pred = (isSigned ?
2969 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
2970 return new ICmpInst(pred, V, Hi);
2971 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00002972
Reid Spencer266e42b2006-12-23 06:05:41 +00002973 // Emit V-Lo > Hi-1-Lo
2974 Constant *NegLo = ConstantExpr::getNeg(Lo);
2975 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00002976 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00002977 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
2978 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002979}
2980
Chris Lattnerb4b25302005-09-18 07:22:02 +00002981// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2982// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2983// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2984// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00002985static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002986 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00002987 if (!isShiftedMask_64(V)) return false;
2988
2989 // look for the first zero bit after the run of ones
2990 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2991 // look for the first non-zero bit
2992 ME = 64-CountLeadingZeros_64(V);
2993 return true;
2994}
2995
2996
2997
2998/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2999/// where isSub determines whether the operator is a sub. If we can fold one of
3000/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003001///
3002/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3003/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3004/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3005///
3006/// return (A +/- B).
3007///
3008Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003009 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003010 Instruction &I) {
3011 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3012 if (!LHSI || LHSI->getNumOperands() != 2 ||
3013 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3014
3015 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3016
3017 switch (LHSI->getOpcode()) {
3018 default: return 0;
3019 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003020 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3021 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003022 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003023 break;
3024
3025 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3026 // part, we don't need any explicit masks to take them out of A. If that
3027 // is all N is, ignore it.
3028 unsigned MB, ME;
3029 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencera94d3942007-01-19 21:13:56 +00003030 uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003031 Mask >>= 64-MB+1;
3032 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003033 break;
3034 }
3035 }
Chris Lattneraf517572005-09-18 04:24:45 +00003036 return 0;
3037 case Instruction::Or:
3038 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003039 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003040 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003041 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003042 break;
3043 return 0;
3044 }
3045
3046 Instruction *New;
3047 if (isSub)
3048 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3049 else
3050 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3051 return InsertNewInstBefore(New, I);
3052}
3053
Chris Lattner113f4f42002-06-25 16:13:24 +00003054Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003055 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003056 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003057
Chris Lattner81a7a232004-10-16 18:11:37 +00003058 if (isa<UndefValue>(Op1)) // X & undef -> 0
3059 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3060
Chris Lattner86102b82005-01-01 16:22:27 +00003061 // and X, X = X
3062 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003063 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003064
Chris Lattner5b2edb12006-02-12 08:02:11 +00003065 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003066 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003067 uint64_t KnownZero, KnownOne;
Chris Lattner120ab032007-01-18 22:16:33 +00003068 if (!isa<PackedType>(I.getType())) {
Reid Spencera94d3942007-01-19 21:13:56 +00003069 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner120ab032007-01-18 22:16:33 +00003070 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003071 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003072 } else {
3073 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Op1)) {
3074 if (CP->isAllOnesValue())
3075 return ReplaceInstUsesWith(I, I.getOperand(0));
3076 }
3077 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003078
Zhou Sheng75b871f2007-01-11 12:24:14 +00003079 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003080 uint64_t AndRHSMask = AndRHS->getZExtValue();
Reid Spencera94d3942007-01-19 21:13:56 +00003081 uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003082 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003083
Chris Lattnerba1cb382003-09-19 17:17:26 +00003084 // Optimize a variety of ((val OP C1) & C2) combinations...
3085 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3086 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003087 Value *Op0LHS = Op0I->getOperand(0);
3088 Value *Op0RHS = Op0I->getOperand(1);
3089 switch (Op0I->getOpcode()) {
3090 case Instruction::Xor:
3091 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003092 // If the mask is only needed on one incoming arm, push it up.
3093 if (Op0I->hasOneUse()) {
3094 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3095 // Not masking anything out for the LHS, move to RHS.
3096 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3097 Op0RHS->getName()+".masked");
3098 InsertNewInstBefore(NewRHS, I);
3099 return BinaryOperator::create(
3100 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003101 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003102 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003103 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3104 // Not masking anything out for the RHS, move to LHS.
3105 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3106 Op0LHS->getName()+".masked");
3107 InsertNewInstBefore(NewLHS, I);
3108 return BinaryOperator::create(
3109 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3110 }
3111 }
3112
Chris Lattner86102b82005-01-01 16:22:27 +00003113 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003114 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003115 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3116 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3117 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3118 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3119 return BinaryOperator::createAnd(V, AndRHS);
3120 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3121 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003122 break;
3123
3124 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003125 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3126 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3127 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3128 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3129 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003130 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003131 }
3132
Chris Lattner16464b32003-07-23 19:25:52 +00003133 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003134 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003135 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003136 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003137 // If this is an integer truncation or change from signed-to-unsigned, and
3138 // if the source is an and/or with immediate, transform it. This
3139 // frequently occurs for bitfield accesses.
3140 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003141 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003142 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003143 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003144 if (CastOp->getOpcode() == Instruction::And) {
3145 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003146 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3147 // This will fold the two constants together, which may allow
3148 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003149 Instruction *NewCast = CastInst::createTruncOrBitCast(
3150 CastOp->getOperand(0), I.getType(),
3151 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003152 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003153 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003154 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003155 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003156 return BinaryOperator::createAnd(NewCast, C3);
3157 } else if (CastOp->getOpcode() == Instruction::Or) {
3158 // Change: and (cast (or X, C1) to T), C2
3159 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003160 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003161 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3162 return ReplaceInstUsesWith(I, AndRHS);
3163 }
3164 }
Chris Lattner33217db2003-07-23 19:36:21 +00003165 }
Chris Lattner183b3362004-04-09 19:05:30 +00003166
3167 // Try to fold constant and into select arguments.
3168 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003169 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003170 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003171 if (isa<PHINode>(Op0))
3172 if (Instruction *NV = FoldOpIntoPhi(I))
3173 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003174 }
3175
Chris Lattnerbb74e222003-03-10 23:06:50 +00003176 Value *Op0NotVal = dyn_castNotVal(Op0);
3177 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003178
Chris Lattner023a4832004-06-18 06:07:51 +00003179 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3180 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3181
Misha Brukman9c003d82004-07-30 12:50:08 +00003182 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003183 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003184 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3185 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003186 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003187 return BinaryOperator::createNot(Or);
3188 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003189
3190 {
3191 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003192 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3193 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3194 return ReplaceInstUsesWith(I, Op1);
3195 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3196 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3197 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003198
3199 if (Op0->hasOneUse() &&
3200 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3201 if (A == Op1) { // (A^B)&A -> A&(A^B)
3202 I.swapOperands(); // Simplify below
3203 std::swap(Op0, Op1);
3204 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3205 cast<BinaryOperator>(Op0)->swapOperands();
3206 I.swapOperands(); // Simplify below
3207 std::swap(Op0, Op1);
3208 }
3209 }
3210 if (Op1->hasOneUse() &&
3211 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3212 if (B == Op0) { // B&(A^B) -> B&(B^A)
3213 cast<BinaryOperator>(Op1)->swapOperands();
3214 std::swap(A, B);
3215 }
3216 if (A == Op0) { // A&(A^B) -> A & ~B
3217 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3218 InsertNewInstBefore(NotB, I);
3219 return BinaryOperator::createAnd(A, NotB);
3220 }
3221 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003222 }
3223
Reid Spencer266e42b2006-12-23 06:05:41 +00003224 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3225 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3226 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003227 return R;
3228
Chris Lattner623826c2004-09-28 21:48:02 +00003229 Value *LHSVal, *RHSVal;
3230 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003231 ICmpInst::Predicate LHSCC, RHSCC;
3232 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3233 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3234 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3235 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3236 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3237 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3238 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3239 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003240 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003241 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3242 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3243 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3244 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003245 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003246 std::swap(LHS, RHS);
3247 std::swap(LHSCst, RHSCst);
3248 std::swap(LHSCC, RHSCC);
3249 }
3250
Reid Spencer266e42b2006-12-23 06:05:41 +00003251 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003252 // comparing a value against two constants and and'ing the result
3253 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003254 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3255 // (from the FoldICmpLogical check above), that the two constants
3256 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003257 assert(LHSCst != RHSCst && "Compares not folded above?");
3258
3259 switch (LHSCC) {
3260 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003261 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003262 switch (RHSCC) {
3263 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003264 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3265 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3266 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003267 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003268 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3269 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3270 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003271 return ReplaceInstUsesWith(I, LHS);
3272 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003273 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003274 switch (RHSCC) {
3275 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003276 case ICmpInst::ICMP_ULT:
3277 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3278 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3279 break; // (X != 13 & X u< 15) -> no change
3280 case ICmpInst::ICMP_SLT:
3281 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3282 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3283 break; // (X != 13 & X s< 15) -> no change
3284 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3285 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3286 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003287 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003288 case ICmpInst::ICMP_NE:
3289 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003290 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3291 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3292 LHSVal->getName()+".off");
3293 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00003294 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3295 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00003296 }
3297 break; // (X != 13 & X != 15) -> no change
3298 }
3299 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003300 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003301 switch (RHSCC) {
3302 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003303 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3304 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003305 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003306 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3307 break;
3308 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3309 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003310 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003311 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3312 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003313 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003314 break;
3315 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003316 switch (RHSCC) {
3317 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003318 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3319 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003320 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003321 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3322 break;
3323 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3324 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003325 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003326 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3327 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003328 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003329 break;
3330 case ICmpInst::ICMP_UGT:
3331 switch (RHSCC) {
3332 default: assert(0 && "Unknown integer condition code!");
3333 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3334 return ReplaceInstUsesWith(I, LHS);
3335 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3336 return ReplaceInstUsesWith(I, RHS);
3337 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3338 break;
3339 case ICmpInst::ICMP_NE:
3340 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3341 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3342 break; // (X u> 13 & X != 15) -> no change
3343 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3344 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3345 true, I);
3346 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3347 break;
3348 }
3349 break;
3350 case ICmpInst::ICMP_SGT:
3351 switch (RHSCC) {
3352 default: assert(0 && "Unknown integer condition code!");
3353 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3354 return ReplaceInstUsesWith(I, LHS);
3355 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3356 return ReplaceInstUsesWith(I, RHS);
3357 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3358 break;
3359 case ICmpInst::ICMP_NE:
3360 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3361 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3362 break; // (X s> 13 & X != 15) -> no change
3363 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3364 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3365 true, I);
3366 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3367 break;
3368 }
3369 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003370 }
3371 }
3372 }
3373
Chris Lattner3af10532006-05-05 06:39:07 +00003374 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003375 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3376 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3377 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3378 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003379 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003380 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003381 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3382 I.getType(), TD) &&
3383 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3384 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003385 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3386 Op1C->getOperand(0),
3387 I.getName());
3388 InsertNewInstBefore(NewOp, I);
3389 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3390 }
Chris Lattner3af10532006-05-05 06:39:07 +00003391 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003392
3393 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3394 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3395 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3396 if (SI0->getOpcode() == SI1->getOpcode() &&
3397 SI0->getOperand(1) == SI1->getOperand(1) &&
3398 (SI0->hasOneUse() || SI1->hasOneUse())) {
3399 Instruction *NewOp =
3400 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3401 SI1->getOperand(0),
3402 SI0->getName()), I);
3403 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3404 }
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.
3424 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3425 // 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) {
3491 // We can only handle bswap of unsigned integers, and 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.
3650 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3651 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3652 if (SI0->getOpcode() == SI1->getOpcode() &&
3653 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);
3659 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3660 }
3661 }
Chris Lattner812aab72003-08-12 19:11:07 +00003662
Chris Lattnerd4252a72004-07-30 07:50:03 +00003663 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3664 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003665 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003666 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003667 } else {
3668 A = 0;
3669 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003670 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003671 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3672 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003673 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003674 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003675
Misha Brukman9c003d82004-07-30 12:50:08 +00003676 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003677 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3678 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3679 I.getName()+".demorgan"), I);
3680 return BinaryOperator::createNot(And);
3681 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003682 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003683
Reid Spencer266e42b2006-12-23 06:05:41 +00003684 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3685 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3686 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003687 return R;
3688
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003689 Value *LHSVal, *RHSVal;
3690 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003691 ICmpInst::Predicate LHSCC, RHSCC;
3692 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3693 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3694 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3695 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3696 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3697 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3698 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3699 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003700 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003701 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3702 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3703 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3704 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003705 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003706 std::swap(LHS, RHS);
3707 std::swap(LHSCst, RHSCst);
3708 std::swap(LHSCC, RHSCC);
3709 }
3710
Reid Spencer266e42b2006-12-23 06:05:41 +00003711 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003712 // comparing a value against two constants and or'ing the result
3713 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003714 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3715 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003716 // equal.
3717 assert(LHSCst != RHSCst && "Compares not folded above?");
3718
3719 switch (LHSCC) {
3720 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003721 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003722 switch (RHSCC) {
3723 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003724 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003725 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3726 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3727 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3728 LHSVal->getName()+".off");
3729 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003730 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003731 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003732 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003733 break; // (X == 13 | X == 15) -> no change
3734 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3735 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003736 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003737 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3738 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3739 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003740 return ReplaceInstUsesWith(I, RHS);
3741 }
3742 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003743 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003744 switch (RHSCC) {
3745 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003746 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3747 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3748 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003749 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003750 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3751 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3752 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003753 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003754 }
3755 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003756 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003757 switch (RHSCC) {
3758 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003759 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003760 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003761 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3762 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3763 false, I);
3764 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3765 break;
3766 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3767 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003768 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003769 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3770 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003771 }
3772 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003773 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003774 switch (RHSCC) {
3775 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003776 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3777 break;
3778 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3779 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3780 false, I);
3781 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3782 break;
3783 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3784 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3785 return ReplaceInstUsesWith(I, RHS);
3786 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3787 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003788 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003789 break;
3790 case ICmpInst::ICMP_UGT:
3791 switch (RHSCC) {
3792 default: assert(0 && "Unknown integer condition code!");
3793 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3794 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3795 return ReplaceInstUsesWith(I, LHS);
3796 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3797 break;
3798 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3799 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003800 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003801 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3802 break;
3803 }
3804 break;
3805 case ICmpInst::ICMP_SGT:
3806 switch (RHSCC) {
3807 default: assert(0 && "Unknown integer condition code!");
3808 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3809 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3810 return ReplaceInstUsesWith(I, LHS);
3811 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3812 break;
3813 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3814 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003815 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003816 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3817 break;
3818 }
3819 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003820 }
3821 }
3822 }
Chris Lattner3af10532006-05-05 06:39:07 +00003823
3824 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003825 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003826 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003827 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3828 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003829 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003830 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003831 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3832 I.getType(), TD) &&
3833 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3834 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003835 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3836 Op1C->getOperand(0),
3837 I.getName());
3838 InsertNewInstBefore(NewOp, I);
3839 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3840 }
Chris Lattner3af10532006-05-05 06:39:07 +00003841 }
Chris Lattner3af10532006-05-05 06:39:07 +00003842
Chris Lattner15212982005-09-18 03:42:07 +00003843
Chris Lattner113f4f42002-06-25 16:13:24 +00003844 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003845}
3846
Chris Lattnerc2076352004-02-16 01:20:27 +00003847// XorSelf - Implements: X ^ X --> 0
3848struct XorSelf {
3849 Value *RHS;
3850 XorSelf(Value *rhs) : RHS(rhs) {}
3851 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3852 Instruction *apply(BinaryOperator &Xor) const {
3853 return &Xor;
3854 }
3855};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003856
3857
Chris Lattner113f4f42002-06-25 16:13:24 +00003858Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003859 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003860 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003861
Chris Lattner81a7a232004-10-16 18:11:37 +00003862 if (isa<UndefValue>(Op1))
3863 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3864
Chris Lattnerc2076352004-02-16 01:20:27 +00003865 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3866 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3867 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003868 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003869 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003870
3871 // See if we can simplify any instructions used by the instruction whose sole
3872 // purpose is to compute bits we don't care about.
3873 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003874 if (!isa<PackedType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00003875 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003876 KnownZero, KnownOne))
3877 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003878
Zhou Sheng75b871f2007-01-11 12:24:14 +00003879 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003880 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3881 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00003882 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00003883 return new ICmpInst(ICI->getInversePredicate(),
3884 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003885
Reid Spencer266e42b2006-12-23 06:05:41 +00003886 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00003887 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003888 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3889 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003890 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3891 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003892 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003893 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003894 }
Chris Lattner023a4832004-06-18 06:07:51 +00003895
3896 // ~(~X & Y) --> (X | ~Y)
3897 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3898 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3899 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3900 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003901 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003902 Op0I->getOperand(1)->getName()+".not");
3903 InsertNewInstBefore(NotY, I);
3904 return BinaryOperator::createOr(Op0NotVal, NotY);
3905 }
3906 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003907
Chris Lattner97638592003-07-23 21:37:07 +00003908 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003909 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003910 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003911 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003912 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3913 return BinaryOperator::createSub(
3914 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003915 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003916 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003917 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003918 } else if (Op0I->getOpcode() == Instruction::Or) {
3919 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3920 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3921 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3922 // Anything in both C1 and C2 is known to be zero, remove it from
3923 // NewRHS.
3924 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3925 NewRHS = ConstantExpr::getAnd(NewRHS,
3926 ConstantExpr::getNot(CommonBits));
3927 WorkList.push_back(Op0I);
3928 I.setOperand(0, Op0I->getOperand(0));
3929 I.setOperand(1, NewRHS);
3930 return &I;
3931 }
Chris Lattner97638592003-07-23 21:37:07 +00003932 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003933 }
Chris Lattner183b3362004-04-09 19:05:30 +00003934
3935 // Try to fold constant and into select arguments.
3936 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003937 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003938 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003939 if (isa<PHINode>(Op0))
3940 if (Instruction *NV = FoldOpIntoPhi(I))
3941 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003942 }
3943
Chris Lattnerbb74e222003-03-10 23:06:50 +00003944 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003945 if (X == Op1)
3946 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003947 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003948
Chris Lattnerbb74e222003-03-10 23:06:50 +00003949 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003950 if (X == Op0)
3951 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003952 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003953
Chris Lattnerdcd07922006-04-01 08:03:55 +00003954 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003955 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003956 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003957 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003958 I.swapOperands();
3959 std::swap(Op0, Op1);
3960 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003961 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003962 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003963 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003964 } else if (Op1I->getOpcode() == Instruction::Xor) {
3965 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3966 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3967 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3968 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003969 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3970 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3971 Op1I->swapOperands();
3972 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3973 I.swapOperands(); // Simplified below.
3974 std::swap(Op0, Op1);
3975 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003976 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003977
Chris Lattnerdcd07922006-04-01 08:03:55 +00003978 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003979 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003980 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003981 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003982 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003983 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3984 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003985 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003986 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003987 } else if (Op0I->getOpcode() == Instruction::Xor) {
3988 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3989 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3990 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3991 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003992 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3993 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3994 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003995 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3996 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003997 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3998 InsertNewInstBefore(N, I);
3999 return BinaryOperator::createAnd(N, Op1);
4000 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004001 }
4002
Reid Spencer266e42b2006-12-23 06:05:41 +00004003 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4004 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4005 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004006 return R;
4007
Chris Lattner3af10532006-05-05 06:39:07 +00004008 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004009 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004010 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004011 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4012 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004013 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004014 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004015 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4016 I.getType(), TD) &&
4017 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4018 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004019 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4020 Op1C->getOperand(0),
4021 I.getName());
4022 InsertNewInstBefore(NewOp, I);
4023 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4024 }
Chris Lattner3af10532006-05-05 06:39:07 +00004025 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004026
4027 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4028 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4029 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4030 if (SI0->getOpcode() == SI1->getOpcode() &&
4031 SI0->getOperand(1) == SI1->getOperand(1) &&
4032 (SI0->hasOneUse() || SI1->hasOneUse())) {
4033 Instruction *NewOp =
4034 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4035 SI1->getOperand(0),
4036 SI0->getName()), I);
4037 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4038 }
4039 }
Chris Lattner3af10532006-05-05 06:39:07 +00004040
Chris Lattner113f4f42002-06-25 16:13:24 +00004041 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004042}
4043
Chris Lattner6862fbd2004-09-29 17:40:11 +00004044static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004045 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004046}
4047
4048/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4049/// overflowed for this type.
4050static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4051 ConstantInt *In2) {
4052 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4053
Reid Spencerc635f472006-12-31 05:48:39 +00004054 return cast<ConstantInt>(Result)->getZExtValue() <
4055 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004056}
4057
Chris Lattner0798af32005-01-13 20:14:25 +00004058/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4059/// code necessary to compute the offset from the base pointer (without adding
4060/// in the base pointer). Return the result as a signed integer of intptr size.
4061static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4062 TargetData &TD = IC.getTargetData();
4063 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004064 const Type *IntPtrTy = TD.getIntPtrType();
4065 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004066
4067 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004068 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004069
Chris Lattner0798af32005-01-13 20:14:25 +00004070 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4071 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004072 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004073 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004074 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4075 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004076 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004077 Scale = ConstantExpr::getMul(OpC, Scale);
4078 if (Constant *RC = dyn_cast<Constant>(Result))
4079 Result = ConstantExpr::getAdd(RC, Scale);
4080 else {
4081 // Emit an add instruction.
4082 Result = IC.InsertNewInstBefore(
4083 BinaryOperator::createAdd(Result, Scale,
4084 GEP->getName()+".offs"), I);
4085 }
4086 }
4087 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004088 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004089 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004090 Op->getName()+".c"), I);
4091 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004092 // We'll let instcombine(mul) convert this to a shl if possible.
4093 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4094 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004095
4096 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004097 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004098 GEP->getName()+".offs"), I);
4099 }
4100 }
4101 return Result;
4102}
4103
Reid Spencer266e42b2006-12-23 06:05:41 +00004104/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004105/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004106Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4107 ICmpInst::Predicate Cond,
4108 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004109 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004110
4111 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4112 if (isa<PointerType>(CI->getOperand(0)->getType()))
4113 RHS = CI->getOperand(0);
4114
Chris Lattner0798af32005-01-13 20:14:25 +00004115 Value *PtrBase = GEPLHS->getOperand(0);
4116 if (PtrBase == RHS) {
4117 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004118 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4119 // each index is zero or not.
4120 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004121 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004122 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4123 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004124 bool EmitIt = true;
4125 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4126 if (isa<UndefValue>(C)) // undef index -> undef.
4127 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4128 if (C->isNullValue())
4129 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004130 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4131 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004132 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004133 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004134 ConstantInt::get(Type::Int1Ty,
4135 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004136 }
4137
4138 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004139 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004140 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004141 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4142 if (InVal == 0)
4143 InVal = Comp;
4144 else {
4145 InVal = InsertNewInstBefore(InVal, I);
4146 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004147 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004148 InVal = BinaryOperator::createOr(InVal, Comp);
4149 else // True if all are equal
4150 InVal = BinaryOperator::createAnd(InVal, Comp);
4151 }
4152 }
4153 }
4154
4155 if (InVal)
4156 return InVal;
4157 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004158 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004159 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4160 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004161 }
Chris Lattner0798af32005-01-13 20:14:25 +00004162
Reid Spencer266e42b2006-12-23 06:05:41 +00004163 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004164 // the result to fold to a constant!
4165 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4166 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4167 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004168 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4169 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004170 }
4171 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004172 // If the base pointers are different, but the indices are the same, just
4173 // compare the base pointer.
4174 if (PtrBase != GEPRHS->getOperand(0)) {
4175 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004176 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004177 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004178 if (IndicesTheSame)
4179 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4180 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4181 IndicesTheSame = false;
4182 break;
4183 }
4184
4185 // If all indices are the same, just compare the base pointers.
4186 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004187 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4188 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004189
4190 // Otherwise, the base pointers are different and the indices are
4191 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004192 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004193 }
Chris Lattner0798af32005-01-13 20:14:25 +00004194
Chris Lattner81e84172005-01-13 22:25:21 +00004195 // If one of the GEPs has all zero indices, recurse.
4196 bool AllZeros = true;
4197 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4198 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4199 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4200 AllZeros = false;
4201 break;
4202 }
4203 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004204 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4205 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004206
4207 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004208 AllZeros = true;
4209 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4210 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4211 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4212 AllZeros = false;
4213 break;
4214 }
4215 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004216 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004217
Chris Lattner4fa89822005-01-14 00:20:05 +00004218 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4219 // If the GEPs only differ by one index, compare it.
4220 unsigned NumDifferences = 0; // Keep track of # differences.
4221 unsigned DiffOperand = 0; // The operand that differs.
4222 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4223 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004224 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4225 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004226 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004227 NumDifferences = 2;
4228 break;
4229 } else {
4230 if (NumDifferences++) break;
4231 DiffOperand = i;
4232 }
4233 }
4234
4235 if (NumDifferences == 0) // SAME GEP?
4236 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004237 ConstantInt::get(Type::Int1Ty,
4238 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004239 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004240 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4241 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004242 // Make sure we do a signed comparison here.
4243 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004244 }
4245 }
4246
Reid Spencer266e42b2006-12-23 06:05:41 +00004247 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004248 // the result to fold to a constant!
4249 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4250 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4251 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4252 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4253 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004254 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004255 }
4256 }
4257 return 0;
4258}
4259
Reid Spencer266e42b2006-12-23 06:05:41 +00004260Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4261 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004262 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004263
Chris Lattner6ee923f2007-01-14 19:42:17 +00004264 // Fold trivial predicates.
4265 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4266 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4267 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4268 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4269
4270 // Simplify 'fcmp pred X, X'
4271 if (Op0 == Op1) {
4272 switch (I.getPredicate()) {
4273 default: assert(0 && "Unknown predicate!");
4274 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4275 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4276 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4277 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4278 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4279 case FCmpInst::FCMP_OLT: // True if ordered and less than
4280 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4281 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4282
4283 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4284 case FCmpInst::FCMP_ULT: // True if unordered or less than
4285 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4286 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4287 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4288 I.setPredicate(FCmpInst::FCMP_UNO);
4289 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4290 return &I;
4291
4292 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4293 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4294 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4295 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4296 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4297 I.setPredicate(FCmpInst::FCMP_ORD);
4298 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4299 return &I;
4300 }
4301 }
4302
Reid Spencer266e42b2006-12-23 06:05:41 +00004303 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004304 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004305
Reid Spencer266e42b2006-12-23 06:05:41 +00004306 // Handle fcmp with constant RHS
4307 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4308 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4309 switch (LHSI->getOpcode()) {
4310 case Instruction::PHI:
4311 if (Instruction *NV = FoldOpIntoPhi(I))
4312 return NV;
4313 break;
4314 case Instruction::Select:
4315 // If either operand of the select is a constant, we can fold the
4316 // comparison into the select arms, which will cause one to be
4317 // constant folded and the select turned into a bitwise or.
4318 Value *Op1 = 0, *Op2 = 0;
4319 if (LHSI->hasOneUse()) {
4320 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4321 // Fold the known value into the constant operand.
4322 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4323 // Insert a new FCmp of the other select operand.
4324 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4325 LHSI->getOperand(2), RHSC,
4326 I.getName()), I);
4327 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4328 // Fold the known value into the constant operand.
4329 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4330 // Insert a new FCmp of the other select operand.
4331 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4332 LHSI->getOperand(1), RHSC,
4333 I.getName()), I);
4334 }
4335 }
4336
4337 if (Op1)
4338 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4339 break;
4340 }
4341 }
4342
4343 return Changed ? &I : 0;
4344}
4345
4346Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4347 bool Changed = SimplifyCompare(I);
4348 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4349 const Type *Ty = Op0->getType();
4350
4351 // icmp X, X
4352 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004353 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4354 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004355
4356 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004357 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004358
4359 // icmp of GlobalValues can never equal each other as long as they aren't
4360 // external weak linkage type.
4361 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4362 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4363 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004364 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4365 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004366
4367 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004368 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004369 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4370 isa<ConstantPointerNull>(Op0)) &&
4371 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004372 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004373 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4374 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004375
Reid Spencer266e42b2006-12-23 06:05:41 +00004376 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004377 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004378 switch (I.getPredicate()) {
4379 default: assert(0 && "Invalid icmp instruction!");
4380 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004381 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004382 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004383 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004384 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004385 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004386 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004387
Reid Spencer266e42b2006-12-23 06:05:41 +00004388 case ICmpInst::ICMP_UGT:
4389 case ICmpInst::ICMP_SGT:
4390 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004391 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004392 case ICmpInst::ICMP_ULT:
4393 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004394 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4395 InsertNewInstBefore(Not, I);
4396 return BinaryOperator::createAnd(Not, Op1);
4397 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004398 case ICmpInst::ICMP_UGE:
4399 case ICmpInst::ICMP_SGE:
4400 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004401 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004402 case ICmpInst::ICMP_ULE:
4403 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004404 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4405 InsertNewInstBefore(Not, I);
4406 return BinaryOperator::createOr(Not, Op1);
4407 }
4408 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004409 }
4410
Chris Lattner2dd01742004-06-09 04:24:29 +00004411 // See if we are doing a comparison between a constant and an instruction that
4412 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004413 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004414 switch (I.getPredicate()) {
4415 default: break;
4416 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4417 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004418 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004419 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4420 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4421 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4422 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4423 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004424
Reid Spencer266e42b2006-12-23 06:05:41 +00004425 case ICmpInst::ICMP_SLT:
4426 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004427 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004428 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4429 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4430 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4431 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4432 break;
4433
4434 case ICmpInst::ICMP_UGT:
4435 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004436 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004437 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4438 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4439 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4440 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4441 break;
4442
4443 case ICmpInst::ICMP_SGT:
4444 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004445 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004446 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4447 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4448 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4449 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4450 break;
4451
4452 case ICmpInst::ICMP_ULE:
4453 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004454 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004455 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4456 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4457 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4458 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4459 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004460
Reid Spencer266e42b2006-12-23 06:05:41 +00004461 case ICmpInst::ICMP_SLE:
4462 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004463 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004464 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4465 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4466 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4467 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4468 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004469
Reid Spencer266e42b2006-12-23 06:05:41 +00004470 case ICmpInst::ICMP_UGE:
4471 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004472 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004473 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4474 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4475 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4476 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4477 break;
4478
4479 case ICmpInst::ICMP_SGE:
4480 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004481 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004482 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4483 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4484 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4485 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4486 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004487 }
4488
Reid Spencer266e42b2006-12-23 06:05:41 +00004489 // If we still have a icmp le or icmp ge instruction, turn it into the
4490 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004491 // already been handled above, this requires little checking.
4492 //
Reid Spencer266e42b2006-12-23 06:05:41 +00004493 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4494 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4495 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4496 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4497 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4498 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4499 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4500 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00004501
4502 // See if we can fold the comparison based on bits known to be zero or one
4503 // in the input.
4504 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00004505 if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
Chris Lattneree0f2802006-02-12 02:07:56 +00004506 KnownZero, KnownOne, 0))
4507 return &I;
4508
4509 // Given the known and unknown bits, compute a range that the LHS could be
4510 // in.
4511 if (KnownOne | KnownZero) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004512 // Compute the Min, Max and RHS values based on the known bits. For the
4513 // EQ and NE we use unsigned values.
Reid Spencer910f23f2006-12-23 19:17:57 +00004514 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4515 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00004516 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4517 SRHSVal = CI->getSExtValue();
4518 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4519 SMax);
4520 } else {
4521 URHSVal = CI->getZExtValue();
4522 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4523 UMax);
4524 }
4525 switch (I.getPredicate()) { // LE/GE have been folded already.
4526 default: assert(0 && "Unknown icmp opcode!");
4527 case ICmpInst::ICMP_EQ:
4528 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004529 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004530 break;
4531 case ICmpInst::ICMP_NE:
4532 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004533 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004534 break;
4535 case ICmpInst::ICMP_ULT:
4536 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004537 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004538 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004539 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004540 break;
4541 case ICmpInst::ICMP_UGT:
4542 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004543 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004544 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004545 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004546 break;
4547 case ICmpInst::ICMP_SLT:
4548 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004549 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004550 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004551 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004552 break;
4553 case ICmpInst::ICMP_SGT:
4554 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004555 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004556 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004557 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004558 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004559 }
4560 }
4561
Reid Spencer266e42b2006-12-23 06:05:41 +00004562 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004563 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004564 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004565 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004566 switch (LHSI->getOpcode()) {
4567 case Instruction::And:
4568 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4569 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004570 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4571
Reid Spencer266e42b2006-12-23 06:05:41 +00004572 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004573 // and/compare to be the input width without changing the value
4574 // produced, eliminating a cast.
4575 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4576 // We can do this transformation if either the AND constant does not
4577 // have its sign bit set or if it is an equality comparison.
4578 // Extending a relational comparison when we're checking the sign
4579 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004580 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004581 (I.isEquality() ||
4582 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4583 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4584 ConstantInt *NewCST;
4585 ConstantInt *NewCI;
Reid Spencerc635f472006-12-31 05:48:39 +00004586 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4587 AndCST->getZExtValue());
4588 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4589 CI->getZExtValue());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004590 Instruction *NewAnd =
4591 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4592 LHSI->getName());
4593 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004594 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004595 }
4596 }
4597
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004598 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4599 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4600 // happens a LOT in code produced by the C front-end, for bitfield
4601 // access.
4602 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004603
4604 // Check to see if there is a noop-cast between the shift and the and.
4605 if (!Shift) {
4606 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
Reid Spencer74a528b2006-12-13 18:21:21 +00004607 if (CI->getOpcode() == Instruction::BitCast)
Chris Lattneree0f2802006-02-12 02:07:56 +00004608 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4609 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004610
Reid Spencere0fc4df2006-10-20 07:07:24 +00004611 ConstantInt *ShAmt;
4612 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004613 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4614 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004615
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004616 // We can fold this as long as we can't shift unknown bits
4617 // into the mask. This can only happen with signed shift
4618 // rights, as they sign-extend.
4619 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004620 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004621 if (!CanFold) {
4622 // To test for the bad case of the signed shr, see if any
4623 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004624 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004625 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4626
Reid Spencerc635f472006-12-31 05:48:39 +00004627 Constant *OShAmt = ConstantInt::get(Type::Int8Ty, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004628 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004629 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4630 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004631 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4632 CanFold = true;
4633 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004634
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004635 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004636 Constant *NewCst;
4637 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004638 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004639 else
4640 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004641
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004642 // Check to see if we are shifting out any of the bits being
4643 // compared.
4644 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4645 // If we shifted bits out, the fold is not going to work out.
4646 // As a special case, check to see if this means that the
4647 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004648 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004649 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004650 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004651 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004652 } else {
4653 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004654 Constant *NewAndCST;
4655 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004656 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004657 else
4658 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4659 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00004660 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004661 WorkList.push_back(Shift); // Shift is dead.
4662 AddUsesToWorkList(I);
4663 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004664 }
4665 }
Chris Lattner35167c32004-06-09 07:59:58 +00004666 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004667
4668 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4669 // preferable because it allows the C<<Y expression to be hoisted out
4670 // of a loop if Y is invariant and X is not.
4671 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004672 I.isEquality() && !Shift->isArithmeticShift() &&
4673 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004674 // Compute C << Y.
4675 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004676 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004677 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4678 "tmp");
4679 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004680 // Insert a logical shift.
4681 NS = new ShiftInst(Instruction::LShr, AndCST,
Chris Lattner4922a0e2006-09-18 05:27:43 +00004682 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004683 }
4684 InsertNewInstBefore(cast<Instruction>(NS), I);
4685
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004686 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00004687 Instruction *NewAnd = BinaryOperator::createAnd(
4688 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004689 InsertNewInstBefore(NewAnd, I);
4690
4691 I.setOperand(0, NewAnd);
4692 return &I;
4693 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004694 }
4695 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004696
Reid Spencer266e42b2006-12-23 06:05:41 +00004697 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004698 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004699 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004700 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4701
4702 // Check that the shift amount is in range. If not, don't perform
4703 // undefined shifts. When the shift is visited it will be
4704 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004705 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004706 break;
4707
Chris Lattner272d5ca2004-09-28 18:22:15 +00004708 // If we are comparing against bits always shifted out, the
4709 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004710 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004711 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004712 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004713 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004714 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004715 return ReplaceInstUsesWith(I, Cst);
4716 }
4717
4718 if (LHSI->hasOneUse()) {
4719 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004720 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004721 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc635f472006-12-31 05:48:39 +00004722 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004723
Chris Lattner272d5ca2004-09-28 18:22:15 +00004724 Instruction *AndI =
4725 BinaryOperator::createAnd(LHSI->getOperand(0),
4726 Mask, LHSI->getName()+".mask");
4727 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004728 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004729 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004730 }
4731 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004732 }
4733 break;
4734
Reid Spencer266e42b2006-12-23 06:05:41 +00004735 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004736 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004737 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004738 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004739 // Check that the shift amount is in range. If not, don't perform
4740 // undefined shifts. When the shift is visited it will be
4741 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004742 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004743 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004744 break;
4745
Chris Lattner1023b872004-09-27 16:18:50 +00004746 // If we are comparing against bits always shifted out, the
4747 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004748 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00004749 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00004750 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4751 ShAmt);
4752 else
4753 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4754 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004755
Chris Lattner1023b872004-09-27 16:18:50 +00004756 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004757 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004758 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004759 return ReplaceInstUsesWith(I, Cst);
4760 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004761
Chris Lattner1023b872004-09-27 16:18:50 +00004762 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004763 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004764
Chris Lattner1023b872004-09-27 16:18:50 +00004765 // Otherwise strength reduce the shift into an and.
4766 uint64_t Val = ~0ULL; // All ones.
4767 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc635f472006-12-31 05:48:39 +00004768 Val &= ~0ULL >> (64-TypeBits);
4769 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004770
Chris Lattner1023b872004-09-27 16:18:50 +00004771 Instruction *AndI =
4772 BinaryOperator::createAnd(LHSI->getOperand(0),
4773 Mask, LHSI->getName()+".mask");
4774 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004775 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004776 ConstantExpr::getShl(CI, ShAmt));
4777 }
Chris Lattner1023b872004-09-27 16:18:50 +00004778 }
4779 }
4780 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004781
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004782 case Instruction::SDiv:
4783 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004784 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004785 // Fold this div into the comparison, producing a range check.
4786 // Determine, based on the divide type, what the range is being
4787 // checked. If there is an overflow on the low or high side, remember
4788 // it, otherwise compute the range [low, hi) bounding the new value.
4789 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004790 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004791 // FIXME: If the operand types don't match the type of the divide
4792 // then don't attempt this transform. The code below doesn't have the
4793 // logic to deal with a signed divide and an unsigned compare (and
4794 // vice versa). This is because (x /s C1) <s C2 produces different
4795 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4796 // (x /u C1) <u C2. Simply casting the operands and result won't
4797 // work. :( The if statement below tests that condition and bails
4798 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004799 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4800 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004801 break;
4802
4803 // Initialize the variables that will indicate the nature of the
4804 // range check.
4805 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004806 ConstantInt *LoBound = 0, *HiBound = 0;
4807
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004808 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4809 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4810 // C2 (CI). By solving for X we can turn this into a range check
4811 // instead of computing a divide.
4812 ConstantInt *Prod =
4813 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004814
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004815 // Determine if the product overflows by seeing if the product is
4816 // not equal to the divide. Make sure we do the same kind of divide
4817 // as in the LHS instruction that we're folding.
4818 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00004819 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004820 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4821
Reid Spencer266e42b2006-12-23 06:05:41 +00004822 // Get the ICmp opcode
4823 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004824
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004825 if (DivRHS->isNullValue()) {
4826 // Don't hack on divide by zeros!
Reid Spencer266e42b2006-12-23 06:05:41 +00004827 } else if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004828 LoBound = Prod;
4829 LoOverflow = ProdOV;
4830 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004831 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004832 if (CI->isNullValue()) { // (X / pos) op 0
4833 // Can't overflow.
4834 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4835 HiBound = DivRHS;
4836 } else if (isPositive(CI)) { // (X / pos) op pos
4837 LoBound = Prod;
4838 LoOverflow = ProdOV;
4839 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4840 } else { // (X / pos) op neg
4841 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4842 LoOverflow = AddWithOverflow(LoBound, Prod,
4843 cast<ConstantInt>(DivRHSH));
4844 HiBound = Prod;
4845 HiOverflow = ProdOV;
4846 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004847 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004848 if (CI->isNullValue()) { // (X / neg) op 0
4849 LoBound = AddOne(DivRHS);
4850 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004851 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004852 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004853 } else if (isPositive(CI)) { // (X / neg) op pos
4854 HiOverflow = LoOverflow = ProdOV;
4855 if (!LoOverflow)
4856 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4857 HiBound = AddOne(Prod);
4858 } else { // (X / neg) op neg
4859 LoBound = Prod;
4860 LoOverflow = HiOverflow = ProdOV;
4861 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4862 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004863
Chris Lattnera92af962004-10-11 19:40:04 +00004864 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00004865 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004866 }
4867
4868 if (LoBound) {
4869 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004870 switch (predicate) {
4871 default: assert(0 && "Unhandled icmp opcode!");
4872 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004873 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004874 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004875 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004876 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4877 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004878 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004879 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4880 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004881 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004882 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4883 true, I);
4884 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004885 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004886 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004887 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004888 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4889 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004890 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004891 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4892 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004893 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004894 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4895 false, I);
4896 case ICmpInst::ICMP_ULT:
4897 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004898 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004899 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004900 return new ICmpInst(predicate, X, LoBound);
4901 case ICmpInst::ICMP_UGT:
4902 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004903 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004904 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004905 if (predicate == ICmpInst::ICMP_UGT)
4906 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4907 else
4908 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004909 }
4910 }
4911 }
4912 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004913 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004914
Reid Spencer266e42b2006-12-23 06:05:41 +00004915 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004916 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004917 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004918
Reid Spencere0fc4df2006-10-20 07:07:24 +00004919 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4920 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004921 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4922 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004923 case Instruction::SRem:
4924 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4925 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4926 BO->hasOneUse()) {
4927 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4928 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004929 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4930 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004931 return new ICmpInst(I.getPredicate(), NewRem,
4932 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004933 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004934 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004935 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004936 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004937 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4938 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004939 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004940 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4941 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004942 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004943 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4944 // efficiently invertible, or if the add has just this one use.
4945 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004946
Chris Lattnerc992add2003-08-13 05:33:12 +00004947 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004948 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00004949 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004950 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004951 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004952 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4953 BO->setName("");
4954 InsertNewInstBefore(Neg, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004955 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00004956 }
4957 }
4958 break;
4959 case Instruction::Xor:
4960 // For the xor case, we can xor two constants together, eliminating
4961 // the explicit xor.
4962 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00004963 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4964 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004965
4966 // FALLTHROUGH
4967 case Instruction::Sub:
4968 // Replace (([sub|xor] A, B) != 0) with (A != B)
4969 if (CI->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00004970 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4971 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00004972 break;
4973
4974 case Instruction::Or:
4975 // If bits are being or'd in that are not present in the constant we
4976 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004977 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004978 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004979 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00004980 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4981 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004982 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004983 break;
4984
4985 case Instruction::And:
4986 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004987 // If bits are being compared against that are and'd out, then the
4988 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004989 if (!ConstantExpr::getAnd(CI,
4990 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00004991 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4992 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004993
Chris Lattner35167c32004-06-09 07:59:58 +00004994 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004995 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00004996 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
4997 ICmpInst::ICMP_NE, Op0,
4998 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004999
Reid Spencer266e42b2006-12-23 06:05:41 +00005000 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00005001 if (isSignBit(BOC)) {
5002 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005003 Constant *Zero = Constant::getNullValue(X->getType());
5004 ICmpInst::Predicate pred = isICMP_NE ?
5005 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5006 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005007 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005008
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005009 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005010 if (CI->isNullValue() && isHighOnes(BOC)) {
5011 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005012 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005013 ICmpInst::Predicate pred = isICMP_NE ?
5014 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5015 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005016 }
5017
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005018 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005019 default: break;
5020 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005021 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5022 // Handle set{eq|ne} <intrinsic>, intcst.
5023 switch (II->getIntrinsicID()) {
5024 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005025 case Intrinsic::bswap_i16:
5026 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005027 WorkList.push_back(II); // Dead?
5028 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005029 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005030 ByteSwap_16(CI->getZExtValue())));
5031 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005032 case Intrinsic::bswap_i32:
5033 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005034 WorkList.push_back(II); // Dead?
5035 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005036 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005037 ByteSwap_32(CI->getZExtValue())));
5038 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005039 case Intrinsic::bswap_i64:
5040 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005041 WorkList.push_back(II); // Dead?
5042 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005043 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005044 ByteSwap_64(CI->getZExtValue())));
5045 return &I;
5046 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005047 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005048 } else { // Not a ICMP_EQ/ICMP_NE
5049 // If the LHS is a cast from an integral value of the same size, then
5050 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005051 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5052 Value *CastOp = Cast->getOperand(0);
5053 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005054 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner03c49532007-01-15 02:27:26 +00005055 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005056 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005057 // If this is an unsigned comparison, try to make the comparison use
5058 // smaller constant values.
5059 switch (I.getPredicate()) {
5060 default: break;
5061 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5062 ConstantInt *CUI = cast<ConstantInt>(CI);
5063 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5064 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5065 ConstantInt::get(SrcTy, -1));
5066 break;
5067 }
5068 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5069 ConstantInt *CUI = cast<ConstantInt>(CI);
5070 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5071 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5072 Constant::getNullValue(SrcTy));
5073 break;
5074 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005075 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005076
Chris Lattner2b55ea32004-02-23 07:16:20 +00005077 }
5078 }
Chris Lattnere967b342003-06-04 05:10:11 +00005079 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005080 }
5081
Reid Spencer266e42b2006-12-23 06:05:41 +00005082 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005083 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5084 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5085 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005086 case Instruction::GetElementPtr:
5087 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005088 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005089 bool isAllZeros = true;
5090 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5091 if (!isa<Constant>(LHSI->getOperand(i)) ||
5092 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5093 isAllZeros = false;
5094 break;
5095 }
5096 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005097 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005098 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5099 }
5100 break;
5101
Chris Lattner77c32c32005-04-23 15:31:55 +00005102 case Instruction::PHI:
5103 if (Instruction *NV = FoldOpIntoPhi(I))
5104 return NV;
5105 break;
5106 case Instruction::Select:
5107 // If either operand of the select is a constant, we can fold the
5108 // comparison into the select arms, which will cause one to be
5109 // constant folded and the select turned into a bitwise or.
5110 Value *Op1 = 0, *Op2 = 0;
5111 if (LHSI->hasOneUse()) {
5112 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5113 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005114 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5115 // Insert a new ICmp of the other select operand.
5116 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5117 LHSI->getOperand(2), RHSC,
5118 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005119 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5120 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005121 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5122 // Insert a new ICmp of the other select operand.
5123 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5124 LHSI->getOperand(1), RHSC,
5125 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005126 }
5127 }
Jeff Cohen82639852005-04-23 21:38:35 +00005128
Chris Lattner77c32c32005-04-23 15:31:55 +00005129 if (Op1)
5130 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5131 break;
5132 }
5133 }
5134
Reid Spencer266e42b2006-12-23 06:05:41 +00005135 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005136 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005137 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005138 return NI;
5139 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005140 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5141 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005142 return NI;
5143
Reid Spencer266e42b2006-12-23 06:05:41 +00005144 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005145 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5146 // now.
5147 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5148 if (isa<PointerType>(Op0->getType()) &&
5149 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005150 // We keep moving the cast from the left operand over to the right
5151 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005152 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005153
Chris Lattner64d87b02007-01-06 01:45:59 +00005154 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5155 // so eliminate it as well.
5156 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5157 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005158
Chris Lattner16930792003-11-03 04:25:02 +00005159 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005160 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005161 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005162 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005163 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005164 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005165 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005166 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005167 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005168 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005169 }
5170
5171 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005172 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005173 // This comes up when you have code like
5174 // int X = A < B;
5175 // if (X) ...
5176 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005177 // with a constant or another cast from the same type.
5178 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005179 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005180 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005181 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005182
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005183 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005184 Value *A, *B, *C, *D;
5185 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5186 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5187 Value *OtherVal = A == Op1 ? B : A;
5188 return new ICmpInst(I.getPredicate(), OtherVal,
5189 Constant::getNullValue(A->getType()));
5190 }
5191
5192 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5193 // A^c1 == C^c2 --> A == C^(c1^c2)
5194 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5195 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5196 if (Op1->hasOneUse()) {
5197 Constant *NC = ConstantExpr::getXor(C1, C2);
5198 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5199 return new ICmpInst(I.getPredicate(), A,
5200 InsertNewInstBefore(Xor, I));
5201 }
5202
5203 // A^B == A^D -> B == D
5204 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5205 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5206 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5207 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5208 }
5209 }
5210
5211 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5212 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005213 // A == (A^B) -> B == 0
5214 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005215 return new ICmpInst(I.getPredicate(), OtherVal,
5216 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005217 }
5218 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005219 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005220 return new ICmpInst(I.getPredicate(), B,
5221 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005222 }
5223 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005224 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005225 return new ICmpInst(I.getPredicate(), B,
5226 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005227 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005228
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005229 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5230 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5231 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5232 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5233 Value *X = 0, *Y = 0, *Z = 0;
5234
5235 if (A == C) {
5236 X = B; Y = D; Z = A;
5237 } else if (A == D) {
5238 X = B; Y = C; Z = A;
5239 } else if (B == C) {
5240 X = A; Y = D; Z = B;
5241 } else if (B == D) {
5242 X = A; Y = C; Z = B;
5243 }
5244
5245 if (X) { // Build (X^Y) & Z
5246 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5247 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5248 I.setOperand(0, Op1);
5249 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5250 return &I;
5251 }
5252 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005253 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005254 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005255}
5256
Reid Spencer266e42b2006-12-23 06:05:41 +00005257// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005258// We only handle extending casts so far.
5259//
Reid Spencer266e42b2006-12-23 06:05:41 +00005260Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5261 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005262 Value *LHSCIOp = LHSCI->getOperand(0);
5263 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005264 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005265 Value *RHSCIOp;
5266
Reid Spencer266e42b2006-12-23 06:05:41 +00005267 // We only handle extension cast instructions, so far. Enforce this.
5268 if (LHSCI->getOpcode() != Instruction::ZExt &&
5269 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005270 return 0;
5271
Reid Spencer266e42b2006-12-23 06:05:41 +00005272 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5273 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005274
Reid Spencer266e42b2006-12-23 06:05:41 +00005275 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005276 // Not an extension from the same type?
5277 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005278 if (RHSCIOp->getType() != LHSCIOp->getType())
5279 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005280
5281 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5282 // and the other is a zext), then we can't handle this.
5283 if (CI->getOpcode() != LHSCI->getOpcode())
5284 return 0;
5285
5286 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5287 // then we can't handle this.
5288 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5289 return 0;
5290
5291 // Okay, just insert a compare of the reduced operands now!
5292 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005293 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005294
Reid Spencer266e42b2006-12-23 06:05:41 +00005295 // If we aren't dealing with a constant on the RHS, exit early
5296 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5297 if (!CI)
5298 return 0;
5299
5300 // Compute the constant that would happen if we truncated to SrcTy then
5301 // reextended to DestTy.
5302 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5303 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5304
5305 // If the re-extended constant didn't change...
5306 if (Res2 == CI) {
5307 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5308 // For example, we might have:
5309 // %A = sext short %X to uint
5310 // %B = icmp ugt uint %A, 1330
5311 // It is incorrect to transform this into
5312 // %B = icmp ugt short %X, 1330
5313 // because %A may have negative value.
5314 //
5315 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5316 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005317 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005318 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5319 else
5320 return 0;
5321 }
5322
5323 // The re-extended constant changed so the constant cannot be represented
5324 // in the shorter type. Consequently, we cannot emit a simple comparison.
5325
5326 // First, handle some easy cases. We know the result cannot be equal at this
5327 // point so handle the ICI.isEquality() cases
5328 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005329 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005330 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005331 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005332
5333 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5334 // should have been folded away previously and not enter in here.
5335 Value *Result;
5336 if (isSignedCmp) {
5337 // We're performing a signed comparison.
5338 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005339 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005340 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005341 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005342 } else {
5343 // We're performing an unsigned comparison.
5344 if (isSignedExt) {
5345 // We're performing an unsigned comp with a sign extended value.
5346 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005347 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005348 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5349 NegOne, ICI.getName()), ICI);
5350 } else {
5351 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005352 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005353 }
5354 }
5355
5356 // Finally, return the value computed.
5357 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5358 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5359 return ReplaceInstUsesWith(ICI, Result);
5360 } else {
5361 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5362 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5363 "ICmp should be folded!");
5364 if (Constant *CI = dyn_cast<Constant>(Result))
5365 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5366 else
5367 return BinaryOperator::createNot(Result);
5368 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005369}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005370
Chris Lattnere8d6c602003-03-10 19:16:08 +00005371Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Reid Spencerc635f472006-12-31 05:48:39 +00005372 assert(I.getOperand(1)->getType() == Type::Int8Ty);
Chris Lattner113f4f42002-06-25 16:13:24 +00005373 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005374
5375 // shl X, 0 == X and shr X, 0 == X
5376 // shl 0, X == 0 and shr 0, X == 0
Reid Spencerc635f472006-12-31 05:48:39 +00005377 if (Op1 == Constant::getNullValue(Type::Int8Ty) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005378 Op0 == Constant::getNullValue(Op0->getType()))
5379 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005380
Reid Spencer266e42b2006-12-23 06:05:41 +00005381 if (isa<UndefValue>(Op0)) {
5382 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005383 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005384 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005385 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5386 }
5387 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005388 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5389 return ReplaceInstUsesWith(I, Op0);
5390 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005391 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005392 }
5393
Chris Lattnerd4dee402006-11-10 23:38:52 +00005394 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5395 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005396 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005397 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005398 return ReplaceInstUsesWith(I, CSI);
5399
Chris Lattner183b3362004-04-09 19:05:30 +00005400 // Try to fold constant and into select arguments.
5401 if (isa<Constant>(Op0))
5402 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005403 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005404 return R;
5405
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005406 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005407 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005408 if (MaskedValueIsZero(Op0,
5409 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005410 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005411 }
5412 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005413
Reid Spencere0fc4df2006-10-20 07:07:24 +00005414 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005415 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5416 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005417 return 0;
5418}
5419
Reid Spencere0fc4df2006-10-20 07:07:24 +00005420Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005421 ShiftInst &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005422 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5423 bool isSignedShift = I.getOpcode() == Instruction::AShr;
Chris Lattnerb3309392006-01-06 07:22:22 +00005424 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005425
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005426 // See if we can simplify any instructions used by the instruction whose sole
5427 // purpose is to compute bits we don't care about.
5428 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00005429 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005430 KnownZero, KnownOne))
5431 return &I;
5432
Chris Lattner14553932006-01-06 07:12:35 +00005433 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5434 // of a signed value.
5435 //
5436 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005437 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005438 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005439 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5440 else {
Reid Spencerc635f472006-12-31 05:48:39 +00005441 I.setOperand(1, ConstantInt::get(Type::Int8Ty, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005442 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005443 }
Chris Lattner14553932006-01-06 07:12:35 +00005444 }
5445
5446 // ((X*C1) << C2) == (X * (C1 << C2))
5447 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5448 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5449 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5450 return BinaryOperator::createMul(BO->getOperand(0),
5451 ConstantExpr::getShl(BOOp, Op1));
5452
5453 // Try to fold constant and into select arguments.
5454 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5455 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5456 return R;
5457 if (isa<PHINode>(Op0))
5458 if (Instruction *NV = FoldOpIntoPhi(I))
5459 return NV;
5460
5461 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005462 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5463 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5464 Value *V1, *V2;
5465 ConstantInt *CC;
5466 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005467 default: break;
5468 case Instruction::Add:
5469 case Instruction::And:
5470 case Instruction::Or:
5471 case Instruction::Xor:
5472 // These operators commute.
5473 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005474 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5475 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005476 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005477 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005478 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005479 Op0BO->getName());
5480 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005481 Instruction *X =
5482 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5483 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005484 InsertNewInstBefore(X, I); // (X + (Y << C))
5485 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005486 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005487 return BinaryOperator::createAnd(X, C2);
5488 }
Chris Lattner14553932006-01-06 07:12:35 +00005489
Chris Lattner797dee72005-09-18 06:30:59 +00005490 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5491 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5492 match(Op0BO->getOperand(1),
5493 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005494 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005495 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005496 Instruction *YS = new ShiftInst(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)
5500 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005501 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005502 V1->getName()+".mask");
5503 InsertNewInstBefore(XM, I); // X & (CC << C)
5504
5505 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5506 }
Chris Lattner14553932006-01-06 07:12:35 +00005507
Chris Lattner797dee72005-09-18 06:30:59 +00005508 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005509 case Instruction::Sub:
5510 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005511 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5512 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005513 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005514 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005515 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005516 Op0BO->getName());
5517 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005518 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005519 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005520 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005521 InsertNewInstBefore(X, I); // (X + (Y << C))
5522 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005523 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005524 return BinaryOperator::createAnd(X, C2);
5525 }
Chris Lattner14553932006-01-06 07:12:35 +00005526
Chris Lattner1df0e982006-05-31 21:14:00 +00005527 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005528 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5529 match(Op0BO->getOperand(0),
5530 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005531 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005532 cast<BinaryOperator>(Op0BO->getOperand(0))
5533 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005534 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005535 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005536 Op0BO->getName());
5537 InsertNewInstBefore(YS, I); // (Y << C)
5538 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005539 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005540 V1->getName()+".mask");
5541 InsertNewInstBefore(XM, I); // X & (CC << C)
5542
Chris Lattner1df0e982006-05-31 21:14:00 +00005543 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005544 }
Chris Lattner14553932006-01-06 07:12:35 +00005545
Chris Lattner27cb9db2005-09-18 05:12:10 +00005546 break;
Chris Lattner14553932006-01-06 07:12:35 +00005547 }
5548
5549
5550 // If the operand is an bitwise operator with a constant RHS, and the
5551 // shift is the only use, we can pull it out of the shift.
5552 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5553 bool isValid = true; // Valid only for And, Or, Xor
5554 bool highBitSet = false; // Transform if high bit of constant set?
5555
5556 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005557 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005558 case Instruction::Add:
5559 isValid = isLeftShift;
5560 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005561 case Instruction::Or:
5562 case Instruction::Xor:
5563 highBitSet = false;
5564 break;
5565 case Instruction::And:
5566 highBitSet = true;
5567 break;
Chris Lattner14553932006-01-06 07:12:35 +00005568 }
5569
5570 // If this is a signed shift right, and the high bit is modified
5571 // by the logical operation, do not perform the transformation.
5572 // The highBitSet boolean indicates the value of the high bit of
5573 // the constant which would cause it to be modified for this
5574 // operation.
5575 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005576 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005577 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005578 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5579 }
5580
5581 if (isValid) {
5582 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5583
5584 Instruction *NewShift =
5585 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5586 Op0BO->getName());
5587 Op0BO->setName("");
5588 InsertNewInstBefore(NewShift, I);
5589
5590 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5591 NewRHS);
5592 }
5593 }
5594 }
5595 }
5596
Chris Lattnereb372a02006-01-06 07:52:12 +00005597 // Find out if this is a shift of a shift by a constant.
5598 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005599 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005600 ShiftOp = Op0SI;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005601 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5602 // If this is a noop-integer cast of a shift instruction, use the shift.
5603 if (isa<ShiftInst>(CI->getOperand(0))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005604 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5605 }
5606 }
5607
Reid Spencere0fc4df2006-10-20 07:07:24 +00005608 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005609 // Find the operands and properties of the input shift. Note that the
5610 // signedness of the input shift may differ from the current shift if there
5611 // is a noop cast between the two.
Reid Spencer266e42b2006-12-23 06:05:41 +00005612 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5613 bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005614 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005615
Reid Spencere0fc4df2006-10-20 07:07:24 +00005616 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005617
Reid Spencere0fc4df2006-10-20 07:07:24 +00005618 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5619 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005620
5621 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5622 if (isLeftShift == isShiftOfLeftShift) {
5623 // Do not fold these shifts if the first one is signed and the second one
5624 // is unsigned and this is a right shift. Further, don't do any folding
5625 // on them.
5626 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5627 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005628
Chris Lattnereb372a02006-01-06 07:52:12 +00005629 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5630 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5631 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005632
Chris Lattnereb372a02006-01-06 07:52:12 +00005633 Value *Op = ShiftOp->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005634 ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
Reid Spencerc635f472006-12-31 05:48:39 +00005635 ConstantInt::get(Type::Int8Ty, Amt));
Reid Spencerfdff9382006-11-08 06:47:33 +00005636 if (I.getType() == ShiftResult->getType())
5637 return ShiftResult;
5638 InsertNewInstBefore(ShiftResult, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005639 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005640 }
5641
5642 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5643 // signed types, we can only support the (A >> c1) << c2 configuration,
5644 // because it can not turn an arbitrary bit of A into a sign bit.
5645 if (isUnsignedShift || isLeftShift) {
5646 // Calculate bitmask for what gets shifted off the edge.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005647 Constant *C = ConstantInt::getAllOnesValue(I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005648 if (isLeftShift)
5649 C = ConstantExpr::getShl(C, ShiftAmt1C);
5650 else
Reid Spencerfdff9382006-11-08 06:47:33 +00005651 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005652
5653 Value *Op = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005654
5655 Instruction *Mask =
5656 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5657 InsertNewInstBefore(Mask, I);
5658
5659 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005660 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005661 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005662 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005663 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005664 ConstantInt::get(Type::Int8Ty, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005665 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5666 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005667 return new ShiftInst(Instruction::LShr, Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005668 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005669 } else {
5670 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005671 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005672 }
5673 } else {
5674 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005675 Instruction *Shift =
Reid Spencer2a499b02006-12-13 17:19:09 +00005676 new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005677 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005678 InsertNewInstBefore(Shift, I);
5679
Zhou Sheng75b871f2007-01-11 12:24:14 +00005680 C = ConstantInt::getAllOnesValue(Shift->getType());
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005681 C = ConstantExpr::getShl(C, Op1);
Reid Spencer2a499b02006-12-13 17:19:09 +00005682 return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
Chris Lattnereb372a02006-01-06 07:52:12 +00005683 }
5684 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005685 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005686 // this case, C1 == C2 and C1 is 8, 16, or 32.
5687 if (ShiftAmt1 == ShiftAmt2) {
5688 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005689 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Reid Spencerc635f472006-12-31 05:48:39 +00005690 case 8 : SExtType = Type::Int8Ty; break;
5691 case 16: SExtType = Type::Int16Ty; break;
5692 case 32: SExtType = Type::Int32Ty; break;
Chris Lattnereb372a02006-01-06 07:52:12 +00005693 }
5694
5695 if (SExtType) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005696 Instruction *NewTrunc =
5697 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
Chris Lattnereb372a02006-01-06 07:52:12 +00005698 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005699 return new SExtInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005700 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005701 }
Chris Lattner86102b82005-01-01 16:22:27 +00005702 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005703 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005704 return 0;
5705}
5706
Chris Lattner48a44f72002-05-02 17:06:02 +00005707
Chris Lattner8f663e82005-10-29 04:36:15 +00005708/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5709/// expression. If so, decompose it, returning some value X, such that Val is
5710/// X*Scale+Offset.
5711///
5712static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5713 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00005714 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005715 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00005716 Offset = CI->getZExtValue();
5717 Scale = 1;
5718 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00005719 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5720 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005721 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00005722 if (I->getOpcode() == Instruction::Shl) {
5723 // This is a value scaled by '1 << the shift amt'.
5724 Scale = 1U << CUI->getZExtValue();
5725 Offset = 0;
5726 return I->getOperand(0);
5727 } else if (I->getOpcode() == Instruction::Mul) {
5728 // This value is scaled by 'CUI'.
5729 Scale = CUI->getZExtValue();
5730 Offset = 0;
5731 return I->getOperand(0);
5732 } else if (I->getOpcode() == Instruction::Add) {
5733 // We have X+C. Check to see if we really have (X*C2)+C1,
5734 // where C1 is divisible by C2.
5735 unsigned SubScale;
5736 Value *SubVal =
5737 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5738 Offset += CUI->getZExtValue();
5739 if (SubScale > 1 && (Offset % SubScale == 0)) {
5740 Scale = SubScale;
5741 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00005742 }
5743 }
5744 }
5745 }
5746 }
5747
5748 // Otherwise, we can't look past this.
5749 Scale = 1;
5750 Offset = 0;
5751 return Val;
5752}
5753
5754
Chris Lattner216be912005-10-24 06:03:58 +00005755/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5756/// try to eliminate the cast by moving the type information into the alloc.
5757Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5758 AllocationInst &AI) {
5759 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005760 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005761
Chris Lattnerac87beb2005-10-24 06:22:12 +00005762 // Remove any uses of AI that are dead.
5763 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5764 std::vector<Instruction*> DeadUsers;
5765 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5766 Instruction *User = cast<Instruction>(*UI++);
5767 if (isInstructionTriviallyDead(User)) {
5768 while (UI != E && *UI == User)
5769 ++UI; // If this instruction uses AI more than once, don't break UI.
5770
5771 // Add operands to the worklist.
5772 AddUsesToWorkList(*User);
5773 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005774 DOUT << "IC: DCE: " << *User;
Chris Lattnerac87beb2005-10-24 06:22:12 +00005775
5776 User->eraseFromParent();
5777 removeFromWorkList(User);
5778 }
5779 }
5780
Chris Lattner216be912005-10-24 06:03:58 +00005781 // Get the type really allocated and the type casted to.
5782 const Type *AllocElTy = AI.getAllocatedType();
5783 const Type *CastElTy = PTy->getElementType();
5784 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005785
Chris Lattner50ee0e42007-01-20 22:35:55 +00005786 unsigned AllocElTyAlign = TD->getTypeAlignmentABI(AllocElTy);
5787 unsigned CastElTyAlign = TD->getTypeAlignmentABI(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005788 if (CastElTyAlign < AllocElTyAlign) return 0;
5789
Chris Lattner46705b22005-10-24 06:35:18 +00005790 // If the allocation has multiple uses, only promote it if we are strictly
5791 // increasing the alignment of the resultant allocation. If we keep it the
5792 // same, we open the door to infinite loops of various kinds.
5793 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5794
Chris Lattner216be912005-10-24 06:03:58 +00005795 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5796 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005797 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005798
Chris Lattner8270c332005-10-29 03:19:53 +00005799 // See if we can satisfy the modulus by pulling a scale out of the array
5800 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005801 unsigned ArraySizeScale, ArrayOffset;
5802 Value *NumElements = // See if the array size is a decomposable linear expr.
5803 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5804
Chris Lattner8270c332005-10-29 03:19:53 +00005805 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5806 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005807 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5808 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005809
Chris Lattner8270c332005-10-29 03:19:53 +00005810 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5811 Value *Amt = 0;
5812 if (Scale == 1) {
5813 Amt = NumElements;
5814 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005815 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00005816 Amt = ConstantInt::get(Type::Int32Ty, Scale);
5817 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00005818 Amt = ConstantExpr::getMul(
5819 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5820 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005821 else if (Scale != 1) {
5822 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5823 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005824 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005825 }
5826
Chris Lattner8f663e82005-10-29 04:36:15 +00005827 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00005828 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005829 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5830 Amt = InsertNewInstBefore(Tmp, AI);
5831 }
5832
Chris Lattner216be912005-10-24 06:03:58 +00005833 std::string Name = AI.getName(); AI.setName("");
5834 AllocationInst *New;
5835 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005836 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005837 else
Nate Begeman848622f2005-11-05 09:21:28 +00005838 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005839 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005840
5841 // If the allocation has multiple uses, insert a cast and change all things
5842 // that used it to use the new cast. This will also hack on CI, but it will
5843 // die soon.
5844 if (!AI.hasOneUse()) {
5845 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005846 // New is the allocation instruction, pointer typed. AI is the original
5847 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5848 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00005849 InsertNewInstBefore(NewCast, AI);
5850 AI.replaceAllUsesWith(NewCast);
5851 }
Chris Lattner216be912005-10-24 06:03:58 +00005852 return ReplaceInstUsesWith(CI, New);
5853}
5854
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005855/// CanEvaluateInDifferentType - Return true if we can take the specified value
5856/// and return it without inserting any new casts. This is used by code that
5857/// tries to decide whether promoting or shrinking integer operations to wider
5858/// or smaller types will allow us to eliminate a truncate or extend.
5859static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5860 int &NumCastsRemoved) {
5861 if (isa<Constant>(V)) return true;
5862
5863 Instruction *I = dyn_cast<Instruction>(V);
5864 if (!I || !I->hasOneUse()) return false;
5865
5866 switch (I->getOpcode()) {
5867 case Instruction::And:
5868 case Instruction::Or:
5869 case Instruction::Xor:
5870 // These operators can all arbitrarily be extended or truncated.
5871 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5872 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattner960acb02006-11-29 07:18:39 +00005873 case Instruction::AShr:
5874 case Instruction::LShr:
5875 case Instruction::Shl:
5876 // If this is just a bitcast changing the sign of the operation, we can
5877 // convert if the operand can be converted.
5878 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5879 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5880 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005881 case Instruction::Trunc:
5882 case Instruction::ZExt:
5883 case Instruction::SExt:
5884 case Instruction::BitCast:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005885 // If this is a cast from the destination type, we can trivially eliminate
5886 // it, and this will remove a cast overall.
5887 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005888 // If the first operand is itself a cast, and is eliminable, do not count
5889 // this as an eliminable cast. We would prefer to eliminate those two
5890 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005891 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005892 return true;
5893
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005894 ++NumCastsRemoved;
5895 return true;
5896 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005897 break;
5898 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005899 // TODO: Can handle more cases here.
5900 break;
5901 }
5902
5903 return false;
5904}
5905
5906/// EvaluateInDifferentType - Given an expression that
5907/// CanEvaluateInDifferentType returns true for, actually insert the code to
5908/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00005909Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
5910 bool isSigned ) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005911 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00005912 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005913
5914 // Otherwise, it must be an instruction.
5915 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005916 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005917 switch (I->getOpcode()) {
5918 case Instruction::And:
5919 case Instruction::Or:
5920 case Instruction::Xor: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005921 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5922 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005923 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5924 LHS, RHS, I->getName());
5925 break;
5926 }
Chris Lattner960acb02006-11-29 07:18:39 +00005927 case Instruction::AShr:
5928 case Instruction::LShr:
5929 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005930 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattner960acb02006-11-29 07:18:39 +00005931 Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5932 I->getOperand(1), I->getName());
5933 break;
5934 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005935 case Instruction::Trunc:
5936 case Instruction::ZExt:
5937 case Instruction::SExt:
5938 case Instruction::BitCast:
5939 // If the source type of the cast is the type we're trying for then we can
5940 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005941 if (I->getOperand(0)->getType() == Ty)
5942 return I->getOperand(0);
5943
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005944 // Some other kind of cast, which shouldn't happen, so just ..
5945 // FALL THROUGH
5946 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005947 // TODO: Can handle more cases here.
5948 assert(0 && "Unreachable!");
5949 break;
5950 }
5951
5952 return InsertNewInstBefore(Res, *I);
5953}
5954
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005955/// @brief Implement the transforms common to all CastInst visitors.
5956Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005957 Value *Src = CI.getOperand(0);
5958
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005959 // Casting undef to anything results in undef so might as just replace it and
5960 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00005961 if (isa<UndefValue>(Src)) // cast undef -> undef
5962 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5963
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005964 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5965 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00005966 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005967 if (Instruction::CastOps opc =
5968 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5969 // The first cast (CSrc) is eliminable so we need to fix up or replace
5970 // the second cast (CI). CSrc will then have a good chance of being dead.
5971 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00005972 }
5973 }
Chris Lattner03841652004-05-25 04:29:21 +00005974
Chris Lattnerd0d51602003-06-21 23:12:02 +00005975 // If casting the result of a getelementptr instruction with no offset, turn
5976 // this into a cast of the original pointer!
5977 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005978 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005979 bool AllZeroOperands = true;
5980 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5981 if (!isa<Constant>(GEP->getOperand(i)) ||
5982 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5983 AllZeroOperands = false;
5984 break;
5985 }
5986 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005987 // Changing the cast operand is usually not a good idea but it is safe
5988 // here because the pointer operand is being replaced with another
5989 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00005990 CI.setOperand(0, GEP->getOperand(0));
5991 return &CI;
5992 }
5993 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00005994
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005995 // If we are casting a malloc or alloca to a pointer to a type of the same
5996 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005997 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005998 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5999 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006000
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006001 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006002 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6003 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6004 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006005
6006 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006007 if (isa<PHINode>(Src))
6008 if (Instruction *NV = FoldOpIntoPhi(CI))
6009 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006010
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006011 return 0;
6012}
6013
6014/// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
6015/// integers. This function implements the common transforms for all those
6016/// cases.
6017/// @brief Implement the transforms common to CastInst with integer operands
6018Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6019 if (Instruction *Result = commonCastTransforms(CI))
6020 return Result;
6021
6022 Value *Src = CI.getOperand(0);
6023 const Type *SrcTy = Src->getType();
6024 const Type *DestTy = CI.getType();
6025 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6026 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6027
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006028 // See if we can simplify any instructions used by the LHS whose sole
6029 // purpose is to compute bits we don't care about.
6030 uint64_t KnownZero = 0, KnownOne = 0;
Reid Spencera94d3942007-01-19 21:13:56 +00006031 if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006032 KnownZero, KnownOne))
6033 return &CI;
6034
6035 // If the source isn't an instruction or has more than one use then we
6036 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006037 Instruction *SrcI = dyn_cast<Instruction>(Src);
6038 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006039 return 0;
6040
6041 // Attempt to propagate the cast into the instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006042 int NumCastsRemoved = 0;
6043 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6044 // If this cast is a truncate, evaluting in a different type always
6045 // eliminates the cast, so it is always a win. If this is a noop-cast
6046 // this just removes a noop cast which isn't pointful, but simplifies
6047 // the code. If this is a zero-extension, we need to do an AND to
6048 // maintain the clear top-part of the computation, so we require that
6049 // the input have eliminated at least one cast. If this is a sign
6050 // extension, we insert two new casts (to do the extension) so we
6051 // require that two casts have been eliminated.
6052 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6053 if (!DoXForm) {
6054 switch (CI.getOpcode()) {
6055 case Instruction::Trunc:
6056 DoXForm = true;
6057 break;
6058 case Instruction::ZExt:
6059 DoXForm = NumCastsRemoved >= 1;
6060 break;
6061 case Instruction::SExt:
6062 DoXForm = NumCastsRemoved >= 2;
6063 break;
6064 case Instruction::BitCast:
6065 DoXForm = false;
6066 break;
6067 default:
6068 // All the others use floating point so we shouldn't actually
6069 // get here because of the check above.
6070 assert(!"Unknown cast type .. unreachable");
6071 break;
6072 }
6073 }
6074
6075 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006076 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6077 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006078 assert(Res->getType() == DestTy);
6079 switch (CI.getOpcode()) {
6080 default: assert(0 && "Unknown cast type!");
6081 case Instruction::Trunc:
6082 case Instruction::BitCast:
6083 // Just replace this cast with the result.
6084 return ReplaceInstUsesWith(CI, Res);
6085 case Instruction::ZExt: {
6086 // We need to emit an AND to clear the high bits.
6087 assert(SrcBitSize < DestBitSize && "Not a zext?");
6088 Constant *C =
Reid Spencerc635f472006-12-31 05:48:39 +00006089 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006090 if (DestBitSize < 64)
6091 C = ConstantExpr::getTrunc(C, DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006092 return BinaryOperator::createAnd(Res, C);
6093 }
6094 case Instruction::SExt:
6095 // We need to emit a cast to truncate, then a cast to sext.
6096 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006097 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6098 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006099 }
6100 }
6101 }
6102
6103 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6104 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6105
6106 switch (SrcI->getOpcode()) {
6107 case Instruction::Add:
6108 case Instruction::Mul:
6109 case Instruction::And:
6110 case Instruction::Or:
6111 case Instruction::Xor:
6112 // If we are discarding information, or just changing the sign,
6113 // rewrite.
6114 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6115 // Don't insert two casts if they cannot be eliminated. We allow
6116 // two casts to be inserted if the sizes are the same. This could
6117 // only be converting signedness, which is a noop.
6118 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006119 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6120 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006121 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006122 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6123 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6124 return BinaryOperator::create(
6125 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006126 }
6127 }
6128
6129 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6130 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6131 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006132 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006133 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006134 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006135 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6136 }
6137 break;
6138 case Instruction::SDiv:
6139 case Instruction::UDiv:
6140 case Instruction::SRem:
6141 case Instruction::URem:
6142 // If we are just changing the sign, rewrite.
6143 if (DestBitSize == SrcBitSize) {
6144 // Don't insert two casts if they cannot be eliminated. We allow
6145 // two casts to be inserted if the sizes are the same. This could
6146 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006147 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6148 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006149 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6150 Op0, DestTy, SrcI);
6151 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6152 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006153 return BinaryOperator::create(
6154 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6155 }
6156 }
6157 break;
6158
6159 case Instruction::Shl:
6160 // Allow changing the sign of the source operand. Do not allow
6161 // changing the size of the shift, UNLESS the shift amount is a
6162 // constant. We must not change variable sized shifts to a smaller
6163 // size, because it is undefined to shift more bits out than exist
6164 // in the value.
6165 if (DestBitSize == SrcBitSize ||
6166 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006167 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6168 Instruction::BitCast : Instruction::Trunc);
6169 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006170 return new ShiftInst(Instruction::Shl, Op0c, Op1);
6171 }
6172 break;
6173 case Instruction::AShr:
6174 // If this is a signed shr, and if all bits shifted in are about to be
6175 // truncated off, turn it into an unsigned shr to allow greater
6176 // simplifications.
6177 if (DestBitSize < SrcBitSize &&
6178 isa<ConstantInt>(Op1)) {
6179 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6180 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6181 // Insert the new logical shift right.
6182 return new ShiftInst(Instruction::LShr, Op0, Op1);
6183 }
6184 }
6185 break;
6186
Reid Spencer266e42b2006-12-23 06:05:41 +00006187 case Instruction::ICmp:
6188 // If we are just checking for a icmp eq of a single bit and casting it
6189 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006190 // cast to integer to avoid the comparison.
6191 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6192 uint64_t Op1CV = Op1C->getZExtValue();
6193 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6194 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6195 // cast (X == 1) to int --> X iff X has only the low bit set.
6196 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6197 // cast (X != 0) to int --> X iff X has only the low bit set.
6198 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6199 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6200 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6201 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6202 // If Op1C some other power of two, convert:
6203 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00006204 uint64_t TypeMask = Op1C->getType()->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006205 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006206
6207 // This only works for EQ and NE
6208 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6209 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6210 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006211
6212 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006213 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006214 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6215 // (X&4) == 2 --> false
6216 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00006217 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006218 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006219 return ReplaceInstUsesWith(CI, Res);
6220 }
6221
6222 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6223 Value *In = Op0;
6224 if (ShiftAmt) {
6225 // Perform a logical shr by shiftamt.
6226 // Insert the shift to put the result in the low bit.
6227 In = InsertNewInstBefore(
6228 new ShiftInst(Instruction::LShr, In,
Reid Spencerc635f472006-12-31 05:48:39 +00006229 ConstantInt::get(Type::Int8Ty, ShiftAmt),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006230 In->getName()+".lobit"), CI);
6231 }
6232
Reid Spencer266e42b2006-12-23 06:05:41 +00006233 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006234 Constant *One = ConstantInt::get(In->getType(), 1);
6235 In = BinaryOperator::createXor(In, One, "tmp");
6236 InsertNewInstBefore(cast<Instruction>(In), CI);
6237 }
6238
6239 if (CI.getType() == In->getType())
6240 return ReplaceInstUsesWith(CI, In);
6241 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006242 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006243 }
6244 }
6245 }
6246 break;
6247 }
6248 return 0;
6249}
6250
6251Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006252 if (Instruction *Result = commonIntCastTransforms(CI))
6253 return Result;
6254
6255 Value *Src = CI.getOperand(0);
6256 const Type *Ty = CI.getType();
6257 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6258
6259 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6260 switch (SrcI->getOpcode()) {
6261 default: break;
6262 case Instruction::LShr:
6263 // We can shrink lshr to something smaller if we know the bits shifted in
6264 // are already zeros.
6265 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6266 unsigned ShAmt = ShAmtV->getZExtValue();
6267
6268 // Get a mask for the bits shifting in.
6269 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006270 Value* SrcIOp0 = SrcI->getOperand(0);
6271 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006272 if (ShAmt >= DestBitWidth) // All zeros.
6273 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6274
6275 // Okay, we can shrink this. Truncate the input, then return a new
6276 // shift.
Reid Spencer2a499b02006-12-13 17:19:09 +00006277 Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
Chris Lattnerd747f012006-11-29 07:04:07 +00006278 return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6279 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006280 } else { // This is a variable shr.
6281
6282 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6283 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6284 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006285 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006286 Value *One = ConstantInt::get(SrcI->getType(), 1);
6287
6288 Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6289 SrcI->getOperand(1),
6290 "tmp"), CI);
6291 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6292 SrcI->getOperand(0),
6293 "tmp"), CI);
6294 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006295 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006296 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006297 }
6298 break;
6299 }
6300 }
6301
6302 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006303}
6304
6305Instruction *InstCombiner::visitZExt(CastInst &CI) {
6306 // If one of the common conversion will work ..
6307 if (Instruction *Result = commonIntCastTransforms(CI))
6308 return Result;
6309
6310 Value *Src = CI.getOperand(0);
6311
6312 // If this is a cast of a cast
6313 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006314 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6315 // types and if the sizes are just right we can convert this into a logical
6316 // 'and' which will be much cheaper than the pair of casts.
6317 if (isa<TruncInst>(CSrc)) {
6318 // Get the sizes of the types involved
6319 Value *A = CSrc->getOperand(0);
6320 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6321 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6322 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6323 // If we're actually extending zero bits and the trunc is a no-op
6324 if (MidSize < DstSize && SrcSize == DstSize) {
6325 // Replace both of the casts with an And of the type mask.
Reid Spencera94d3942007-01-19 21:13:56 +00006326 uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006327 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6328 Instruction *And =
6329 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6330 // Unfortunately, if the type changed, we need to cast it back.
6331 if (And->getType() != CI.getType()) {
6332 And->setName(CSrc->getName()+".mask");
6333 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006334 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006335 }
6336 return And;
6337 }
6338 }
6339 }
6340
6341 return 0;
6342}
6343
6344Instruction *InstCombiner::visitSExt(CastInst &CI) {
6345 return commonIntCastTransforms(CI);
6346}
6347
6348Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6349 return commonCastTransforms(CI);
6350}
6351
6352Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6353 return commonCastTransforms(CI);
6354}
6355
6356Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006357 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006358}
6359
6360Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006361 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006362}
6363
6364Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6365 return commonCastTransforms(CI);
6366}
6367
6368Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6369 return commonCastTransforms(CI);
6370}
6371
6372Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006373 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006374}
6375
6376Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6377 return commonCastTransforms(CI);
6378}
6379
6380Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6381
6382 // If the operands are integer typed then apply the integer transforms,
6383 // otherwise just apply the common ones.
6384 Value *Src = CI.getOperand(0);
6385 const Type *SrcTy = Src->getType();
6386 const Type *DestTy = CI.getType();
6387
Chris Lattner03c49532007-01-15 02:27:26 +00006388 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006389 if (Instruction *Result = commonIntCastTransforms(CI))
6390 return Result;
6391 } else {
6392 if (Instruction *Result = commonCastTransforms(CI))
6393 return Result;
6394 }
6395
6396
6397 // Get rid of casts from one type to the same type. These are useless and can
6398 // be replaced by the operand.
6399 if (DestTy == Src->getType())
6400 return ReplaceInstUsesWith(CI, Src);
6401
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006402 // If the source and destination are pointers, and this cast is equivalent to
6403 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6404 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006405 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6406 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6407 const Type *DstElTy = DstPTy->getElementType();
6408 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006409
Reid Spencerc635f472006-12-31 05:48:39 +00006410 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006411 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006412 while (SrcElTy != DstElTy &&
6413 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6414 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6415 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006416 ++NumZeros;
6417 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006418
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006419 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006420 if (SrcElTy == DstElTy) {
Chris Lattner416a8932007-01-31 20:08:52 +00006421 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6422 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006423 }
6424 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006425 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006426
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006427 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6428 if (SVI->hasOneUse()) {
6429 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6430 // a bitconvert to a vector with the same # elts.
6431 if (isa<PackedType>(DestTy) &&
6432 cast<PackedType>(DestTy)->getNumElements() ==
6433 SVI->getType()->getNumElements()) {
6434 CastInst *Tmp;
6435 // If either of the operands is a cast from CI.getType(), then
6436 // evaluating the shuffle in the casted destination's type will allow
6437 // us to eliminate at least one cast.
6438 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6439 Tmp->getOperand(0)->getType() == DestTy) ||
6440 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6441 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006442 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6443 SVI->getOperand(0), DestTy, &CI);
6444 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6445 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006446 // Return a new shuffle vector. Use the same element ID's, as we
6447 // know the vector types match #elts.
6448 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006449 }
6450 }
6451 }
6452 }
Chris Lattner260ab202002-04-18 17:39:14 +00006453 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006454}
6455
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006456/// GetSelectFoldableOperands - We want to turn code that looks like this:
6457/// %C = or %A, %B
6458/// %D = select %cond, %C, %A
6459/// into:
6460/// %C = select %cond, %B, 0
6461/// %D = or %A, %C
6462///
6463/// Assuming that the specified instruction is an operand to the select, return
6464/// a bitmask indicating which operands of this instruction are foldable if they
6465/// equal the other incoming value of the select.
6466///
6467static unsigned GetSelectFoldableOperands(Instruction *I) {
6468 switch (I->getOpcode()) {
6469 case Instruction::Add:
6470 case Instruction::Mul:
6471 case Instruction::And:
6472 case Instruction::Or:
6473 case Instruction::Xor:
6474 return 3; // Can fold through either operand.
6475 case Instruction::Sub: // Can only fold on the amount subtracted.
6476 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006477 case Instruction::LShr:
6478 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006479 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006480 default:
6481 return 0; // Cannot fold
6482 }
6483}
6484
6485/// GetSelectFoldableConstant - For the same transformation as the previous
6486/// function, return the identity constant that goes into the select.
6487static Constant *GetSelectFoldableConstant(Instruction *I) {
6488 switch (I->getOpcode()) {
6489 default: assert(0 && "This cannot happen!"); abort();
6490 case Instruction::Add:
6491 case Instruction::Sub:
6492 case Instruction::Or:
6493 case Instruction::Xor:
6494 return Constant::getNullValue(I->getType());
6495 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006496 case Instruction::LShr:
6497 case Instruction::AShr:
Reid Spencerc635f472006-12-31 05:48:39 +00006498 return Constant::getNullValue(Type::Int8Ty);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006499 case Instruction::And:
6500 return ConstantInt::getAllOnesValue(I->getType());
6501 case Instruction::Mul:
6502 return ConstantInt::get(I->getType(), 1);
6503 }
6504}
6505
Chris Lattner411336f2005-01-19 21:50:18 +00006506/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6507/// have the same opcode and only one use each. Try to simplify this.
6508Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6509 Instruction *FI) {
6510 if (TI->getNumOperands() == 1) {
6511 // If this is a non-volatile load or a cast from the same type,
6512 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006513 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006514 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6515 return 0;
6516 } else {
6517 return 0; // unknown unary op.
6518 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006519
Chris Lattner411336f2005-01-19 21:50:18 +00006520 // Fold this by inserting a select from the input values.
6521 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6522 FI->getOperand(0), SI.getName()+".v");
6523 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006524 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6525 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006526 }
6527
Reid Spencer266e42b2006-12-23 06:05:41 +00006528 // Only handle binary, compare and shift operators here.
Reid Spencer43c77d52006-12-23 18:58:04 +00006529 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006530 return 0;
6531
6532 // Figure out if the operations have any operands in common.
6533 Value *MatchOp, *OtherOpT, *OtherOpF;
6534 bool MatchIsOpZero;
6535 if (TI->getOperand(0) == FI->getOperand(0)) {
6536 MatchOp = TI->getOperand(0);
6537 OtherOpT = TI->getOperand(1);
6538 OtherOpF = FI->getOperand(1);
6539 MatchIsOpZero = true;
6540 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6541 MatchOp = TI->getOperand(1);
6542 OtherOpT = TI->getOperand(0);
6543 OtherOpF = FI->getOperand(0);
6544 MatchIsOpZero = false;
6545 } else if (!TI->isCommutative()) {
6546 return 0;
6547 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6548 MatchOp = TI->getOperand(0);
6549 OtherOpT = TI->getOperand(1);
6550 OtherOpF = FI->getOperand(0);
6551 MatchIsOpZero = true;
6552 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6553 MatchOp = TI->getOperand(1);
6554 OtherOpT = TI->getOperand(0);
6555 OtherOpF = FI->getOperand(1);
6556 MatchIsOpZero = true;
6557 } else {
6558 return 0;
6559 }
6560
6561 // If we reach here, they do have operations in common.
6562 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6563 OtherOpF, SI.getName()+".v");
6564 InsertNewInstBefore(NewSI, SI);
6565
6566 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6567 if (MatchIsOpZero)
6568 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6569 else
6570 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006571 }
Reid Spencer43c77d52006-12-23 18:58:04 +00006572
6573 assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6574 if (MatchIsOpZero)
6575 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6576 else
6577 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006578}
6579
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006580Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006581 Value *CondVal = SI.getCondition();
6582 Value *TrueVal = SI.getTrueValue();
6583 Value *FalseVal = SI.getFalseValue();
6584
6585 // select true, X, Y -> X
6586 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006587 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006588 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006589
6590 // select C, X, X -> X
6591 if (TrueVal == FalseVal)
6592 return ReplaceInstUsesWith(SI, TrueVal);
6593
Chris Lattner81a7a232004-10-16 18:11:37 +00006594 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6595 return ReplaceInstUsesWith(SI, FalseVal);
6596 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6597 return ReplaceInstUsesWith(SI, TrueVal);
6598 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6599 if (isa<Constant>(TrueVal))
6600 return ReplaceInstUsesWith(SI, TrueVal);
6601 else
6602 return ReplaceInstUsesWith(SI, FalseVal);
6603 }
6604
Reid Spencer542964f2007-01-11 18:21:29 +00006605 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006606 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006607 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006608 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006609 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006610 } else {
6611 // Change: A = select B, false, C --> A = and !B, C
6612 Value *NotCond =
6613 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6614 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006615 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006616 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006617 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006618 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006619 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006620 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006621 } else {
6622 // Change: A = select B, C, true --> A = or !B, C
6623 Value *NotCond =
6624 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6625 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006626 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006627 }
6628 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00006629 }
Chris Lattner1c631e82004-04-08 04:43:23 +00006630
Chris Lattner183b3362004-04-09 19:05:30 +00006631 // Selecting between two integer constants?
6632 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6633 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6634 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006635 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006636 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006637 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006638 // select C, 0, 1 -> cast !C to int
6639 Value *NotCond =
6640 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006641 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006642 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006643 }
Chris Lattner35167c32004-06-09 07:59:58 +00006644
Reid Spencer266e42b2006-12-23 06:05:41 +00006645 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006646
Reid Spencer266e42b2006-12-23 06:05:41 +00006647 // (x <s 0) ? -1 : 0 -> ashr x, 31
6648 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattner380c7e92006-09-20 04:44:59 +00006649 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6650 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6651 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006652 if (IC->isSignedPredicate())
Chris Lattner380c7e92006-09-20 04:44:59 +00006653 CanXForm = CmpCst->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006654 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006655 else {
6656 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006657 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006658 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006659 }
6660
6661 if (CanXForm) {
6662 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006663 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006664 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006665 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencerc635f472006-12-31 05:48:39 +00006666 Constant *ShAmt = ConstantInt::get(Type::Int8Ty, Bits-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00006667 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattner380c7e92006-09-20 04:44:59 +00006668 ShAmt, "ones");
6669 InsertNewInstBefore(SRA, SI);
6670
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006671 // Finally, convert to the type of the select RHS. We figure out
6672 // if this requires a SExt, Trunc or BitCast based on the sizes.
6673 Instruction::CastOps opc = Instruction::BitCast;
6674 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6675 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6676 if (SRASize < SISize)
6677 opc = Instruction::SExt;
6678 else if (SRASize > SISize)
6679 opc = Instruction::Trunc;
6680 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006681 }
6682 }
6683
6684
6685 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006686 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006687 // non-constant value, eliminate this whole mess. This corresponds to
6688 // cases like this: ((X & 27) ? 27 : 0)
6689 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006690 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006691 cast<Constant>(IC->getOperand(1))->isNullValue())
6692 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6693 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006694 isa<ConstantInt>(ICA->getOperand(1)) &&
6695 (ICA->getOperand(1) == TrueValC ||
6696 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006697 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6698 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006699 // know whether we have a icmp_ne or icmp_eq and whether the
6700 // true or false val is the zero.
Chris Lattner35167c32004-06-09 07:59:58 +00006701 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006702 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006703 Value *V = ICA;
6704 if (ShouldNotVal)
6705 V = InsertNewInstBefore(BinaryOperator::create(
6706 Instruction::Xor, V, ICA->getOperand(1)), SI);
6707 return ReplaceInstUsesWith(SI, V);
6708 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006709 }
Chris Lattner533bc492004-03-30 19:37:13 +00006710 }
Chris Lattner623fba12004-04-10 22:21:27 +00006711
6712 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006713 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6714 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006715 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006716 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006717 return ReplaceInstUsesWith(SI, FalseVal);
6718 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006719 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006720 return ReplaceInstUsesWith(SI, TrueVal);
6721 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6722
Reid Spencer266e42b2006-12-23 06:05:41 +00006723 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006724 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006725 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006726 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006727 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006728 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6729 return ReplaceInstUsesWith(SI, TrueVal);
6730 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6731 }
6732 }
6733
6734 // See if we are selecting two values based on a comparison of the two values.
6735 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6736 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6737 // Transform (X == Y) ? X : Y -> Y
6738 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6739 return ReplaceInstUsesWith(SI, FalseVal);
6740 // Transform (X != Y) ? X : Y -> X
6741 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6742 return ReplaceInstUsesWith(SI, TrueVal);
6743 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6744
6745 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6746 // Transform (X == Y) ? Y : X -> X
6747 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6748 return ReplaceInstUsesWith(SI, FalseVal);
6749 // Transform (X != Y) ? Y : X -> Y
6750 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006751 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006752 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6753 }
6754 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006755
Chris Lattnera04c9042005-01-13 22:52:24 +00006756 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6757 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6758 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006759 Instruction *AddOp = 0, *SubOp = 0;
6760
Chris Lattner411336f2005-01-19 21:50:18 +00006761 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6762 if (TI->getOpcode() == FI->getOpcode())
6763 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6764 return IV;
6765
6766 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6767 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006768 if (TI->getOpcode() == Instruction::Sub &&
6769 FI->getOpcode() == Instruction::Add) {
6770 AddOp = FI; SubOp = TI;
6771 } else if (FI->getOpcode() == Instruction::Sub &&
6772 TI->getOpcode() == Instruction::Add) {
6773 AddOp = TI; SubOp = FI;
6774 }
6775
6776 if (AddOp) {
6777 Value *OtherAddOp = 0;
6778 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6779 OtherAddOp = AddOp->getOperand(1);
6780 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6781 OtherAddOp = AddOp->getOperand(0);
6782 }
6783
6784 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006785 // So at this point we know we have (Y -> OtherAddOp):
6786 // select C, (add X, Y), (sub X, Z)
6787 Value *NegVal; // Compute -Z
6788 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6789 NegVal = ConstantExpr::getNeg(C);
6790 } else {
6791 NegVal = InsertNewInstBefore(
6792 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006793 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006794
6795 Value *NewTrueOp = OtherAddOp;
6796 Value *NewFalseOp = NegVal;
6797 if (AddOp != TI)
6798 std::swap(NewTrueOp, NewFalseOp);
6799 Instruction *NewSel =
6800 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6801
6802 NewSel = InsertNewInstBefore(NewSel, SI);
6803 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006804 }
6805 }
6806 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006807
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006808 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00006809 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006810 // See the comment above GetSelectFoldableOperands for a description of the
6811 // transformation we are doing here.
6812 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6813 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6814 !isa<Constant>(FalseVal))
6815 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6816 unsigned OpToFold = 0;
6817 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6818 OpToFold = 1;
6819 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6820 OpToFold = 2;
6821 }
6822
6823 if (OpToFold) {
6824 Constant *C = GetSelectFoldableConstant(TVI);
6825 std::string Name = TVI->getName(); TVI->setName("");
6826 Instruction *NewSel =
6827 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6828 Name);
6829 InsertNewInstBefore(NewSel, SI);
6830 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6831 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6832 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6833 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6834 else {
6835 assert(0 && "Unknown instruction!!");
6836 }
6837 }
6838 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006839
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006840 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6841 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6842 !isa<Constant>(TrueVal))
6843 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6844 unsigned OpToFold = 0;
6845 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6846 OpToFold = 1;
6847 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6848 OpToFold = 2;
6849 }
6850
6851 if (OpToFold) {
6852 Constant *C = GetSelectFoldableConstant(FVI);
6853 std::string Name = FVI->getName(); FVI->setName("");
6854 Instruction *NewSel =
6855 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6856 Name);
6857 InsertNewInstBefore(NewSel, SI);
6858 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6859 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6860 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6861 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6862 else {
6863 assert(0 && "Unknown instruction!!");
6864 }
6865 }
6866 }
6867 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006868
6869 if (BinaryOperator::isNot(CondVal)) {
6870 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6871 SI.setOperand(1, FalseVal);
6872 SI.setOperand(2, TrueVal);
6873 return &SI;
6874 }
6875
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006876 return 0;
6877}
6878
Chris Lattner82f2ef22006-03-06 20:18:44 +00006879/// GetKnownAlignment - If the specified pointer has an alignment that we can
6880/// determine, return it, otherwise return 0.
6881static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6882 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6883 unsigned Align = GV->getAlignment();
6884 if (Align == 0 && TD)
Chris Lattner50ee0e42007-01-20 22:35:55 +00006885 Align = TD->getTypeAlignmentPref(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00006886 return Align;
6887 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6888 unsigned Align = AI->getAlignment();
6889 if (Align == 0 && TD) {
6890 if (isa<AllocaInst>(AI))
Chris Lattner50ee0e42007-01-20 22:35:55 +00006891 Align = TD->getTypeAlignmentPref(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00006892 else if (isa<MallocInst>(AI)) {
6893 // Malloc returns maximally aligned memory.
Chris Lattner50ee0e42007-01-20 22:35:55 +00006894 Align = TD->getTypeAlignmentABI(AI->getType()->getElementType());
6895 Align =
6896 std::max(Align,
6897 (unsigned)TD->getTypeAlignmentABI(Type::DoubleTy));
6898 Align =
6899 std::max(Align,
6900 (unsigned)TD->getTypeAlignmentABI(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006901 }
6902 }
6903 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006904 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00006905 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006906 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00006907 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006908 if (isa<PointerType>(CI->getOperand(0)->getType()))
6909 return GetKnownAlignment(CI->getOperand(0), TD);
6910 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006911 } else if (isa<GetElementPtrInst>(V) ||
6912 (isa<ConstantExpr>(V) &&
6913 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6914 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006915 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6916 if (BaseAlignment == 0) return 0;
6917
6918 // If all indexes are zero, it is just the alignment of the base pointer.
6919 bool AllZeroOperands = true;
6920 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6921 if (!isa<Constant>(GEPI->getOperand(i)) ||
6922 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6923 AllZeroOperands = false;
6924 break;
6925 }
6926 if (AllZeroOperands)
6927 return BaseAlignment;
6928
6929 // Otherwise, if the base alignment is >= the alignment we expect for the
6930 // base pointer type, then we know that the resultant pointer is aligned at
6931 // least as much as its type requires.
6932 if (!TD) return 0;
6933
6934 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00006935 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
6936 if (TD->getTypeAlignmentABI(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006937 <= BaseAlignment) {
6938 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00006939 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
6940 return TD->getTypeAlignmentABI(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00006941 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006942 return 0;
6943 }
6944 return 0;
6945}
6946
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006947
Chris Lattnerc66b2232006-01-13 20:11:04 +00006948/// visitCallInst - CallInst simplification. This mostly only handles folding
6949/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6950/// the heavy lifting.
6951///
Chris Lattner970c33a2003-06-19 17:00:31 +00006952Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006953 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6954 if (!II) return visitCallSite(&CI);
6955
Chris Lattner51ea1272004-02-28 05:22:00 +00006956 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6957 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006958 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006959 bool Changed = false;
6960
6961 // memmove/cpy/set of zero bytes is a noop.
6962 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6963 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6964
Chris Lattner00648e12004-10-12 04:52:52 +00006965 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006966 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006967 // Replace the instruction with just byte operations. We would
6968 // transform other cases to loads/stores, but we don't know if
6969 // alignment is sufficient.
6970 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006971 }
6972
Chris Lattner00648e12004-10-12 04:52:52 +00006973 // If we have a memmove and the source operation is a constant global,
6974 // then the source and dest pointers can't alias, so we can change this
6975 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006976 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006977 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6978 if (GVSrc->isConstant()) {
6979 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006980 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00006981 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00006982 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00006983 Name = "llvm.memcpy.i32";
6984 else
6985 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00006986 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006987 CI.getCalledFunction()->getFunctionType());
6988 CI.setOperand(0, MemCpy);
6989 Changed = true;
6990 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006991 }
Chris Lattner00648e12004-10-12 04:52:52 +00006992
Chris Lattner82f2ef22006-03-06 20:18:44 +00006993 // If we can determine a pointer alignment that is bigger than currently
6994 // set, update the alignment.
6995 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6996 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6997 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6998 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006999 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007000 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007001 Changed = true;
7002 }
7003 } else if (isa<MemSetInst>(MI)) {
7004 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007005 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007006 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007007 Changed = true;
7008 }
7009 }
7010
Chris Lattnerc66b2232006-01-13 20:11:04 +00007011 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007012 } else {
7013 switch (II->getIntrinsicID()) {
7014 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007015 case Intrinsic::ppc_altivec_lvx:
7016 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007017 case Intrinsic::x86_sse_loadu_ps:
7018 case Intrinsic::x86_sse2_loadu_pd:
7019 case Intrinsic::x86_sse2_loadu_dq:
7020 // Turn PPC lvx -> load if the pointer is known aligned.
7021 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007022 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007023 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007024 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007025 return new LoadInst(Ptr);
7026 }
7027 break;
7028 case Intrinsic::ppc_altivec_stvx:
7029 case Intrinsic::ppc_altivec_stvxl:
7030 // Turn stvx -> store if the pointer is known aligned.
7031 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007032 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007033 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7034 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007035 return new StoreInst(II->getOperand(1), Ptr);
7036 }
7037 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007038 case Intrinsic::x86_sse_storeu_ps:
7039 case Intrinsic::x86_sse2_storeu_pd:
7040 case Intrinsic::x86_sse2_storeu_dq:
7041 case Intrinsic::x86_sse2_storel_dq:
7042 // Turn X86 storeu -> store if the pointer is known aligned.
7043 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7044 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007045 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7046 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007047 return new StoreInst(II->getOperand(2), Ptr);
7048 }
7049 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007050
7051 case Intrinsic::x86_sse_cvttss2si: {
7052 // These intrinsics only demands the 0th element of its input vector. If
7053 // we can simplify the input based on that, do so now.
7054 uint64_t UndefElts;
7055 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7056 UndefElts)) {
7057 II->setOperand(1, V);
7058 return II;
7059 }
7060 break;
7061 }
7062
Chris Lattnere79d2492006-04-06 19:19:17 +00007063 case Intrinsic::ppc_altivec_vperm:
7064 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7065 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7066 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7067
7068 // Check that all of the elements are integer constants or undefs.
7069 bool AllEltsOk = true;
7070 for (unsigned i = 0; i != 16; ++i) {
7071 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7072 !isa<UndefValue>(Mask->getOperand(i))) {
7073 AllEltsOk = false;
7074 break;
7075 }
7076 }
7077
7078 if (AllEltsOk) {
7079 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007080 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7081 II->getOperand(1), Mask->getType(), CI);
7082 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7083 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007084 Value *Result = UndefValue::get(Op0->getType());
7085
7086 // Only extract each element once.
7087 Value *ExtractedElts[32];
7088 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7089
7090 for (unsigned i = 0; i != 16; ++i) {
7091 if (isa<UndefValue>(Mask->getOperand(i)))
7092 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007093 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007094 Idx &= 31; // Match the hardware behavior.
7095
7096 if (ExtractedElts[Idx] == 0) {
7097 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007098 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007099 InsertNewInstBefore(Elt, CI);
7100 ExtractedElts[Idx] = Elt;
7101 }
7102
7103 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007104 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007105 InsertNewInstBefore(cast<Instruction>(Result), CI);
7106 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007107 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007108 }
7109 }
7110 break;
7111
Chris Lattner503221f2006-01-13 21:28:09 +00007112 case Intrinsic::stackrestore: {
7113 // If the save is right next to the restore, remove the restore. This can
7114 // happen when variable allocas are DCE'd.
7115 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7116 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7117 BasicBlock::iterator BI = SS;
7118 if (&*++BI == II)
7119 return EraseInstFromFunction(CI);
7120 }
7121 }
7122
7123 // If the stack restore is in a return/unwind block and if there are no
7124 // allocas or calls between the restore and the return, nuke the restore.
7125 TerminatorInst *TI = II->getParent()->getTerminator();
7126 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7127 BasicBlock::iterator BI = II;
7128 bool CannotRemove = false;
7129 for (++BI; &*BI != TI; ++BI) {
7130 if (isa<AllocaInst>(BI) ||
7131 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7132 CannotRemove = true;
7133 break;
7134 }
7135 }
7136 if (!CannotRemove)
7137 return EraseInstFromFunction(CI);
7138 }
7139 break;
7140 }
7141 }
Chris Lattner00648e12004-10-12 04:52:52 +00007142 }
7143
Chris Lattnerc66b2232006-01-13 20:11:04 +00007144 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007145}
7146
7147// InvokeInst simplification
7148//
7149Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007150 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007151}
7152
Chris Lattneraec3d942003-10-07 22:32:43 +00007153// visitCallSite - Improvements for call and invoke instructions.
7154//
7155Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007156 bool Changed = false;
7157
7158 // If the callee is a constexpr cast of a function, attempt to move the cast
7159 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007160 if (transformConstExprCastCall(CS)) return 0;
7161
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007162 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007163
Chris Lattner61d9d812005-05-13 07:09:09 +00007164 if (Function *CalleeF = dyn_cast<Function>(Callee))
7165 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7166 Instruction *OldCall = CS.getInstruction();
7167 // If the call and callee calling conventions don't match, this call must
7168 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007169 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007170 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007171 if (!OldCall->use_empty())
7172 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7173 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7174 return EraseInstFromFunction(*OldCall);
7175 return 0;
7176 }
7177
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007178 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7179 // This instruction is not reachable, just remove it. We insert a store to
7180 // undef so that we know that this code is not reachable, despite the fact
7181 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007182 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007183 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007184 CS.getInstruction());
7185
7186 if (!CS.getInstruction()->use_empty())
7187 CS.getInstruction()->
7188 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7189
7190 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7191 // Don't break the CFG, insert a dummy cond branch.
7192 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007193 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007194 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007195 return EraseInstFromFunction(*CS.getInstruction());
7196 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007197
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007198 const PointerType *PTy = cast<PointerType>(Callee->getType());
7199 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7200 if (FTy->isVarArg()) {
7201 // See if we can optimize any arguments passed through the varargs area of
7202 // the call.
7203 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7204 E = CS.arg_end(); I != E; ++I)
7205 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7206 // If this cast does not effect the value passed through the varargs
7207 // area, we can eliminate the use of the cast.
7208 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007209 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007210 *I = Op;
7211 Changed = true;
7212 }
7213 }
7214 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007215
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007216 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007217}
7218
Chris Lattner970c33a2003-06-19 17:00:31 +00007219// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7220// attempt to move the cast to the arguments of the call/invoke.
7221//
7222bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7223 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7224 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007225 if (CE->getOpcode() != Instruction::BitCast ||
7226 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007227 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007228 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007229 Instruction *Caller = CS.getInstruction();
7230
7231 // Okay, this is a cast from a function to a different type. Unless doing so
7232 // would cause a type conversion of one of our arguments, change this call to
7233 // be a direct call with arguments casted to the appropriate types.
7234 //
7235 const FunctionType *FT = Callee->getFunctionType();
7236 const Type *OldRetTy = Caller->getType();
7237
Chris Lattner1f7942f2004-01-14 06:06:08 +00007238 // Check to see if we are changing the return type...
7239 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00007240 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007241 OldRetTy != FT->getReturnType() &&
7242 // Conversion is ok if changing from pointer to int of same size.
7243 !(isa<PointerType>(FT->getReturnType()) &&
7244 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007245 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007246
7247 // If the callsite is an invoke instruction, and the return value is used by
7248 // a PHI node in a successor, we cannot change the return type of the call
7249 // because there is no place to put the cast instruction (without breaking
7250 // the critical edge). Bail out in this case.
7251 if (!Caller->use_empty())
7252 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7253 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7254 UI != E; ++UI)
7255 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7256 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007257 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007258 return false;
7259 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007260
7261 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7262 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007263
Chris Lattner970c33a2003-06-19 17:00:31 +00007264 CallSite::arg_iterator AI = CS.arg_begin();
7265 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7266 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007267 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007268 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007269 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007270 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007271 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00007272 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007273 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7274 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7275 && c->getSExtValue() > 0);
Reid Spencer5301e7c2007-01-30 20:08:39 +00007276 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007277 }
7278
7279 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00007280 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00007281 return false; // Do not delete arguments unless we have a function body...
7282
7283 // Okay, we decided that this is a safe thing to do: go ahead and start
7284 // inserting cast instructions as necessary...
7285 std::vector<Value*> Args;
7286 Args.reserve(NumActualArgs);
7287
7288 AI = CS.arg_begin();
7289 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7290 const Type *ParamTy = FT->getParamType(i);
7291 if ((*AI)->getType() == ParamTy) {
7292 Args.push_back(*AI);
7293 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007294 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007295 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007296 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007297 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007298 }
7299 }
7300
7301 // If the function takes more arguments than the call was taking, add them
7302 // now...
7303 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7304 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7305
7306 // If we are removing arguments to the function, emit an obnoxious warning...
7307 if (FT->getNumParams() < NumActualArgs)
7308 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007309 cerr << "WARNING: While resolving call to function '"
7310 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007311 } else {
7312 // Add all of the arguments in their promoted form to the arg list...
7313 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7314 const Type *PTy = getPromotedType((*AI)->getType());
7315 if (PTy != (*AI)->getType()) {
7316 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007317 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7318 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007319 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007320 InsertNewInstBefore(Cast, *Caller);
7321 Args.push_back(Cast);
7322 } else {
7323 Args.push_back(*AI);
7324 }
7325 }
7326 }
7327
7328 if (FT->getReturnType() == Type::VoidTy)
7329 Caller->setName(""); // Void type should not have a name...
7330
7331 Instruction *NC;
7332 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007333 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00007334 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007335 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007336 } else {
7337 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007338 if (cast<CallInst>(Caller)->isTailCall())
7339 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007340 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007341 }
7342
7343 // Insert a cast of the return type as necessary...
7344 Value *NV = NC;
7345 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7346 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007347 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007348 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7349 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007350 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007351
7352 // If this is an invoke instruction, we should insert it after the first
7353 // non-phi, instruction in the normal successor block.
7354 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7355 BasicBlock::iterator I = II->getNormalDest()->begin();
7356 while (isa<PHINode>(I)) ++I;
7357 InsertNewInstBefore(NC, *I);
7358 } else {
7359 // Otherwise, it's a call, just insert cast right after the call instr
7360 InsertNewInstBefore(NC, *Caller);
7361 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007362 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007363 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007364 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007365 }
7366 }
7367
7368 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7369 Caller->replaceAllUsesWith(NV);
7370 Caller->getParent()->getInstList().erase(Caller);
7371 removeFromWorkList(Caller);
7372 return true;
7373}
7374
Chris Lattnercadac0c2006-11-01 04:51:18 +00007375/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7376/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7377/// and a single binop.
7378Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7379 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007380 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007381 isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007382 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007383 Value *LHSVal = FirstInst->getOperand(0);
7384 Value *RHSVal = FirstInst->getOperand(1);
7385
7386 const Type *LHSType = LHSVal->getType();
7387 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007388
7389 // Scan to see if all operands are the same opcode, all have one use, and all
7390 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007391 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007392 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007393 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007394 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007395 // types or GEP's with different index types.
7396 I->getOperand(0)->getType() != LHSType ||
7397 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007398 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007399
7400 // If they are CmpInst instructions, check their predicates
7401 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7402 if (cast<CmpInst>(I)->getPredicate() !=
7403 cast<CmpInst>(FirstInst)->getPredicate())
7404 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007405
7406 // Keep track of which operand needs a phi node.
7407 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7408 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007409 }
7410
Chris Lattner4f218d52006-11-08 19:42:28 +00007411 // Otherwise, this is safe to transform, determine if it is profitable.
7412
7413 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7414 // Indexes are often folded into load/store instructions, so we don't want to
7415 // hide them behind a phi.
7416 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7417 return 0;
7418
Chris Lattnercadac0c2006-11-01 04:51:18 +00007419 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007420 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007421 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007422 if (LHSVal == 0) {
7423 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7424 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7425 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007426 InsertNewInstBefore(NewLHS, PN);
7427 LHSVal = NewLHS;
7428 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007429
7430 if (RHSVal == 0) {
7431 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7432 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7433 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007434 InsertNewInstBefore(NewRHS, PN);
7435 RHSVal = NewRHS;
7436 }
7437
Chris Lattnercd62f112006-11-08 19:29:23 +00007438 // Add all operands to the new PHIs.
7439 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7440 if (NewLHS) {
7441 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7442 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7443 }
7444 if (NewRHS) {
7445 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7446 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7447 }
7448 }
7449
Chris Lattnercadac0c2006-11-01 04:51:18 +00007450 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007451 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007452 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7453 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7454 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007455 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7456 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7457 else {
7458 assert(isa<GetElementPtrInst>(FirstInst));
7459 return new GetElementPtrInst(LHSVal, RHSVal);
7460 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007461}
7462
Chris Lattner14f82c72006-11-01 07:13:54 +00007463/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7464/// of the block that defines it. This means that it must be obvious the value
7465/// of the load is not changed from the point of the load to the end of the
7466/// block it is in.
7467static bool isSafeToSinkLoad(LoadInst *L) {
7468 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7469
7470 for (++BBI; BBI != E; ++BBI)
7471 if (BBI->mayWriteToMemory())
7472 return false;
7473 return true;
7474}
7475
Chris Lattner970c33a2003-06-19 17:00:31 +00007476
Chris Lattner7515cab2004-11-14 19:13:23 +00007477// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7478// operator and they all are only used by the PHI, PHI together their
7479// inputs, and do the operation once, to the result of the PHI.
7480Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7481 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7482
7483 // Scan the instruction, looking for input operations that can be folded away.
7484 // If all input operands to the phi are the same instruction (e.g. a cast from
7485 // the same type or "+42") we can pull the operation through the PHI, reducing
7486 // code size and simplifying code.
7487 Constant *ConstantOp = 0;
7488 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007489 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007490 if (isa<CastInst>(FirstInst)) {
7491 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00007492 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7493 isa<CmpInst>(FirstInst)) {
7494 // Can fold binop, compare or shift here if the RHS is a constant,
7495 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007496 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007497 if (ConstantOp == 0)
7498 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007499 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7500 isVolatile = LI->isVolatile();
7501 // We can't sink the load if the loaded value could be modified between the
7502 // load and the PHI.
7503 if (LI->getParent() != PN.getIncomingBlock(0) ||
7504 !isSafeToSinkLoad(LI))
7505 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007506 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007507 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007508 return FoldPHIArgBinOpIntoPHI(PN);
7509 // Can't handle general GEPs yet.
7510 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007511 } else {
7512 return 0; // Cannot fold this operation.
7513 }
7514
7515 // Check to see if all arguments are the same operation.
7516 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7517 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7518 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007519 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007520 return 0;
7521 if (CastSrcTy) {
7522 if (I->getOperand(0)->getType() != CastSrcTy)
7523 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007524 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007525 // We can't sink the load if the loaded value could be modified between
7526 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007527 if (LI->isVolatile() != isVolatile ||
7528 LI->getParent() != PN.getIncomingBlock(i) ||
7529 !isSafeToSinkLoad(LI))
7530 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007531 } else if (I->getOperand(1) != ConstantOp) {
7532 return 0;
7533 }
7534 }
7535
7536 // Okay, they are all the same operation. Create a new PHI node of the
7537 // correct type, and PHI together all of the LHS's of the instructions.
7538 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7539 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007540 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007541
7542 Value *InVal = FirstInst->getOperand(0);
7543 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007544
7545 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007546 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7547 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7548 if (NewInVal != InVal)
7549 InVal = 0;
7550 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7551 }
7552
7553 Value *PhiVal;
7554 if (InVal) {
7555 // The new PHI unions all of the same values together. This is really
7556 // common, so we handle it intelligently here for compile-time speed.
7557 PhiVal = InVal;
7558 delete NewPN;
7559 } else {
7560 InsertNewInstBefore(NewPN, PN);
7561 PhiVal = NewPN;
7562 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007563
Chris Lattner7515cab2004-11-14 19:13:23 +00007564 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007565 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7566 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007567 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007568 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007569 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007570 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007571 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7572 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7573 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007574 else
7575 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00007576 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007577}
Chris Lattner48a44f72002-05-02 17:06:02 +00007578
Chris Lattner71536432005-01-17 05:10:15 +00007579/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7580/// that is dead.
7581static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7582 if (PN->use_empty()) return true;
7583 if (!PN->hasOneUse()) return false;
7584
7585 // Remember this node, and if we find the cycle, return.
7586 if (!PotentiallyDeadPHIs.insert(PN).second)
7587 return true;
7588
7589 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7590 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007591
Chris Lattner71536432005-01-17 05:10:15 +00007592 return false;
7593}
7594
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007595// PHINode simplification
7596//
Chris Lattner113f4f42002-06-25 16:13:24 +00007597Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007598 // If LCSSA is around, don't mess with Phi nodes
7599 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007600
Owen Andersonae8aa642006-07-10 22:03:18 +00007601 if (Value *V = PN.hasConstantValue())
7602 return ReplaceInstUsesWith(PN, V);
7603
Owen Andersonae8aa642006-07-10 22:03:18 +00007604 // If all PHI operands are the same operation, pull them through the PHI,
7605 // reducing code size.
7606 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7607 PN.getIncomingValue(0)->hasOneUse())
7608 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7609 return Result;
7610
7611 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7612 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7613 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007614 if (PN.hasOneUse()) {
7615 Instruction *PHIUser = cast<Instruction>(PN.use_back());
7616 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Owen Andersonae8aa642006-07-10 22:03:18 +00007617 std::set<PHINode*> PotentiallyDeadPHIs;
7618 PotentiallyDeadPHIs.insert(&PN);
7619 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7620 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7621 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007622
7623 // If this phi has a single use, and if that use just computes a value for
7624 // the next iteration of a loop, delete the phi. This occurs with unused
7625 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7626 // common case here is good because the only other things that catch this
7627 // are induction variable analysis (sometimes) and ADCE, which is only run
7628 // late.
7629 if (PHIUser->hasOneUse() &&
7630 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7631 PHIUser->use_back() == &PN) {
7632 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7633 }
7634 }
Owen Andersonae8aa642006-07-10 22:03:18 +00007635
Chris Lattner91daeb52003-12-19 05:58:40 +00007636 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007637}
7638
Reid Spencer13bc5d72006-12-12 09:18:51 +00007639static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7640 Instruction *InsertPoint,
7641 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00007642 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7643 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007644 // We must cast correctly to the pointer type. Ensure that we
7645 // sign extend the integer value if it is smaller as this is
7646 // used for address computation.
7647 Instruction::CastOps opcode =
7648 (VTySize < PtrSize ? Instruction::SExt :
7649 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7650 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007651}
7652
Chris Lattner48a44f72002-05-02 17:06:02 +00007653
Chris Lattner113f4f42002-06-25 16:13:24 +00007654Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007655 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007656 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007657 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007658 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007659 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007660
Chris Lattner81a7a232004-10-16 18:11:37 +00007661 if (isa<UndefValue>(GEP.getOperand(0)))
7662 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7663
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007664 bool HasZeroPointerIndex = false;
7665 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7666 HasZeroPointerIndex = C->isNullValue();
7667
7668 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007669 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007670
Chris Lattner69193f92004-04-05 01:30:19 +00007671 // Eliminate unneeded casts for indices.
7672 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007673 gep_type_iterator GTI = gep_type_begin(GEP);
7674 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7675 if (isa<SequentialType>(*GTI)) {
7676 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00007677 if (CI->getOpcode() == Instruction::ZExt ||
7678 CI->getOpcode() == Instruction::SExt) {
7679 const Type *SrcTy = CI->getOperand(0)->getType();
7680 // We can eliminate a cast from i32 to i64 iff the target
7681 // is a 32-bit pointer target.
7682 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7683 MadeChange = true;
7684 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00007685 }
7686 }
7687 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007688 // If we are using a wider index than needed for this platform, shrink it
7689 // to what we need. If the incoming value needs a cast instruction,
7690 // insert it. This explicit cast can make subsequent optimizations more
7691 // obvious.
7692 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007693 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007694 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007695 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007696 MadeChange = true;
7697 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007698 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7699 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007700 GEP.setOperand(i, Op);
7701 MadeChange = true;
7702 }
Chris Lattner69193f92004-04-05 01:30:19 +00007703 }
7704 if (MadeChange) return &GEP;
7705
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007706 // Combine Indices - If the source pointer to this getelementptr instruction
7707 // is a getelementptr instruction, combine the indices of the two
7708 // getelementptr instructions into a single instruction.
7709 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007710 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007711 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007712 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007713
7714 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007715 // Note that if our source is a gep chain itself that we wait for that
7716 // chain to be resolved before we perform this transformation. This
7717 // avoids us creating a TON of code in some cases.
7718 //
7719 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7720 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7721 return 0; // Wait until our source is folded to completion.
7722
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007723 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007724
7725 // Find out whether the last index in the source GEP is a sequential idx.
7726 bool EndsWithSequential = false;
7727 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7728 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007729 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007730
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007731 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007732 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007733 // Replace: gep (gep %P, long B), long A, ...
7734 // With: T = long A+B; gep %P, T, ...
7735 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007736 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007737 if (SO1 == Constant::getNullValue(SO1->getType())) {
7738 Sum = GO1;
7739 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7740 Sum = SO1;
7741 } else {
7742 // If they aren't the same type, convert both to an integer of the
7743 // target's pointer size.
7744 if (SO1->getType() != GO1->getType()) {
7745 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007746 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007747 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007748 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007749 } else {
7750 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007751 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007752 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007753 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007754
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007755 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007756 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007757 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007758 } else {
7759 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007760 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7761 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007762 }
7763 }
7764 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007765 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7766 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7767 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007768 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7769 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007770 }
Chris Lattner69193f92004-04-05 01:30:19 +00007771 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007772
7773 // Recycle the GEP we already have if possible.
7774 if (SrcGEPOperands.size() == 2) {
7775 GEP.setOperand(0, SrcGEPOperands[0]);
7776 GEP.setOperand(1, Sum);
7777 return &GEP;
7778 } else {
7779 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7780 SrcGEPOperands.end()-1);
7781 Indices.push_back(Sum);
7782 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7783 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007784 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007785 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007786 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007787 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007788 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7789 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007790 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7791 }
7792
7793 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007794 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007795
Chris Lattner5f667a62004-05-07 22:09:22 +00007796 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007797 // GEP of global variable. If all of the indices for this GEP are
7798 // constants, we can promote this to a constexpr instead of an instruction.
7799
7800 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00007801 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007802 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7803 for (; I != E && isa<Constant>(*I); ++I)
7804 Indices.push_back(cast<Constant>(*I));
7805
7806 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00007807 Constant *CE = ConstantExpr::getGetElementPtr(GV,
7808 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007809
7810 // Replace all uses of the GEP with the new constexpr...
7811 return ReplaceInstUsesWith(GEP, CE);
7812 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007813 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00007814 if (!isa<PointerType>(X->getType())) {
7815 // Not interesting. Source pointer must be a cast from pointer.
7816 } else if (HasZeroPointerIndex) {
7817 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7818 // into : GEP [10 x ubyte]* X, long 0, ...
7819 //
7820 // This occurs when the program declares an array extern like "int X[];"
7821 //
7822 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7823 const PointerType *XTy = cast<PointerType>(X->getType());
7824 if (const ArrayType *XATy =
7825 dyn_cast<ArrayType>(XTy->getElementType()))
7826 if (const ArrayType *CATy =
7827 dyn_cast<ArrayType>(CPTy->getElementType()))
7828 if (CATy->getElementType() == XATy->getElementType()) {
7829 // At this point, we know that the cast source type is a pointer
7830 // to an array of the same type as the destination pointer
7831 // array. Because the array type is never stepped over (there
7832 // is a leading zero) we can fold the cast into this GEP.
7833 GEP.setOperand(0, X);
7834 return &GEP;
7835 }
7836 } else if (GEP.getNumOperands() == 2) {
7837 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007838 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7839 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007840 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7841 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7842 if (isa<ArrayType>(SrcElTy) &&
7843 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7844 TD->getTypeSize(ResElTy)) {
7845 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00007846 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00007847 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007848 // V and GEP are both pointer types --> BitCast
7849 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007850 }
Chris Lattner2a893292005-09-13 18:36:04 +00007851
7852 // Transform things like:
7853 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7854 // (where tmp = 8*tmp2) into:
7855 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7856
7857 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00007858 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00007859 uint64_t ArrayEltSize =
7860 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7861
7862 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7863 // allow either a mul, shift, or constant here.
7864 Value *NewIdx = 0;
7865 ConstantInt *Scale = 0;
7866 if (ArrayEltSize == 1) {
7867 NewIdx = GEP.getOperand(1);
7868 Scale = ConstantInt::get(NewIdx->getType(), 1);
7869 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007870 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007871 Scale = CI;
7872 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7873 if (Inst->getOpcode() == Instruction::Shl &&
7874 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007875 unsigned ShAmt =
7876 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007877 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007878 NewIdx = Inst->getOperand(0);
7879 } else if (Inst->getOpcode() == Instruction::Mul &&
7880 isa<ConstantInt>(Inst->getOperand(1))) {
7881 Scale = cast<ConstantInt>(Inst->getOperand(1));
7882 NewIdx = Inst->getOperand(0);
7883 }
7884 }
7885
7886 // If the index will be to exactly the right offset with the scale taken
7887 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007888 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007889 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007890 Scale = ConstantInt::get(Scale->getType(),
7891 Scale->getZExtValue() / ArrayEltSize);
7892 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007893 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7894 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00007895 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7896 NewIdx = InsertNewInstBefore(Sc, GEP);
7897 }
7898
7899 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007900 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00007901 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00007902 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007903 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7904 // The NewGEP must be pointer typed, so must the old one -> BitCast
7905 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00007906 }
7907 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007908 }
Chris Lattnerca081252001-12-14 16:52:21 +00007909 }
7910
Chris Lattnerca081252001-12-14 16:52:21 +00007911 return 0;
7912}
7913
Chris Lattner1085bdf2002-11-04 16:18:53 +00007914Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7915 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7916 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007917 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7918 const Type *NewTy =
7919 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007920 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007921
7922 // Create and insert the replacement instruction...
7923 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007924 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007925 else {
7926 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007927 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007928 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007929
7930 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007931
Chris Lattner1085bdf2002-11-04 16:18:53 +00007932 // Scan to the end of the allocation instructions, to skip over a block of
7933 // allocas if possible...
7934 //
7935 BasicBlock::iterator It = New;
7936 while (isa<AllocationInst>(*It)) ++It;
7937
7938 // Now that I is pointing to the first non-allocation-inst in the block,
7939 // insert our getelementptr instruction...
7940 //
Reid Spencerc635f472006-12-31 05:48:39 +00007941 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00007942 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7943 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007944
7945 // Now make everything use the getelementptr instead of the original
7946 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007947 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007948 } else if (isa<UndefValue>(AI.getArraySize())) {
7949 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007950 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007951
7952 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7953 // Note that we only do this for alloca's, because malloc should allocate and
7954 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007955 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007956 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007957 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7958
Chris Lattner1085bdf2002-11-04 16:18:53 +00007959 return 0;
7960}
7961
Chris Lattner8427bff2003-12-07 01:24:23 +00007962Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7963 Value *Op = FI.getOperand(0);
7964
7965 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7966 if (CastInst *CI = dyn_cast<CastInst>(Op))
7967 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7968 FI.setOperand(0, CI->getOperand(0));
7969 return &FI;
7970 }
7971
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007972 // free undef -> unreachable.
7973 if (isa<UndefValue>(Op)) {
7974 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007975 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007976 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007977 return EraseInstFromFunction(FI);
7978 }
7979
Chris Lattnerf3a36602004-02-28 04:57:37 +00007980 // If we have 'free null' delete the instruction. This can happen in stl code
7981 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007982 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007983 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007984
Chris Lattner8427bff2003-12-07 01:24:23 +00007985 return 0;
7986}
7987
7988
Chris Lattner72684fe2005-01-31 05:51:45 +00007989/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007990static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7991 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007992 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007993
7994 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007995 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007996 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007997
Reid Spencer31a4ef42007-01-22 05:51:25 +00007998 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7999 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008000 // If the source is an array, the code below will not succeed. Check to
8001 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8002 // constants.
8003 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8004 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8005 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008006 Value *Idxs[2];
8007 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8008 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008009 SrcTy = cast<PointerType>(CastOp->getType());
8010 SrcPTy = SrcTy->getElementType();
8011 }
8012
Reid Spencer31a4ef42007-01-22 05:51:25 +00008013 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
8014 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008015 // Do not allow turning this into a load of an integer, which is then
8016 // casted to a pointer, this pessimizes pointer analysis a lot.
8017 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008018 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8019 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008020
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008021 // Okay, we are casting from one integer or pointer type to another of
8022 // the same size. Instead of casting the pointer before the load, cast
8023 // the result of the loaded value.
8024 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8025 CI->getName(),
8026 LI.isVolatile()),LI);
8027 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008028 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008029 }
Chris Lattner35e24772004-07-13 01:49:43 +00008030 }
8031 }
8032 return 0;
8033}
8034
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008035/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008036/// from this value cannot trap. If it is not obviously safe to load from the
8037/// specified pointer, we do a quick local scan of the basic block containing
8038/// ScanFrom, to determine if the address is already accessed.
8039static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8040 // If it is an alloca or global variable, it is always safe to load from.
8041 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8042
8043 // Otherwise, be a little bit agressive by scanning the local block where we
8044 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008045 // from/to. If so, the previous load or store would have already trapped,
8046 // so there is no harm doing an extra load (also, CSE will later eliminate
8047 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008048 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8049
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008050 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008051 --BBI;
8052
8053 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8054 if (LI->getOperand(0) == V) return true;
8055 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8056 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008057
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008058 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008059 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008060}
8061
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008062Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8063 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008064
Chris Lattnera9d84e32005-05-01 04:24:53 +00008065 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008066 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008067 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8068 return Res;
8069
8070 // None of the following transforms are legal for volatile loads.
8071 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008072
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008073 if (&LI.getParent()->front() != &LI) {
8074 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008075 // If the instruction immediately before this is a store to the same
8076 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008077 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8078 if (SI->getOperand(1) == LI.getOperand(0))
8079 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008080 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8081 if (LIB->getOperand(0) == LI.getOperand(0))
8082 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008083 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008084
8085 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8086 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8087 isa<UndefValue>(GEPI->getOperand(0))) {
8088 // Insert a new store to null instruction before the load to indicate
8089 // that this code is not reachable. We do this instead of inserting
8090 // an unreachable instruction directly because we cannot modify the
8091 // CFG.
8092 new StoreInst(UndefValue::get(LI.getType()),
8093 Constant::getNullValue(Op->getType()), &LI);
8094 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8095 }
8096
Chris Lattner81a7a232004-10-16 18:11:37 +00008097 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008098 // load null/undef -> undef
8099 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008100 // Insert a new store to null instruction before the load to indicate that
8101 // this code is not reachable. We do this instead of inserting an
8102 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008103 new StoreInst(UndefValue::get(LI.getType()),
8104 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008105 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008106 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008107
Chris Lattner81a7a232004-10-16 18:11:37 +00008108 // Instcombine load (constant global) into the value loaded.
8109 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008110 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00008111 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008112
Chris Lattner81a7a232004-10-16 18:11:37 +00008113 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8114 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8115 if (CE->getOpcode() == Instruction::GetElementPtr) {
8116 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008117 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008118 if (Constant *V =
8119 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008120 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008121 if (CE->getOperand(0)->isNullValue()) {
8122 // Insert a new store to null instruction before the load to indicate
8123 // that this code is not reachable. We do this instead of inserting
8124 // an unreachable instruction directly because we cannot modify the
8125 // CFG.
8126 new StoreInst(UndefValue::get(LI.getType()),
8127 Constant::getNullValue(Op->getType()), &LI);
8128 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8129 }
8130
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008131 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008132 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8133 return Res;
8134 }
8135 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008136
Chris Lattnera9d84e32005-05-01 04:24:53 +00008137 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008138 // Change select and PHI nodes to select values instead of addresses: this
8139 // helps alias analysis out a lot, allows many others simplifications, and
8140 // exposes redundancy in the code.
8141 //
8142 // Note that we cannot do the transformation unless we know that the
8143 // introduced loads cannot trap! Something like this is valid as long as
8144 // the condition is always false: load (select bool %C, int* null, int* %G),
8145 // but it would not be valid if we transformed it to load from null
8146 // unconditionally.
8147 //
8148 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8149 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008150 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8151 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008152 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008153 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008154 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008155 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008156 return new SelectInst(SI->getCondition(), V1, V2);
8157 }
8158
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008159 // load (select (cond, null, P)) -> load P
8160 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8161 if (C->isNullValue()) {
8162 LI.setOperand(0, SI->getOperand(2));
8163 return &LI;
8164 }
8165
8166 // load (select (cond, P, null)) -> load P
8167 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8168 if (C->isNullValue()) {
8169 LI.setOperand(0, SI->getOperand(1));
8170 return &LI;
8171 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008172 }
8173 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008174 return 0;
8175}
8176
Reid Spencere928a152007-01-19 21:20:31 +00008177/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00008178/// when possible.
8179static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8180 User *CI = cast<User>(SI.getOperand(1));
8181 Value *CastOp = CI->getOperand(0);
8182
8183 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8184 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8185 const Type *SrcPTy = SrcTy->getElementType();
8186
Reid Spencer31a4ef42007-01-22 05:51:25 +00008187 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008188 // If the source is an array, the code below will not succeed. Check to
8189 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8190 // constants.
8191 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8192 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8193 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008194 Value* Idxs[2];
8195 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8196 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00008197 SrcTy = cast<PointerType>(CastOp->getType());
8198 SrcPTy = SrcTy->getElementType();
8199 }
8200
Reid Spencer9a4bed02007-01-20 23:35:48 +00008201 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8202 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8203 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008204
8205 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00008206 // the same size. Instead of casting the pointer before
8207 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00008208 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008209 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00008210 Instruction::CastOps opcode = Instruction::BitCast;
8211 const Type* CastSrcTy = SIOp0->getType();
8212 const Type* CastDstTy = SrcPTy;
8213 if (isa<PointerType>(CastDstTy)) {
8214 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008215 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00008216 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008217 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008218 opcode = Instruction::PtrToInt;
8219 }
8220 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00008221 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008222 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008223 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00008224 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8225 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008226 return new StoreInst(NewCast, CastOp);
8227 }
8228 }
8229 }
8230 return 0;
8231}
8232
Chris Lattner31f486c2005-01-31 05:36:43 +00008233Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8234 Value *Val = SI.getOperand(0);
8235 Value *Ptr = SI.getOperand(1);
8236
8237 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008238 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008239 ++NumCombined;
8240 return 0;
8241 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00008242
8243 // If the RHS is an alloca with a single use, zapify the store, making the
8244 // alloca dead.
8245 if (Ptr->hasOneUse()) {
8246 if (isa<AllocaInst>(Ptr)) {
8247 EraseInstFromFunction(SI);
8248 ++NumCombined;
8249 return 0;
8250 }
8251
8252 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8253 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8254 GEP->getOperand(0)->hasOneUse()) {
8255 EraseInstFromFunction(SI);
8256 ++NumCombined;
8257 return 0;
8258 }
8259 }
Chris Lattner31f486c2005-01-31 05:36:43 +00008260
Chris Lattner5997cf92006-02-08 03:25:32 +00008261 // Do really simple DSE, to catch cases where there are several consequtive
8262 // stores to the same location, separated by a few arithmetic operations. This
8263 // situation often occurs with bitfield accesses.
8264 BasicBlock::iterator BBI = &SI;
8265 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8266 --ScanInsts) {
8267 --BBI;
8268
8269 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8270 // Prev store isn't volatile, and stores to the same location?
8271 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8272 ++NumDeadStore;
8273 ++BBI;
8274 EraseInstFromFunction(*PrevSI);
8275 continue;
8276 }
8277 break;
8278 }
8279
Chris Lattnerdab43b22006-05-26 19:19:20 +00008280 // If this is a load, we have to stop. However, if the loaded value is from
8281 // the pointer we're loading and is producing the pointer we're storing,
8282 // then *this* store is dead (X = load P; store X -> P).
8283 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8284 if (LI == Val && LI->getOperand(0) == Ptr) {
8285 EraseInstFromFunction(SI);
8286 ++NumCombined;
8287 return 0;
8288 }
8289 // Otherwise, this is a load from some other location. Stores before it
8290 // may not be dead.
8291 break;
8292 }
8293
Chris Lattner5997cf92006-02-08 03:25:32 +00008294 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008295 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008296 break;
8297 }
8298
8299
8300 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008301
8302 // store X, null -> turns into 'unreachable' in SimplifyCFG
8303 if (isa<ConstantPointerNull>(Ptr)) {
8304 if (!isa<UndefValue>(Val)) {
8305 SI.setOperand(0, UndefValue::get(Val->getType()));
8306 if (Instruction *U = dyn_cast<Instruction>(Val))
8307 WorkList.push_back(U); // Dropped a use.
8308 ++NumCombined;
8309 }
8310 return 0; // Do not modify these!
8311 }
8312
8313 // store undef, Ptr -> noop
8314 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008315 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008316 ++NumCombined;
8317 return 0;
8318 }
8319
Chris Lattner72684fe2005-01-31 05:51:45 +00008320 // If the pointer destination is a cast, see if we can fold the cast into the
8321 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008322 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008323 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8324 return Res;
8325 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008326 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008327 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8328 return Res;
8329
Chris Lattner219175c2005-09-12 23:23:25 +00008330
8331 // If this store is the last instruction in the basic block, and if the block
8332 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008333 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008334 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8335 if (BI->isUnconditional()) {
8336 // Check to see if the successor block has exactly two incoming edges. If
8337 // so, see if the other predecessor contains a store to the same location.
8338 // if so, insert a PHI node (if needed) and move the stores down.
8339 BasicBlock *Dest = BI->getSuccessor(0);
8340
8341 pred_iterator PI = pred_begin(Dest);
8342 BasicBlock *Other = 0;
8343 if (*PI != BI->getParent())
8344 Other = *PI;
8345 ++PI;
8346 if (PI != pred_end(Dest)) {
8347 if (*PI != BI->getParent())
8348 if (Other)
8349 Other = 0;
8350 else
8351 Other = *PI;
8352 if (++PI != pred_end(Dest))
8353 Other = 0;
8354 }
8355 if (Other) { // If only one other pred...
8356 BBI = Other->getTerminator();
8357 // Make sure this other block ends in an unconditional branch and that
8358 // there is an instruction before the branch.
8359 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8360 BBI != Other->begin()) {
8361 --BBI;
8362 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8363
8364 // If this instruction is a store to the same location.
8365 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8366 // Okay, we know we can perform this transformation. Insert a PHI
8367 // node now if we need it.
8368 Value *MergedVal = OtherStore->getOperand(0);
8369 if (MergedVal != SI.getOperand(0)) {
8370 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8371 PN->reserveOperandSpace(2);
8372 PN->addIncoming(SI.getOperand(0), SI.getParent());
8373 PN->addIncoming(OtherStore->getOperand(0), Other);
8374 MergedVal = InsertNewInstBefore(PN, Dest->front());
8375 }
8376
8377 // Advance to a place where it is safe to insert the new store and
8378 // insert it.
8379 BBI = Dest->begin();
8380 while (isa<PHINode>(BBI)) ++BBI;
8381 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8382 OtherStore->isVolatile()), *BBI);
8383
8384 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008385 EraseInstFromFunction(SI);
8386 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008387 ++NumCombined;
8388 return 0;
8389 }
8390 }
8391 }
8392 }
8393
Chris Lattner31f486c2005-01-31 05:36:43 +00008394 return 0;
8395}
8396
8397
Chris Lattner9eef8a72003-06-04 04:46:00 +00008398Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8399 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008400 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008401 BasicBlock *TrueDest;
8402 BasicBlock *FalseDest;
8403 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8404 !isa<Constant>(X)) {
8405 // Swap Destinations and condition...
8406 BI.setCondition(X);
8407 BI.setSuccessor(0, FalseDest);
8408 BI.setSuccessor(1, TrueDest);
8409 return &BI;
8410 }
8411
Reid Spencer266e42b2006-12-23 06:05:41 +00008412 // Cannonicalize fcmp_one -> fcmp_oeq
8413 FCmpInst::Predicate FPred; Value *Y;
8414 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8415 TrueDest, FalseDest)))
8416 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8417 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8418 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Chris Lattnerd4252a72004-07-30 07:50:03 +00008419 std::string Name = I->getName(); I->setName("");
Reid Spencer266e42b2006-12-23 06:05:41 +00008420 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8421 Value *NewSCC = new FCmpInst(NewPred, X, Y, Name, I);
8422 // Swap Destinations and condition...
8423 BI.setCondition(NewSCC);
8424 BI.setSuccessor(0, FalseDest);
8425 BI.setSuccessor(1, TrueDest);
8426 removeFromWorkList(I);
8427 I->getParent()->getInstList().erase(I);
8428 WorkList.push_back(cast<Instruction>(NewSCC));
8429 return &BI;
8430 }
8431
8432 // Cannonicalize icmp_ne -> icmp_eq
8433 ICmpInst::Predicate IPred;
8434 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8435 TrueDest, FalseDest)))
8436 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8437 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8438 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8439 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8440 std::string Name = I->getName(); I->setName("");
8441 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8442 Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00008443 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008444 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008445 BI.setSuccessor(0, FalseDest);
8446 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00008447 removeFromWorkList(I);
8448 I->getParent()->getInstList().erase(I);
8449 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00008450 return &BI;
8451 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008452
Chris Lattner9eef8a72003-06-04 04:46:00 +00008453 return 0;
8454}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008455
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008456Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8457 Value *Cond = SI.getCondition();
8458 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8459 if (I->getOpcode() == Instruction::Add)
8460 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8461 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8462 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008463 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008464 AddRHS));
8465 SI.setOperand(0, I->getOperand(0));
8466 WorkList.push_back(I);
8467 return &SI;
8468 }
8469 }
8470 return 0;
8471}
8472
Chris Lattner6bc98652006-03-05 00:22:33 +00008473/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8474/// is to leave as a vector operation.
8475static bool CheapToScalarize(Value *V, bool isConstant) {
8476 if (isa<ConstantAggregateZero>(V))
8477 return true;
8478 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8479 if (isConstant) return true;
8480 // If all elts are the same, we can extract.
8481 Constant *Op0 = C->getOperand(0);
8482 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8483 if (C->getOperand(i) != Op0)
8484 return false;
8485 return true;
8486 }
8487 Instruction *I = dyn_cast<Instruction>(V);
8488 if (!I) return false;
8489
8490 // Insert element gets simplified to the inserted element or is deleted if
8491 // this is constant idx extract element and its a constant idx insertelt.
8492 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8493 isa<ConstantInt>(I->getOperand(2)))
8494 return true;
8495 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8496 return true;
8497 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8498 if (BO->hasOneUse() &&
8499 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8500 CheapToScalarize(BO->getOperand(1), isConstant)))
8501 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008502 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8503 if (CI->hasOneUse() &&
8504 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8505 CheapToScalarize(CI->getOperand(1), isConstant)))
8506 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008507
8508 return false;
8509}
8510
Chris Lattner12249be2006-05-25 23:48:38 +00008511/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8512/// elements into values that are larger than the #elts in the input.
8513static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8514 unsigned NElts = SVI->getType()->getNumElements();
8515 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8516 return std::vector<unsigned>(NElts, 0);
8517 if (isa<UndefValue>(SVI->getOperand(2)))
8518 return std::vector<unsigned>(NElts, 2*NElts);
8519
8520 std::vector<unsigned> Result;
8521 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8522 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8523 if (isa<UndefValue>(CP->getOperand(i)))
8524 Result.push_back(NElts*2); // undef -> 8
8525 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008526 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008527 return Result;
8528}
8529
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008530/// FindScalarElement - Given a vector and an element number, see if the scalar
8531/// value is already around as a register, for example if it were inserted then
8532/// extracted from the vector.
8533static Value *FindScalarElement(Value *V, unsigned EltNo) {
8534 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8535 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008536 unsigned Width = PTy->getNumElements();
8537 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008538 return UndefValue::get(PTy->getElementType());
8539
8540 if (isa<UndefValue>(V))
8541 return UndefValue::get(PTy->getElementType());
8542 else if (isa<ConstantAggregateZero>(V))
8543 return Constant::getNullValue(PTy->getElementType());
8544 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8545 return CP->getOperand(EltNo);
8546 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8547 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008548 if (!isa<ConstantInt>(III->getOperand(2)))
8549 return 0;
8550 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008551
8552 // If this is an insert to the element we are looking for, return the
8553 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008554 if (EltNo == IIElt)
8555 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008556
8557 // Otherwise, the insertelement doesn't modify the value, recurse on its
8558 // vector input.
8559 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008560 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008561 unsigned InEl = getShuffleMask(SVI)[EltNo];
8562 if (InEl < Width)
8563 return FindScalarElement(SVI->getOperand(0), InEl);
8564 else if (InEl < Width*2)
8565 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8566 else
8567 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008568 }
8569
8570 // Otherwise, we don't know.
8571 return 0;
8572}
8573
Robert Bocchinoa8352962006-01-13 22:48:06 +00008574Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008575
Chris Lattner92346c32006-03-31 18:25:14 +00008576 // If packed val is undef, replace extract with scalar undef.
8577 if (isa<UndefValue>(EI.getOperand(0)))
8578 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8579
8580 // If packed val is constant 0, replace extract with scalar 0.
8581 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8582 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8583
Robert Bocchinoa8352962006-01-13 22:48:06 +00008584 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8585 // If packed val is constant with uniform operands, replace EI
8586 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008587 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008588 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008589 if (C->getOperand(i) != op0) {
8590 op0 = 0;
8591 break;
8592 }
8593 if (op0)
8594 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008595 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008596
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008597 // If extracting a specified index from the vector, see if we can recursively
8598 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008599 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008600 // This instruction only demands the single element from the input vector.
8601 // If the input vector has a single use, simplify it based on this use
8602 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008603 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008604 if (EI.getOperand(0)->hasOneUse()) {
8605 uint64_t UndefElts;
8606 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008607 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008608 UndefElts)) {
8609 EI.setOperand(0, V);
8610 return &EI;
8611 }
8612 }
8613
Reid Spencere0fc4df2006-10-20 07:07:24 +00008614 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008615 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008616 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008617
Chris Lattner83f65782006-05-25 22:53:38 +00008618 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008619 if (I->hasOneUse()) {
8620 // Push extractelement into predecessor operation if legal and
8621 // profitable to do so
8622 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008623 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8624 if (CheapToScalarize(BO, isConstantElt)) {
8625 ExtractElementInst *newEI0 =
8626 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8627 EI.getName()+".lhs");
8628 ExtractElementInst *newEI1 =
8629 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8630 EI.getName()+".rhs");
8631 InsertNewInstBefore(newEI0, EI);
8632 InsertNewInstBefore(newEI1, EI);
8633 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8634 }
Reid Spencerde46e482006-11-02 20:25:50 +00008635 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008636 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008637 PointerType::get(EI.getType()), EI);
8638 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008639 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008640 InsertNewInstBefore(GEP, EI);
8641 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008642 }
8643 }
8644 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8645 // Extracting the inserted element?
8646 if (IE->getOperand(2) == EI.getOperand(1))
8647 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8648 // If the inserted and extracted elements are constants, they must not
8649 // be the same value, extract from the pre-inserted value instead.
8650 if (isa<Constant>(IE->getOperand(2)) &&
8651 isa<Constant>(EI.getOperand(1))) {
8652 AddUsesToWorkList(EI);
8653 EI.setOperand(0, IE->getOperand(0));
8654 return &EI;
8655 }
8656 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8657 // If this is extracting an element from a shufflevector, figure out where
8658 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008659 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8660 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008661 Value *Src;
8662 if (SrcIdx < SVI->getType()->getNumElements())
8663 Src = SVI->getOperand(0);
8664 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8665 SrcIdx -= SVI->getType()->getNumElements();
8666 Src = SVI->getOperand(1);
8667 } else {
8668 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008669 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008670 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008671 }
8672 }
Chris Lattner83f65782006-05-25 22:53:38 +00008673 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008674 return 0;
8675}
8676
Chris Lattner90951862006-04-16 00:51:47 +00008677/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8678/// elements from either LHS or RHS, return the shuffle mask and true.
8679/// Otherwise, return false.
8680static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8681 std::vector<Constant*> &Mask) {
8682 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8683 "Invalid CollectSingleShuffleElements");
8684 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8685
8686 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008687 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00008688 return true;
8689 } else if (V == LHS) {
8690 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008691 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00008692 return true;
8693 } else if (V == RHS) {
8694 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008695 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008696 return true;
8697 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8698 // If this is an insert of an extract from some other vector, include it.
8699 Value *VecOp = IEI->getOperand(0);
8700 Value *ScalarOp = IEI->getOperand(1);
8701 Value *IdxOp = IEI->getOperand(2);
8702
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008703 if (!isa<ConstantInt>(IdxOp))
8704 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008705 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008706
8707 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8708 // Okay, we can handle this if the vector we are insertinting into is
8709 // transitively ok.
8710 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8711 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00008712 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008713 return true;
8714 }
8715 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8716 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008717 EI->getOperand(0)->getType() == V->getType()) {
8718 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008719 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008720
8721 // This must be extracting from either LHS or RHS.
8722 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8723 // Okay, we can handle this if the vector we are insertinting into is
8724 // transitively ok.
8725 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8726 // If so, update the mask to reflect the inserted value.
8727 if (EI->getOperand(0) == LHS) {
8728 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008729 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008730 } else {
8731 assert(EI->getOperand(0) == RHS);
8732 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008733 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008734
8735 }
8736 return true;
8737 }
8738 }
8739 }
8740 }
8741 }
8742 // TODO: Handle shufflevector here!
8743
8744 return false;
8745}
8746
8747/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8748/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8749/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008750static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008751 Value *&RHS) {
8752 assert(isa<PackedType>(V->getType()) &&
8753 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008754 "Invalid shuffle!");
8755 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8756
8757 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008758 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008759 return V;
8760 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008761 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008762 return V;
8763 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8764 // If this is an insert of an extract from some other vector, include it.
8765 Value *VecOp = IEI->getOperand(0);
8766 Value *ScalarOp = IEI->getOperand(1);
8767 Value *IdxOp = IEI->getOperand(2);
8768
8769 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8770 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8771 EI->getOperand(0)->getType() == V->getType()) {
8772 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008773 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8774 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008775
8776 // Either the extracted from or inserted into vector must be RHSVec,
8777 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008778 if (EI->getOperand(0) == RHS || RHS == 0) {
8779 RHS = EI->getOperand(0);
8780 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008781 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008782 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008783 return V;
8784 }
8785
Chris Lattner90951862006-04-16 00:51:47 +00008786 if (VecOp == RHS) {
8787 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008788 // Everything but the extracted element is replaced with the RHS.
8789 for (unsigned i = 0; i != NumElts; ++i) {
8790 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00008791 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008792 }
8793 return V;
8794 }
Chris Lattner90951862006-04-16 00:51:47 +00008795
8796 // If this insertelement is a chain that comes from exactly these two
8797 // vectors, return the vector and the effective shuffle.
8798 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8799 return EI->getOperand(0);
8800
Chris Lattner39fac442006-04-15 01:39:45 +00008801 }
8802 }
8803 }
Chris Lattner90951862006-04-16 00:51:47 +00008804 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008805
8806 // Otherwise, can't do anything fancy. Return an identity vector.
8807 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008808 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008809 return V;
8810}
8811
8812Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8813 Value *VecOp = IE.getOperand(0);
8814 Value *ScalarOp = IE.getOperand(1);
8815 Value *IdxOp = IE.getOperand(2);
8816
8817 // If the inserted element was extracted from some other vector, and if the
8818 // indexes are constant, try to turn this into a shufflevector operation.
8819 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8820 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8821 EI->getOperand(0)->getType() == IE.getType()) {
8822 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008823 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8824 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008825
8826 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8827 return ReplaceInstUsesWith(IE, VecOp);
8828
8829 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8830 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8831
8832 // If we are extracting a value from a vector, then inserting it right
8833 // back into the same place, just use the input vector.
8834 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8835 return ReplaceInstUsesWith(IE, VecOp);
8836
8837 // We could theoretically do this for ANY input. However, doing so could
8838 // turn chains of insertelement instructions into a chain of shufflevector
8839 // instructions, and right now we do not merge shufflevectors. As such,
8840 // only do this in a situation where it is clear that there is benefit.
8841 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8842 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8843 // the values of VecOp, except then one read from EIOp0.
8844 // Build a new shuffle mask.
8845 std::vector<Constant*> Mask;
8846 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00008847 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008848 else {
8849 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00008850 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00008851 NumVectorElts));
8852 }
Reid Spencerc635f472006-12-31 05:48:39 +00008853 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008854 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8855 ConstantPacked::get(Mask));
8856 }
8857
8858 // If this insertelement isn't used by some other insertelement, turn it
8859 // (and any insertelements it points to), into one big shuffle.
8860 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8861 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008862 Value *RHS = 0;
8863 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8864 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8865 // We now have a shuffle of LHS, RHS, Mask.
8866 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008867 }
8868 }
8869 }
8870
8871 return 0;
8872}
8873
8874
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008875Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8876 Value *LHS = SVI.getOperand(0);
8877 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008878 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008879
8880 bool MadeChange = false;
8881
Chris Lattner2deeaea2006-10-05 06:55:50 +00008882 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008883 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008884 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8885
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008886 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00008887 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008888 if (isa<UndefValue>(SVI.getOperand(1))) {
8889 // Scan to see if there are any references to the RHS. If so, replace them
8890 // with undef element refs and set MadeChange to true.
8891 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8892 if (Mask[i] >= e && Mask[i] != 2*e) {
8893 Mask[i] = 2*e;
8894 MadeChange = true;
8895 }
8896 }
8897
8898 if (MadeChange) {
8899 // Remap any references to RHS to use LHS.
8900 std::vector<Constant*> Elts;
8901 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8902 if (Mask[i] == 2*e)
8903 Elts.push_back(UndefValue::get(Type::Int32Ty));
8904 else
8905 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8906 }
8907 SVI.setOperand(2, ConstantPacked::get(Elts));
8908 }
8909 }
Chris Lattner39fac442006-04-15 01:39:45 +00008910
Chris Lattner12249be2006-05-25 23:48:38 +00008911 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8912 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8913 if (LHS == RHS || isa<UndefValue>(LHS)) {
8914 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008915 // shuffle(undef,undef,mask) -> undef.
8916 return ReplaceInstUsesWith(SVI, LHS);
8917 }
8918
Chris Lattner12249be2006-05-25 23:48:38 +00008919 // Remap any references to RHS to use LHS.
8920 std::vector<Constant*> Elts;
8921 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008922 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00008923 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00008924 else {
8925 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8926 (Mask[i] < e && isa<UndefValue>(LHS)))
8927 Mask[i] = 2*e; // Turn into undef.
8928 else
8929 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00008930 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008931 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008932 }
Chris Lattner12249be2006-05-25 23:48:38 +00008933 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008934 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008935 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008936 LHS = SVI.getOperand(0);
8937 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008938 MadeChange = true;
8939 }
8940
Chris Lattner0e477162006-05-26 00:29:06 +00008941 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008942 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008943
Chris Lattner12249be2006-05-25 23:48:38 +00008944 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8945 if (Mask[i] >= e*2) continue; // Ignore undef values.
8946 // Is this an identity shuffle of the LHS value?
8947 isLHSID &= (Mask[i] == i);
8948
8949 // Is this an identity shuffle of the RHS value?
8950 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008951 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008952
Chris Lattner12249be2006-05-25 23:48:38 +00008953 // Eliminate identity shuffles.
8954 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8955 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008956
Chris Lattner0e477162006-05-26 00:29:06 +00008957 // If the LHS is a shufflevector itself, see if we can combine it with this
8958 // one without producing an unusual shuffle. Here we are really conservative:
8959 // we are absolutely afraid of producing a shuffle mask not in the input
8960 // program, because the code gen may not be smart enough to turn a merged
8961 // shuffle into two specific shuffles: it may produce worse code. As such,
8962 // we only merge two shuffles if the result is one of the two input shuffle
8963 // masks. In this case, merging the shuffles just removes one instruction,
8964 // which we know is safe. This is good for things like turning:
8965 // (splat(splat)) -> splat.
8966 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8967 if (isa<UndefValue>(RHS)) {
8968 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8969
8970 std::vector<unsigned> NewMask;
8971 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8972 if (Mask[i] >= 2*e)
8973 NewMask.push_back(2*e);
8974 else
8975 NewMask.push_back(LHSMask[Mask[i]]);
8976
8977 // If the result mask is equal to the src shuffle or this shuffle mask, do
8978 // the replacement.
8979 if (NewMask == LHSMask || NewMask == Mask) {
8980 std::vector<Constant*> Elts;
8981 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8982 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00008983 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00008984 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00008985 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008986 }
8987 }
8988 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8989 LHSSVI->getOperand(1),
8990 ConstantPacked::get(Elts));
8991 }
8992 }
8993 }
Chris Lattner4284f642007-01-30 22:32:46 +00008994
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008995 return MadeChange ? &SVI : 0;
8996}
8997
8998
Robert Bocchinoa8352962006-01-13 22:48:06 +00008999
Chris Lattner99f48c62002-09-02 04:59:56 +00009000void InstCombiner::removeFromWorkList(Instruction *I) {
9001 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
9002 WorkList.end());
9003}
9004
Chris Lattner39c98bb2004-12-08 23:43:58 +00009005
9006/// TryToSinkInstruction - Try to move the specified instruction from its
9007/// current block into the beginning of DestBlock, which can only happen if it's
9008/// safe to move the instruction past all of the instructions between it and the
9009/// end of its block.
9010static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9011 assert(I->hasOneUse() && "Invariants didn't hold!");
9012
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009013 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9014 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009015
Chris Lattner39c98bb2004-12-08 23:43:58 +00009016 // Do not sink alloca instructions out of the entry block.
9017 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9018 return false;
9019
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009020 // We can only sink load instructions if there is nothing between the load and
9021 // the end of block that could change the value.
9022 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009023 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9024 Scan != E; ++Scan)
9025 if (Scan->mayWriteToMemory())
9026 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009027 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009028
9029 BasicBlock::iterator InsertPos = DestBlock->begin();
9030 while (isa<PHINode>(InsertPos)) ++InsertPos;
9031
Chris Lattner9f269e42005-08-08 19:11:57 +00009032 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009033 ++NumSunkInst;
9034 return true;
9035}
9036
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009037
9038/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9039/// all reachable code to the worklist.
9040///
9041/// This has a couple of tricks to make the code faster and more powerful. In
9042/// particular, we constant fold and DCE instructions as we go, to avoid adding
9043/// them to the worklist (this significantly speeds up instcombine on code where
9044/// many instructions are dead or constant). Additionally, if we find a branch
9045/// whose condition is a known constant, we only visit the reachable successors.
9046///
9047static void AddReachableCodeToWorklist(BasicBlock *BB,
9048 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00009049 std::vector<Instruction*> &WorkList,
9050 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009051 // We have now visited this block! If we've already been here, bail out.
9052 if (!Visited.insert(BB).second) return;
9053
9054 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9055 Instruction *Inst = BBI++;
9056
9057 // DCE instruction if trivially dead.
9058 if (isInstructionTriviallyDead(Inst)) {
9059 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009060 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009061 Inst->eraseFromParent();
9062 continue;
9063 }
9064
9065 // ConstantProp instruction if trivially constant.
Chris Lattnere3eda252007-01-30 23:16:15 +00009066 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009067 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009068 Inst->replaceAllUsesWith(C);
9069 ++NumConstProp;
9070 Inst->eraseFromParent();
9071 continue;
9072 }
9073
9074 WorkList.push_back(Inst);
9075 }
9076
9077 // Recursively visit successors. If this is a branch or switch on a constant,
9078 // only visit the reachable successor.
9079 TerminatorInst *TI = BB->getTerminator();
9080 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00009081 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
Reid Spencercddc9df2007-01-12 04:24:46 +00009082 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00009083 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9084 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009085 return;
9086 }
9087 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9088 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9089 // See if this is an explicit destination.
9090 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9091 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009092 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009093 return;
9094 }
9095
9096 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00009097 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009098 return;
9099 }
9100 }
9101
9102 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00009103 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009104}
9105
Chris Lattner113f4f42002-06-25 16:13:24 +00009106bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00009107 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009108 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00009109
Chris Lattner4ed40f72005-07-07 20:40:38 +00009110 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009111 // Do a depth-first traversal of the function, populate the worklist with
9112 // the reachable instructions. Ignore blocks that are not reachable. Keep
9113 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00009114 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00009115 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009116
Chris Lattner4ed40f72005-07-07 20:40:38 +00009117 // Do a quick scan over the function. If we find any blocks that are
9118 // unreachable, remove any instructions inside of them. This prevents
9119 // the instcombine code from having to deal with some bad special cases.
9120 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9121 if (!Visited.count(BB)) {
9122 Instruction *Term = BB->getTerminator();
9123 while (Term != BB->begin()) { // Remove instrs bottom-up
9124 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009125
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009126 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009127 ++NumDeadInst;
9128
9129 if (!I->use_empty())
9130 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9131 I->eraseFromParent();
9132 }
9133 }
9134 }
Chris Lattnerca081252001-12-14 16:52:21 +00009135
9136 while (!WorkList.empty()) {
9137 Instruction *I = WorkList.back(); // Get an instruction from the worklist
9138 WorkList.pop_back();
9139
Chris Lattner1443bc52006-05-11 17:11:52 +00009140 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009141 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009142 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009143 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009144 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009145 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009146
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009147 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009148
9149 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009150 removeFromWorkList(I);
9151 continue;
9152 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009153
Chris Lattner1443bc52006-05-11 17:11:52 +00009154 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +00009155 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009156 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009157
Chris Lattner1443bc52006-05-11 17:11:52 +00009158 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009159 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009160 ReplaceInstUsesWith(*I, C);
9161
Chris Lattner99f48c62002-09-02 04:59:56 +00009162 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009163 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00009164 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009165 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009166 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009167
Chris Lattner39c98bb2004-12-08 23:43:58 +00009168 // See if we can trivially sink this instruction to a successor basic block.
9169 if (I->hasOneUse()) {
9170 BasicBlock *BB = I->getParent();
9171 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9172 if (UserParent != BB) {
9173 bool UserIsSuccessor = false;
9174 // See if the user is one of our successors.
9175 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9176 if (*SI == UserParent) {
9177 UserIsSuccessor = true;
9178 break;
9179 }
9180
9181 // If the user is one of our immediate successors, and if that successor
9182 // only has us as a predecessors (we'd have to split the critical edge
9183 // otherwise), we can keep going.
9184 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9185 next(pred_begin(UserParent)) == pred_end(UserParent))
9186 // Okay, the CFG is simple enough, try to sink this instruction.
9187 Changed |= TryToSinkInstruction(I, UserParent);
9188 }
9189 }
9190
Chris Lattnerca081252001-12-14 16:52:21 +00009191 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009192 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009193 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009194 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009195 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009196 DOUT << "IC: Old = " << *I
9197 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009198
Chris Lattner396dbfe2004-06-09 05:08:07 +00009199 // Everything uses the new instruction now.
9200 I->replaceAllUsesWith(Result);
9201
9202 // Push the new instruction and any users onto the worklist.
9203 WorkList.push_back(Result);
9204 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009205
9206 // Move the name to the new instruction first...
9207 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00009208 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009209
9210 // Insert the new instruction into the basic block...
9211 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009212 BasicBlock::iterator InsertPos = I;
9213
9214 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9215 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9216 ++InsertPos;
9217
9218 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009219
Chris Lattner63d75af2004-05-01 23:27:23 +00009220 // Make sure that we reprocess all operands now that we reduced their
9221 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009222 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9223 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9224 WorkList.push_back(OpI);
9225
Chris Lattner396dbfe2004-06-09 05:08:07 +00009226 // Instructions can end up on the worklist more than once. Make sure
9227 // we do not process an instruction that has been deleted.
9228 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009229
9230 // Erase the old instruction.
9231 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009232 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009233 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009234
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009235 // If the instruction was modified, it's possible that it is now dead.
9236 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009237 if (isInstructionTriviallyDead(I)) {
9238 // Make sure we process all operands now that we are reducing their
9239 // use counts.
9240 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9241 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9242 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009243
Chris Lattner63d75af2004-05-01 23:27:23 +00009244 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009245 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009246 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009247 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009248 } else {
9249 WorkList.push_back(Result);
9250 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009251 }
Chris Lattner053c0932002-05-14 15:24:07 +00009252 }
Chris Lattner260ab202002-04-18 17:39:14 +00009253 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009254 }
9255 }
9256
Chris Lattner260ab202002-04-18 17:39:14 +00009257 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009258}
9259
Brian Gaeke38b79e82004-07-27 17:43:21 +00009260FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009261 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009262}
Brian Gaeke960707c2003-11-11 22:41:34 +00009263